body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>Case 1: rank1_naming</p>
<p>This function takes two arguments </p>
<ul>
<li>list_proteins_pattern_available </li>
<li>best_match_protein_name </li>
</ul>
<blockquote>
<p>Objective: Extract the three letter pattern from the both arguments.
Match the pattern and keep only the matched items. Extract the numbers
from <code>list_proteins_pattern_available</code> and also sort it. Find the
maximum number from the collected numbers and add <code>1</code> to get the next
number. </p>
</blockquote>
<p>Please let me know if you have any questions.</p>
<p>Can you point ways to improve this script?</p>
<pre><code>import re
def case_rank1_naming(list_proteins_pattern_available, best_match_protein_name):
#This will store the list of numbers
available_list_numbers = []
#extract the three letter pattern
protein_pattern = re.search(r"[A-Z]{1}[a-z]{2}", best_match_protein_name)
protein_pattern = protein_pattern.group()
#extract the numbers
for name in list_proteins_pattern_available:
pattern = re.search(r"[A-Z]{1}[a-z]{2}\d{1,3}", name)
number = re.search(r"\d{1,3}", pattern.group())
available_list_numbers.append(number.group())
#Convert all the string numbers to integers
available_list_numbers = [int(x) for x in available_list_numbers]
#Sort the available number. Just realized I use two times sort function.
available_list_numbers.sort()
# Sort the available number, get the maximum number and add one to get next number
# Example: result will be 50
primary_number_prediction = int(max(sorted(available_list_numbers))) + 1
#Add the protein pattern, the next predicted number and 'Aa1' at the suffix
predicted_name = protein_pattern + str(primary_number_prediction) + 'Aa1'
return predicted_name
list_proteins_pattern_available = ['Xpp1Aa1', 'Xpp2Aa1', 'Xpp35Aa1', 'Xpp35Ab1', 'Xpp35Ac1', 'Xpp35Ba1', 'Xpp36Aa1', 'Xpp49Aa1', 'Xpp49Ab1']
best_match_protein_name = 'Xpp35Ba1'
predicted_name = case_rank1_naming(list_proteins_pattern_available, best_match_protein_name)
print(predicted_name)
#Xpp50Aa1
</code></pre>
|
[] |
[
{
"body": "<p>I'll show an example implementation first, and then describe it:</p>\n\n<pre><code>from typing import Iterable\nimport re\n\n\ndef case_rank1_naming(proteins_available: Iterable[str], best_match_protein_name: str) -> str:\n # extract the three-letter pattern\n protein_pattern = re.search(r\"[A-Z][a-z]{2}\", best_match_protein_name).group()\n\n # extract the numbers\n best_number = max(\n int(re.search(r\"[A-Z][a-z]{2}(\\d{1,3})\", name)[1])\n for name in proteins_available\n )\n\n # Add the protein pattern, the next predicted number and 'Aa1' at the suffix\n return f'{protein_pattern}{best_number + 1}Aa1'\n\n\ndef main():\n proteins_available = (\n 'Xpp1Aa1', 'Xpp2Aa1', 'Xpp35Aa1', 'Xpp35Ab1', 'Xpp35Ac1',\n 'Xpp35Ba1', 'Xpp36Aa1', 'Xpp49Aa1', 'Xpp49Ab1'\n )\n best_match_protein_name = 'Xpp35Ba1'\n predicted_name = case_rank1_naming(proteins_available, best_match_protein_name)\n assert predicted_name == 'Xpp50Aa1'\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<ul>\n<li>Add type hints to better-define your function signature</li>\n<li>Don't write <code>{1}</code> in a regex - you can just drop it</li>\n<li>Call <code>max</code> immediately on a generator rather than making and sorting a list</li>\n<li>Shorten your variable names. Especially don't include the type of the variable in its name. Type hints and appropriate pluralization will cover you instead.</li>\n<li>Use f-strings</li>\n<li>Have a <code>main</code> function</li>\n<li>In <code>main</code>, use a tuple for <code>proteins_available</code> instead of a list because it doesn't need to mutate</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T15:32:41.833",
"Id": "445661",
"Score": "0",
"body": "you are on a roll :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T15:46:37.993",
"Id": "445663",
"Score": "0",
"body": "Thank you. I will go through it and understand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T17:20:38.610",
"Id": "445678",
"Score": "0",
"body": "Why this step assert predicted_name == 'Xpp50Aa1'. In many cases we don't know the predicted name. right? Is this for testing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T17:22:29.700",
"Id": "445679",
"Score": "0",
"body": "Yes, it's only for testing. You'll definitely want to leave that out in general program use, and move it to a unit test."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T15:26:12.210",
"Id": "229190",
"ParentId": "229188",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229190",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T15:01:35.963",
"Id": "229188",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"regex"
],
"Title": "Extract, filter and match three letters from the given arguments and predict the name"
}
|
229188
|
<p>I am making use of C++ and SFML to make a basic Pong game. I have made it so that there are two players who can control the paddle on each side and the ball will bounce off screen and paddles except the left and right sides of screen. Player can also pause and restart the game anytime.</p>
<blockquote>
<p>My goal is to learn C++'s features such as pointers, references,
polymorphism using virtual, inheritance and memory management by
putting it in practice. Therefore, keeping that in mind, I tried to
create the game.</p>
</blockquote>
<p>I want to know how successful I have been so far and if I am in right track to achieving object oriented program. Any advice on how I can improve and criticism related to my code structure would be appreciated as I look to improve as a programmer. </p>
<p>My code: </p>
<p><strong>GameObject.h</strong></p>
<pre><code>#include <SFML/Graphics.hpp>
using namespace sf;
class GameObject
{
protected:
Vector2f position;
float speed;
RenderWindow& m_window;
public:
GameObject(float startX, float startY, RenderWindow& window);
virtual void Draw() = 0;
virtual void Update() = 0;
};
</code></pre>
<p><strong>GameObject.cpp</strong></p>
<pre><code>#include "GameObject.h"
GameObject::GameObject(float startX, float startY, sf::RenderWindow& window) : m_window(window)
{
position.x = startX;
position.y = startY;
speed = 0.3f;
}
</code></pre>
<p><strong>Paddle.h</strong></p>
<pre><code>#include <iostream>
#include "GameObject.h"
class Paddle : public GameObject
{
private:
RectangleShape paddleShape;
const int shapeWidth = 10;
const int shapeHeight = 50;
public:
Paddle(float startX, float startY, RenderWindow& window);
FloatRect getPosition();
RectangleShape getShape();
void moveUp();
void moveDown();
void HandleInput1();
void HandleInput2();
void Update() override;
void Draw() override;
};
</code></pre>
<p><strong>Paddle.cpp</strong></p>
<pre><code>#include "Paddle.h"
Paddle::Paddle(float startX, float startY, RenderWindow& window) : GameObject(startX, startY, window)
{
paddleShape.setSize(sf::Vector2f(shapeWidth, shapeHeight));
paddleShape.setPosition(position);
}
FloatRect Paddle::getPosition()
{
return paddleShape.getGlobalBounds();
}
RectangleShape Paddle::getShape()
{
return paddleShape;
}
void Paddle::moveUp()
{
position.y -= speed;
}
void Paddle::moveDown()
{
position.y += speed;
}
void Paddle::HandleInput1()
{
if (Keyboard::isKeyPressed(Keyboard::W) && (paddleShape.getPosition().y - paddleShape.getSize().y / 2 > -20.0f))
{
paddleShape.move(0.f, -speed);
}
else if (Keyboard::isKeyPressed(Keyboard::S) && (paddleShape.getPosition().y + paddleShape.getSize().y / 2 < m_window.getSize().y - 35.f))
{
paddleShape.move(0.f, speed);
}
}
void Paddle::HandleInput2()
{
if (Keyboard::isKeyPressed(Keyboard::Up) && (paddleShape.getPosition().y - paddleShape.getSize().y / 2 > -20.0f))
{
paddleShape.move(0.f, -speed);
}
else if (Keyboard::isKeyPressed(Keyboard::Down) && (paddleShape.getPosition().y + paddleShape.getSize().y / 2 < m_window.getSize().y - 35.f))
{
paddleShape.move(0.f, speed);
}
}
void Paddle::Update()
{
}
void Paddle::Draw()
{
m_window.draw(paddleShape);
}
</code></pre>
<p><strong>Ball.h</strong></p>
<pre><code>#include "GameObject.h"
#include "Paddle.h"
class Ball : public GameObject
{
private:
CircleShape ballShape;
const float radius = 10.0f;
public:
float ballAngle = 0.0f;
const float pi = 3.14159f;
public:
Ball(float startX, float startY, RenderWindow& window);
FloatRect getPosition();
CircleShape getShape();
float getRadius();
void reboundTop();
void reboundBottom();
void reboundBat();
void Update() override;
void Draw() override;
</code></pre>
<p><strong>Ball.cpp</strong></p>
<pre><code>#include "Ball.h"
Ball::Ball(float startX, float startY, RenderWindow& window) : GameObject(startX, startY, window)
{
ballShape.setRadius(radius);
ballShape.setPosition(position);
do
{
ballAngle = (std::rand() % 360) * 2 * pi / 360;
} while (std::abs(std::cos(ballAngle)) < 0.7f);
}
FloatRect Ball::getPosition()
{
return ballShape.getGlobalBounds();
}
CircleShape Ball::getShape()
{
return ballShape;
}
float Ball::getRadius()
{
return radius;
}
void Ball::reboundTop()
{
ballAngle = -ballAngle;
ballShape.setPosition(ballShape.getPosition().x, radius + 0.1f);
}
void Ball::reboundBottom()
{
ballAngle = -ballAngle;
ballShape.setPosition(ballShape.getPosition().x, m_window.getSize().y - radius - 0.1f);
}
void Ball::reboundBat()
{
}
void Ball::Update()
{
ballShape.move(std::cos(ballAngle) * (speed - 0.1), std::sin(ballAngle) * (speed - 0.1));
}
void Ball::Draw()
{
m_window.draw(ballShape);
}
</code></pre>
<p><strong>Game.h</strong></p>
<pre><code>#include <SFML/Graphics.hpp>
#include "Paddle.h"
#include "Ball.h"
using namespace sf;
class Game
{
private:
std::unique_ptr<Paddle> player1;
std::unique_ptr<Paddle> player2;
std::unique_ptr<Ball> ball;
Font font;
Text pause;
Text gameOver;
Text restart;
bool isPaused;
bool isGameOver;
bool isRestart;
public:
RenderWindow& m_window;
const unsigned int m_windowWidth;
const unsigned int m_windowHeight;
public:
Game(RenderWindow& window, const unsigned int& windowWidth, const unsigned int& windowHeight);
RenderWindow& GetWindow();
void RestartGame();
void HandleCollision();
void HandleInput();
void Update();
void Draw();
void Run();
};
</code></pre>
<p><strong>Game.cpp</strong></p>
<pre><code>#include "Game.h"
Game::Game(RenderWindow& window, const unsigned int& windowWidth, const unsigned int& windowHeight) :
m_window(window), m_windowWidth(windowWidth), m_windowHeight(windowHeight)
{
RestartGame();
font.loadFromFile("resources/American Captain.ttf");
gameOver.setFont(font);
gameOver.setCharacterSize(42);
gameOver.setFillColor(sf::Color::White);
gameOver.setStyle(sf::Text::Bold);
gameOver.setPosition((m_windowWidth / 2) - 100, m_windowHeight / 2);
pause.setFont(font);
pause.setCharacterSize(42);
pause.setFillColor(sf::Color::White);
pause.setStyle(sf::Text::Regular);
pause.setPosition((m_windowWidth / 2) - 80, m_windowHeight / 2);
restart.setFont(font);
restart.setCharacterSize(25);
restart.setFillColor(sf::Color::White);
restart.setStyle(sf::Text::Regular);
restart.setPosition((m_windowWidth / 2) - 100, (m_windowHeight / 2) + 50);
}
RenderWindow& Game::GetWindow()
{
return m_window;
}
void Game::RestartGame()
{
isPaused = false;
isGameOver = false;
isRestart = true;
gameOver.setString("");
pause.setString("");
restart.setString("");
player1 = std::make_unique<Paddle>(40, m_windowHeight / 2, m_window);
player2 = std::make_unique<Paddle>(m_windowWidth - 50, m_windowHeight / 2, m_window);
ball = std::make_unique<Ball>(m_windowWidth / 2, m_windowHeight / 2, m_window);
}
void Game::HandleCollision()
{
if (ball->getShape().getPosition().x - ball->getRadius() < 0.0f)
{
isGameOver = true;
gameOver.setString("PLAYER 2 WINS!");
restart.setString("Press R to restart\nPress Esc to Quit");
}
else if (ball->getShape().getPosition().x + ball->getRadius() > m_windowWidth)
{
isGameOver = true;
gameOver.setString("PLAYER 1 WINS!");
restart.setString("Press R to restart\nPress Esc to Quit");
}
else if (ball->getShape().getPosition().y - ball->getRadius() < 0.f)
{
ball->reboundTop();
}
else if (ball->getShape().getPosition().y + ball->getRadius() > m_windowHeight)
{
ball->reboundBottom();
}
else if (ball->getPosition().intersects(player2->getPosition()))
{
if (ball->getShape().getPosition().y > player2->getShape().getPosition().y)
ball->ballAngle = ball->pi - ball->ballAngle + (std::rand() % 20) * ball->pi / 180;
else
ball->ballAngle = ball->pi - ball->ballAngle - (std::rand() % 20) * ball->pi / 180;
ball->getShape().setPosition(player2->getShape().getPosition().x - ball->getRadius() - player2->getShape().getSize().x / 2 - 0.1f, ball->getShape().getPosition().y);
}
else if (ball->getPosition().intersects(player1->getPosition()))
{
if (ball->getShape().getPosition().y > player1->getShape().getPosition().y)
ball->ballAngle = ball->pi - ball->ballAngle + (std::rand() % 20) * ball->pi / 180;
else
ball->ballAngle = ball->pi - ball->ballAngle - (std::rand() % 20) * ball->pi / 180;
ball->getShape().setPosition(player1->getShape().getPosition().x - ball->getRadius() - player1->getShape().getSize().x / 2 - 0.1f, ball->getShape().getPosition().y);
}
}
void Game::HandleInput()
{
player1->HandleInput1();
player2->HandleInput2();
}
void Game::Update()
{
player1->Update();
player2->Update();
ball->Update();
}
void Game::Draw()
{
player1->Draw();
player2->Draw();
ball->Draw();
m_window.draw(pause);
m_window.draw(gameOver);
m_window.draw(restart);
}
void Game::Run()
{
//Game Loop
while (m_window.isOpen())
{
sf::Event event;
while (m_window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
m_window.close();
if (event.type == Event::KeyPressed && event.key.code == sf::Keyboard::P)
{
if(!isGameOver)
isPaused = !isPaused;
}
if (event.type == Event::KeyPressed && event.key.code == sf::Keyboard::R)
RestartGame();
}
m_window.clear();
HandleCollision();
if (!isPaused)
{
HandleInput();
Update();
}
if (isPaused)
pause.setString("Game Paused");
else
pause.setString("");
Draw();
m_window.display();
}
}
</code></pre>
<p><strong>Main.cpp</strong></p>
<pre><code>#include <iostream>
#include <memory>
#include <SFML/Graphics.hpp>
#include "Paddle.h"
#include "Game.h"
int main()
{
const unsigned int windowWidth = 800;
const unsigned int windowHeight = 600;
RenderWindow window(VideoMode(windowWidth, windowHeight), "PONG GAME");
std::unique_ptr<Game> game = std::make_unique<Game>(window, windowWidth, windowHeight);
game->Run();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T21:52:59.840",
"Id": "445866",
"Score": "1",
"body": "It appears that you have updated the description and code. Does the code work correctly to the best of your knowledge now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T13:17:58.580",
"Id": "445939",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ Yes, it does."
}
] |
[
{
"body": "<p>I am glad to see that you separated the components of the program into different source files. Here's my suggestions:</p>\n\n<h1>Game Object</h1>\n\n<p>Avoid <code>using namespace sf;</code>. Especially in a header. The problem of using-directives are especially apparent with third-party libraries — the source of the names is obfuscated and there's the risk of name clashing. For someone who doesn't know a lot about SFML (like me), I can see immediately what <code>sf::RenderWindow</code> is, but <code>RenderWindow</code> makes me wonder.</p>\n\n<p>The virtual destructor is missing.</p>\n\n<p>What's wrong with the indentation here?</p>\n\n<pre><code>protected:\nVector2f position;\nfloat speed;\nRenderWindow& m_window;\n</code></pre>\n\n<p>You should use member initializer clauses here:</p>\n\n<pre><code>GameObject::GameObject(float startX, float startY, sf::RenderWindow& window)\n : position{startX, startY}\n , speed{0.3}\n , m_window{window}\n{\n}\n</code></pre>\n\n<p>I don't see why the constructor shouldn't be taking a 2D vector directly.</p>\n\n<p>Protected members in the base class are like \"global variables\" to the inheritance hierarchy. I much prefer a pure interface:</p>\n\n<pre><code>class GameObject {\npublic:\n virtual ~GameObject() {}\n virtual void Draw() = 0;\n virtual void Update() = 0;\n};\n</code></pre>\n\n<p>It is not common to capitalize function names, but that's purely a matter of style.</p>\n\n<h1>Paddle</h1>\n\n<p>You don't use the I/O library, so omit <code>#include <iostream></code>.</p>\n\n<p><code>shapeWidth</code> and <code>shapeHeight</code> should be <code>static constexpr</code>. The constructor can be inherited.</p>\n\n<p>Now the downside of having protected members in the base class is evident: <code>paddleShape</code> stores the position, resulting in data duplication. You have to make sure the two sets of data are synchronized, which adds clutter to the code. The code looks better like this:</p>\n\n<pre><code>Paddle::Paddle(sf::Vector2f position, RenderWindow& window)\n{\n paddleShape.setSize(sf::Vector2f(shapeWidth, shapeHeight));\n paddleShape.setPosition(position);\n}\n</code></pre>\n\n<p>And if <code>RectangleShape</code> has constructors, you should use them.</p>\n\n<p>The move functions should be defined in class.</p>\n\n<h1>Ball</h1>\n\n<p>Similarly, <code>radius</code> should be a <code>static constexpr</code>. <code>pi</code> should probably be global (possibly in a namespace) until we have C++20 <code>std::numbers::pi</code>.</p>\n\n<p>The calculation of <code>ballAngle</code> can be written like this: (where <code>engine</code> is a suitable random number engine)</p>\n\n<pre><code>static const auto angle_min = std::acos(0.7);\nstatic const auto angle_max = std::acos(-0.7);\n\nstd::uniform_real_distribution<float>{angle_min, angle_max} rdist;\nballAngle = rdist(engine);\nif (std::bernoulli_distribution bdist{0.5}; bdist(engine))\n ballAngle = 2 * pi - ballAngle;\n</code></pre>\n\n<h1>Game (logic)</h1>\n\n<p>You can use <code>std::optional</code> instead of <code>std::unique_ptr</code>:</p>\n\n<pre><code>std::optional<Paddle> player1;\nstd::optional<Paddle> player2;\nstd::optional<Ball> ball;\n</code></pre>\n\n<p>and then, in <code>RestartGame</code>,</p>\n\n<pre><code>player1.emplace(40, m_windowHeight / 2, m_window);\nplayer2.emplace(m_windowWidth - 50, m_windowHeight / 2, m_window);\nball.emplace(m_windowWidth / 2, m_windowHeight / 2, m_window);\n</code></pre>\n\n<p>This also makes your code exception safe. Not particularly important in this case, I guess, but consider readability and semantic accuracy.</p>\n\n<h1>Main</h1>\n\n<p>The main code has zero reason to use dynamic memory. Use a local variable:</p>\n\n<pre><code>Game game(window, windowWidth, windowHeight);\ngame.Run();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T09:40:01.130",
"Id": "229365",
"ParentId": "229195",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229365",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T16:36:56.530",
"Id": "229195",
"Score": "1",
"Tags": [
"c++",
"beginner",
"game",
"sfml",
"pong"
],
"Title": "Basic Pong game using C++ and SFML"
}
|
229195
|
<p>I want to build Git class where i can store integers. <code>FilesSet</code> is where I store current state of integers. <code>Commits</code>' key is basically commit number so I can checkout pretty fast. <code>Hashes</code> is used for quick search of hashes that I need in commit part.</p>
<p><code>Update</code> is for updating current state of integers.</p>
<p>In <code>Commit</code> I want to save a copy of current state and do it fast. First of all I don't want to compare arrays of integers, so I calculate hash of current state. Then if <code>Hashes</code> already has that hash as a key, I add to <code>Commits</code> Pair of commitNumber and integer array that corresponds to that hash so I won't have to store another copy of array. And in <code>Hashes</code> of this key I add commit Number so I can see which commits have that hash. This one is a bottleneck for my solution.</p>
<p>In <code>Checkout</code> I basically get int that I need by arguments. I think this method is already really fast.
I need this class to be fast but I can't really provide test cases as they are hidden at my college testing system. My current solution is too slow with <code>int Commit()</code> .
Here it is :</p>
<pre><code>using System.Collections.Generic;
using System.Linq;
using System;
namespace GitTask
{
public class Git
{
int[] FilesSet { get; set; }
Dictionary<int, int[]> Commits { get; set; }
SortedList<int, List<int>> Hashes { get; set; }
public Git(int filesCount)
{
FilesSet = new int[filesCount];
Commits = new Dictionary<int, int[]>();
Hashes = new SortedList<int, List<int>>();
}
public void Update(int fileNumber, int value)
{
FilesSet[fileNumber] = value;
}
public int Commit()
{
var commitNumber = Commits.Count;
var tempHash = GetMyHashCode(FilesSet);
if (Hashes.TryGetValue(tempHash, out List<int> key))
{
Commits.Add(commitNumber, Commits[key[0]]);
Hashes[tempHash].Add(commitNumber);
return commitNumber;
}
Commits.Add(Commits.Count, FilesSet.Clone() as int[]);
Hashes.Add(tempHash, new List<int>(new int[] { commitNumber }));
return commitNumber;
}
public int Checkout(int commitNumber, int fileNumber)
{
if (commitNumber >= Commits.Count)
throw new ArgumentException();
else
{
var commit = Commits[commitNumber];
return commit[fileNumber];
}
}
private int GetMyHashCode(int[] array)
{
int result = 0;
for (int i = 0; i < array.Length; ++i)
{
result = unchecked(result * 31 + array[i]);
}
return result;
}
}
}
</code></pre>
<p>I expect you to come up with tips on speeding it up or creating new kind of storing files. I also tried to measure performance of methods and it seems like calculating hash of big array is a problem and adding to <code>SortedList<int,List<int>></code> is a problem as well.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T19:33:01.510",
"Id": "445696",
"Score": "0",
"body": "What I would recommend is to try to space it more (use paragraphs) :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T07:09:20.833",
"Id": "445731",
"Score": "0",
"body": "How much of the API is imposed by the spec and how much is amenable to suggestions for redesign?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T08:26:21.350",
"Id": "445741",
"Score": "1",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T14:20:11.363",
"Id": "445788",
"Score": "0",
"body": "Other than the performance is too slow are there any other issues? Does the code work as expected?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T14:25:45.307",
"Id": "445789",
"Score": "3",
"body": "@pacmaninbw there's no other problems rather than speed. Code works correct to me."
}
] |
[
{
"body": "<h3>Hash code collisions</h3>\n\n<p>There's a problem with <code>Commit</code>: matching hash codes do not mean that two objects are equal ('pigeonhole principle'). For example, both <code>[1, 0]</code> and <code>[0, 31]</code> have hash code 31. You can only be sure that objects are not equal when their hash codes don't match - the inverse is not true.</p>\n\n<p>Also, are you sure that reusing arrays is worth the effort? If <code>filesCount</code> is small, then the savings are small as well, and if <code>filesCount</code> is large, then the likelyhood that a specific state has occurred before is probably very small.</p>\n\n<h3>Multiple smaller arrays</h3>\n\n<p>One alternative is to divide the state into multiple smaller arrays. This limits the impact of individual changes: you only need to copy a 'sub-array' (and create a new 'array-of-arrays'), instead of copying the full state. This also increases the likelyhood that a particular sub-array has occurred before, although I do not think that is something you need to be concerned about.</p>\n\n<p>In Git terms, this is similar to using multiple files instead of a single large file. Committing changes to a single file only creates a new blob for the modified file and a new tree object that references the new blob (and older blobs for unmodified files).</p>\n\n<h3>Change-sets</h3>\n\n<p>Another alternative is to store a change-set for each value, using a binary search to find the value for a particular commit number. This can save a lot of space, but it'll make checkouts slower. Whether that trade-off is worth it depends on the intended use of this class.</p>\n\n<h3>Other notes</h3>\n\n<ul>\n<li>Instead of <code>Clone() as int[]</code>, you can use Linq's <code>ToArray()</code> method.</li>\n<li>I'd put the last 4 lines of <code>Commit</code> inside an <code>else</code> statement, to make it clearer that these are two mutually exclusive paths.</li>\n<li>On the other hand, I would not use an <code>else</code> statement in <code>Checkout</code> - the <code>if</code> check is an 'early-out' guard clause, not a full-blown separate path.</li>\n<li>In <code>Checkout</code>, an <code>ArgumentOutOfRangeException</code> might be better suited. You may also want to guard against negative values. And why not check for invalid file numbers as well?</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:16:28.857",
"Id": "229242",
"ParentId": "229199",
"Score": "5"
}
},
{
"body": "<blockquote>\n<pre><code> if (Hashes.TryGetValue(tempHash, out List<int> key))\n {\n Commits.Add(commitNumber, Commits[key[0]]);\n Hashes[tempHash].Add(commitNumber);\n</code></pre>\n</blockquote>\n\n<p>Be consistent: you've already got an alias for <code>Hashes[tempHash]</code>, so use it.</p>\n\n<p>Also, on the subject of names, why <code>tempHash</code> instead of just <code>hash</code>? And <code>key</code> for the value of a <code>KeyValuePair</code> is a tad confusing.</p>\n\n<hr>\n\n<blockquote>\n <p>I also tried to measure performance of methods and it seems like calculating hash of big array is a problem and adding to <code>SortedList<int,List<int>></code> is a problem as well.</p>\n</blockquote>\n\n<p>Well done for profiling. Both of those problems seem to me to have the same solution: don't do it.</p>\n\n<p>The hash can be updated incrementally. FWIW, real solutions do this using a Merkle tree. To make this robust you need to do something about the <code>FilesSet</code> property. You should only expose the data in read-only form (e.g. as <code>IReadOnlyList<int></code>), and if you have a setter it should take a defensive copy and recalculate the hash from scratch. But I'd be strongly tempted to remove the property and the <code>Update</code> method and replace them with an indexer. </p>\n\n<p>As to the second: why use <code>SortedList</code>? What advantage does it give here over a <code>Dictionary</code>?</p>\n\n<p>Aside from those points, I think the design is back to front. It would be simpler to do things the way version control systems actually do it: the commit version (tag) references the hash, and the hash references the data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T07:00:45.387",
"Id": "229291",
"ParentId": "229199",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229242",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T19:07:09.777",
"Id": "229199",
"Score": "4",
"Tags": [
"c#",
"performance",
"hash-map"
],
"Title": "Mini-git class performance issue"
}
|
229199
|
<p>Got this problem from <a href="https://www.codewars.com/kata/recover-a-secret-string-from-random-triplets" rel="nofollow noreferrer">Codewars</a>.</p>
<blockquote>
<p>There is a secret string which is unknown to you. Given a collection of random triplets from the string, recover the original string.</p>
<p>A triplet here is defined as a sequence of three letters such that each letter occurs somewhere before the next in the given string. "whi" is a triplet for the string "whatisup".</p>
<p>As a simplification, you may assume that no letter occurs more than once in the secret string.</p>
<p>You can assume nothing about the triplets given to you other than that they are valid triplets and that they contain sufficient information to deduce the original string. In particular, this means that the secret string will never contain letters that do not occur in one of the triplets given to you.</p>
</blockquote>
<p>For example, given triplets <code>[['t','u','p'], ['w','h','i'], ['t','s','u'], ['a','t','s'], ['h','a','p'], ['t','i','s'], ['w','h','s']]</code>, the code should return the string <code>whatisup</code>. All the context that I had to solve the problem came from the description. This is a programming challenge, not meant to solve a real life problem. My code passed the tests. There where no random tests though. My main interest is about performance.</p>
<pre><code>function recoverSecret(triplets) {
const after = {};
const precedence = (a, b) => after[a].has(b)
|| [...after[a]].some(c => precedence(c, b) == -1) ? -1 : 1;
for (let triplet of triplets) {
after[triplet[0]] = new Set([...(after[triplet[0]] || []), ...triplet.slice(1)]);
after[triplet[1]] = new Set([...(after[triplet[1]] || []), triplet[2]]);
after[triplet[2]] = new Set([...(after[triplet[2]] || [])]);
}
return Object.keys(after).sort(precedence).join``;
}
</code></pre>
<p>Tried destructuring <code>triplet</code> into <code>[a, b, c]</code> to make it more readable, but got execution timeout. Codewars platform has a max time limit of 12000ms. Wanted to do this:</p>
<pre><code>for (let [a, b, c] of triplets) {
after[a] = new Set([...(after[a] || []), b, c]);
after[b] = new Set([...(after[b] || []), c]);
after[c] = new Set([...(after[c] || [])]);
}
</code></pre>
|
[] |
[
{
"body": "<p>I have mainly two things I'd like to look at:</p>\n\n<p>I'm not a big of fan of the constant deconstructing and recreating of <code>Set</code>s in the loop, especially since this most likely has negative impact on the performance. Unfortunately because there is not direct way to add multiple values to a <code>Set</code> there is no functional \"one line\" solution. My function to do this would look like this:</p>\n\n<pre><code>const addToAfter = (key, values) => {\n const set = after[key] || (after[key] = new Set());\n values.forEach(a => set.add(a));\n};\n</code></pre>\n\n<p>which changes the loop to </p>\n\n<pre><code>for (let triplet of triplets) {\n addToAfter(triplet[0], triplet.slice(1));\n addToAfter(triplet[1], [triplet[2]]);\n addToAfter(triplet[2], []);\n}\n</code></pre>\n\n<p>This leads to my second point: the obvious code repetition. I don't think there is a reason not to use another loop here, which also has the \"advantage\", that you don't need to limit yourself to \"triplets\", but support arrays of any length:</p>\n\n<pre><code>for (let triplet of triplets) {\n for (let i = 0, len = triplet.length; i < len; i++) {\n addToAfter(triplet[i], triplet.slice(i + 1)); \n }\n}\n</code></pre>\n\n<p>If performance is important, I'd even consider getting rid of the <code>.slice</code> call and replace it with a loop, that adds the characters directly to the <code>Set</code>.</p>\n\n<p>In general: I'm avoiding the \"modern\" functional way, because it (at least in this case) leads to slightly cryptic syntax (and thus unread code) and a lot of (slow) memory reallocation and data copying. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T09:36:07.477",
"Id": "229232",
"ParentId": "229200",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T19:31:26.370",
"Id": "229200",
"Score": "2",
"Tags": [
"javascript",
"programming-challenge"
],
"Title": "Recover a secret string from random triplets"
}
|
229200
|
<p>If I use <code>node.addEventListener('click',Wyg.Editor.nodeClickedEvent);</code> then when <code>node</code> is clicked, <code>nodeClickedEvent</code> has <code>this</code>===<code>node</code>. Since <code>nodeClickedEvent</code> is a static function in a class, I want <code>this</code> to === <code>Wyg.Editor</code>, so I wrote a helper function to simplify it.</p>
<p>Helper Function:</p>
<pre class="lang-js prettyprint-override"><code>function fixThisFunc(object,functionName){
const fixedFunc = function(){
object[functionName].apply(object,arguments);
};
return fixedFunc;
}
</code></pre>
<p>How it's used: </p>
<pre class="lang-js prettyprint-override"><code>let node = document.getElementById('myFavoriteNode');
node.addEventListener('click', fixThisFunc(Wyg.Editor,'nodeClickedEvent'));
</code></pre>
<p>How it looked before:</p>
<blockquote>
<pre><code>node.addEventListener('click',
function(event){
Wyg.Editor.nodeClickedEvent(event);
}
);
</code></pre>
</blockquote>
<p>The Wyg.Editor class is like:</p>
<pre class="lang-js prettyprint-override"><code>Wyg.Editor = class {
static nodeClickedEvent(event){
const clickedNode = event.target;
console.log(this); //successfully outputs the Wyg.Editor object/class
this.getEditableNode(clickedNode);
}
//there are more functions, of course
};
</code></pre>
<p>I'm looking for a review of the Helper Function <code>fixThisFunc</code></p>
<p>Are there any particular problems I should be worried about? is there a better way to achieve this functionality?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T20:16:04.733",
"Id": "445701",
"Score": "0",
"body": "Do you mean to use this for this particular scenario or as an API reusable across use cases?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T07:55:25.553",
"Id": "445735",
"Score": "1",
"body": "isn't `bind` enough?\\"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T20:13:41.377",
"Id": "445849",
"Score": "0",
"body": "@Semi-Friends, yes. Yes it is! Didn't know about it."
}
] |
[
{
"body": "<blockquote>\n<p>is there a better way to achieve this functionality?</p>\n</blockquote>\n<p>You can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind\" rel=\"nofollow noreferrer\"><code>Function.bind()</code></a> to create a function with the <code>this</code> context bound to <code>Wyg.Editor</code>:</p>\n<pre><code>const node = document.getElementById('myFavoriteNode');\nnode.addEventListener('click', Wyg.Editor.nodeClickedEvent.bind(Wyg.Editor));\n</code></pre>\n<p>See this demonstrated in the snippet below.</p>\n<p>Notice that <code>const</code> was used instead of <code>let</code> - unless there is a reason to re-assign <code>node</code>, use <code>const</code>. This will help avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>.</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 Wyg = {};\nWyg.Editor = class {\n\n static nodeClickedEvent(event){\n const clickedNode = event.target;\n console.log('nodeClickedEvent() - this: ', this); \n \n }\n};\nconst node = document.getElementById('myFavoriteNode');\nnode.addEventListener('click', Wyg.Editor.nodeClickedEvent.bind(Wyg.Editor));</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><button id=\"myFavoriteNode\">click this favorite node</button></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T20:14:24.417",
"Id": "445850",
"Score": "0",
"body": "Thanks! That's exactly what I need."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T20:22:42.513",
"Id": "229205",
"ParentId": "229204",
"Score": "6"
}
},
{
"body": "<h2>Accessing statics via <code>this</code></h2>\n\n<p>Defining the object reference outside the object just to gain access via a miss used accessor (<code>this</code>) is a hack and not how to use static objects to handle events.</p>\n\n<h3>Binding objects to a function</h3>\n\n<p>First what you did could have been a little less complicated</p>\n\n<p>You had something like</p>\n\n<pre><code>class Editor {\n static nodeClick(event){\n this.editable(event.target); // miss used 'this' to reference 'Editor'\n }\n static editable() {} \n}\n\n\nfunction fixThis(object,functionName){\n const fixedFunc = function(){\n object[functionName].apply(object, arguments);\n };\n return fixedFunc;\n}\nnode.addEventListener('click', fixThis(Editor,'nodeClick'));\n</code></pre>\n\n<p>Could have written the binding using <code>Function.call</code></p>\n\n<pre><code>const thisFunc = (obj, func) => (...args) => func.call(obj, ...args);\nnode.addEventListener('click', fixThis(Editor, Editor.nodeClick));\n</code></pre>\n\n<p>or using <code>Function.bind</code> as one line</p>\n\n<pre><code>node.addEventListener('click', Editor.nodeClick.bind(Editor));\n</code></pre>\n\n<h2>Access static via name</h2>\n\n<p>Static functions should access properties via the defined name. This makes it clear that you are accessing the static properties and conforms with static property accessed from within an instance of the object.</p>\n\n<p>Your objects static access via name should look like</p>\n\n<pre><code>class Editor {\n static nodeClick(event){\n Editor.editable(event.target); // correct reference to 'Editor'\n }\n static editable() {}\n}\n</code></pre>\n\n<p>Then you don't need to bind <code>Editor</code> to <code>Editor.nodeClick</code> to maintain the correct reference. Just pass the static function as is, to the event</p>\n\n<pre><code>node.addeventListener(\"click\", Editor.nodeClick);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T20:24:57.960",
"Id": "445851",
"Score": "0",
"body": "I'll be using `bind`. I find that produces a much more predictable result, and I like it. Hacky or not. I don't want to hard code class names, because that makes my code more dependent upon my naming practices. Using `this` means I can refactor & rename things and still get the same result."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T00:29:56.150",
"Id": "229216",
"ParentId": "229204",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p>is there a better way to achieve this functionality?</p>\n</blockquote>\n\n<p>You might use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#In_an_inline_event_handler\" rel=\"nofollow noreferrer\">a wrapping function</a>:</p>\n\n<pre><code>let node = document.getElementById('myFavoriteNode');\nnode.addEventListener('click', event => Wyg.Editor.nodeClickedEvent(event));\n\n// or, using regular function expression\nnode.addEventListener('click', function(event) {\n return Wyg.Editor.nodeClickedEvent(event);\n});\n\n</code></pre>\n\n<p>Using a wrapper function lets you <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#As_an_object_method\" rel=\"nofollow noreferrer\">keep the original context</a> of your <code>nodeClickedEvent</code> method the way you expect. You can use either arrow or regular function expression, because you don't care at all about the <code>this</code> value <code>addEventListener</code> provides to the callback.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T20:26:45.947",
"Id": "445853",
"Score": "0",
"body": "The `event => ...` is far more concise than what I originally had, and I do kind of like it. But I'm gonna roll with `bind`. Fits how I like to code, because I'd rather use `this` wherever I can than use a hard-coded class name."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T08:18:39.483",
"Id": "229226",
"ParentId": "229204",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229205",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T19:52:44.637",
"Id": "229204",
"Score": "5",
"Tags": [
"javascript",
"object-oriented",
"event-handling",
"scope"
],
"Title": "Wrap a js function with a fixed this arg"
}
|
229204
|
<p>I just started to learn C++ and I decided to make a rock paper scissor game. It works very well but I would like to know how could I improve it further. Thank you very much in advance for your help.</p>
<pre><code>#include <iostream>
#include <string>
#include <time.h>
int main()
{
using namespace std;
string playagain = "yes";
string computerchoice;
string playerChoice;
// computer
int computerNumber;
//rounds + statistics
string name;
int playedRounds =0;
int wonRounds = 0;
int lostRounds = 0;
int tieRounds = 0;
// game text
cout << "_______________________________________________" << endl;
cout << "welcome it's a rock paper scissor game" << endl;
cout << "Whats your name?" << endl;
cin >> name;
cout << "well hey " +name +" please Choose one "<< endl;
cout << "rock - paper - scissor" << endl;
cout << "_______________________________________________" << endl;
while (playagain == "yes") {
// generating a random number
srand(static_cast<unsigned int>(time(NULL)));
computerNumber = rand() % 3 + 1;
// ________________________________ computer picking a element
if (computerNumber == 1) {
computerchoice = "rock";
}
else if (computerNumber == 2) {
computerchoice = "paper";
}
else {
computerchoice = "scissor";
}
//_________________________________
// player choice + go to line
playerChoice: {
cin >> playerChoice;
}
if (playerChoice != "rock" && "paper" && "scissor") {
cout << "" << endl;
cout << "Please choose from one of them"<<endl;
cout << "ROCK - PAPER - SCISSOR" << endl;
cout << "" << endl;
goto playerChoice;
}
// player vs computer
cout << playerChoice + " VS " + computerchoice << endl;
// game rules
if (playerChoice == "rock" && computerchoice == "paper") {
cout << "you lost"; playedRounds++; lostRounds++;
}
else if (playerChoice == "rock" && computerchoice == "scissor") {
cout << "you won"; playedRounds++; wonRounds++;
}
else if (playerChoice == "scissor" && computerchoice == "paper") {
cout << "you won"; playedRounds++; wonRounds++;
}
else if (playerChoice == "scissor" && computerchoice == "rock") {
cout << "you lost"; playedRounds++; lostRounds++;
}
else if (playerChoice == "paper" && computerchoice == "scissor") {
cout << "you lost"; playedRounds++; lostRounds++;
}
else if (playerChoice == "paper" && computerchoice == "rock") {
cout << "you won"; playedRounds++; wonRounds++;
}
else {
cout << "tie"; playedRounds++; tieRounds++;
}
//__________________________________________________________________
cout << "" << endl;
cout << "" << endl;
cout << "_______________________________________________" << endl;
cout << "would u like to play again? or if u wanna check out your statistics u can just type = sta" << endl;
cout << "yes - no - sta" << endl;
cout << "_______________________________________________" << endl;
cout << "" << endl;
cout << "" << endl;
playagain:{ // GO TO LINE
cin >> playagain;
}
if (playagain == "yes") {
cout << "_______________________________________________" << endl;
cout << "Choose wisely, rock - paper - scissor" << endl;
cout << "rock - paper - scissor" << endl;
cout << "_______________________________________________" << endl;
}
else if (playagain == "no") {
cout << "have a nice day! now the program is going to shutdown";
}
else if (playagain == "sta") {
cout << "" << endl;
cout << "" << endl;
cout << "Player name:" +name <<endl;
cout << "Played Rounds: "; cout << +playedRounds << endl;
cout << "Won Rounds: "; cout << +wonRounds << endl;
cout << "lost Round: "; cout << +lostRounds << endl;
cout << "Tie Rounds: "; cout << +tieRounds << endl;
cout << "would u like to continue ? " << endl;
cout << "yes for continue no for exit " << endl;
goto playagain;
}
else {
cout << "i couldn't understand could u repeat please?" << endl;
goto playagain;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T22:56:12.747",
"Id": "445711",
"Score": "5",
"body": "Welcome to CR! You're about to be told why `using namespace std;` shouldn't be used, and how a monolithic sequence of executable instructions can be turned into small, specialized procedures that do nothing more than what their name says - I hope you learn as much on this site as I did! In the meantime feel free to browse other [tag:rock-paper-scissors] posts for more ideas and tips, as each post contains a working implementation and very valuable inputs from reviewers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:50:29.270",
"Id": "445783",
"Score": "1",
"body": "Each question on Code Review is valuable because everyone codes differently, but for future reference after you post a question look on the right hand side of the screen towards the bottom and you will see related posts. These may help you as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T16:59:57.763",
"Id": "445966",
"Score": "1",
"body": "[rock-paper-scissors-lizard-spock](https://the-big-bang-theory.com/rock-paper-scissors-lizard-spock/)"
}
] |
[
{
"body": "<p>Welcome to the wonderful land of computer programming!</p>\n\n<p>There are a few things you could do that could help clean up that code. However, if this is for a class, I would recommend not to add functions, make sure the player is giving a valid safe input, and avoiding namespace issues for future development.</p>\n\n<p>But if it is for a class, here are yet a few</p>\n\n<ul>\n<li>Where can nested loops be used?\n\n<ul>\n<li>The flow control for playing again could be reworked as the \"no\" test isn't needed because the output could be outside the loop.</li>\n<li>Any goto statements make it difficult to read because we typically can't easily distinguish the difference as we can we code blocks.</li>\n</ul></li>\n<li>Using proper vernacular and grammar would increase your max audience by roughly 5%.</li>\n</ul>\n\n<p><strong>Edit:</strong><br>\nI wanted to add, that after 2^32 + 1 runs of your program, you'll see that the computer has a slight bias towards 0. This is pretty common when using making computer AI choices with most random number generators. This is because the of the way the modulus operator works. 10 % 3 will have have a distribution of 4, 3, and 3. I wouldn't worry about it too much for Rock, Paper, Scissors (it's basically a 1:40,000,000,000,000,000) but it's something you should be made aware of.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T23:02:23.717",
"Id": "229212",
"ParentId": "229211",
"Score": "4"
}
},
{
"body": "<p>Welcome to Code Review and welcome to C++! Let's go through the code and see what can be improved.</p>\n\n<p>In C++, the headers of the form <code><xxx.h></code> are <em>deprecated</em>, which means they should not be used. You are recommended to use</p>\n\n<pre><code>#include <ctime>\n</code></pre>\n\n<p>instead of <code>#include <time.h></code>.</p>\n\n<p><code>using namespace std;</code> is considered bad practice because it causes name clashes. It will cause problems when you try to use common identifiers like <code>size</code>, <code>count</code>, <code>find</code>, etc. See <a href=\"https://stackoverflow.com/q/1452721\">Why is <code>using namespace std;</code> considered bad practice?</a>. Explicitly qualify the names with <code>std::</code> instead. You will find that this makes the code more readable when you deal with larger programs and multiple libraries.</p>\n\n<p>I notice that your code structure looks like this:</p>\n\n<blockquote>\n<pre><code>#include <iostream>\n#include <string>\n#include <time.h>\n\nint main()\n{\n // ... sea of code ...\n}\n</code></pre>\n</blockquote>\n\n<p>You have one big <code>main</code> function that does pretty much everything. Well, that's not good for readability. We will try to break it down to small parts. Each part should do one logical thing (e.g., ask for user input, randomly select rock/paper/scissor, etc.)</p>\n\n<p>You represent paper/scissor/rock by the strings <code>\"paper\"</code>, <code>\"scissor\"</code>, and <code>\"rock\"</code>. This is a bit wasteful. You can define an enumeration like this:</p>\n\n<pre><code>enum class Move {\n paper, scissor, rock\n};\n</code></pre>\n\n<p>and define the game logic:</p>\n\n<pre><code>enum class Result {\n win, lose, tie\n};\n\nconstexpr bool beats(Move a, Move b)\n{\n return (static_cast<int>(a) + 2) % 3 == static_cast<int>(b);\n}\n\nconstexpr Result compete(Move a, Move b)\n{\n if (beats(a, b))\n return Result::win;\n else if (beats(b, a))\n return Result::lose;\n else\n return Result::tie;\n}\n</code></pre>\n\n<p>The game has some states — the player name and the statistics. These can be wrapped in a class:</p>\n\n<pre><code>class RPS_game {\npublic:\n // std::string_view requires <string_view>\n // std::uint_fast32_t requires <cstdint>\n RPS_game(std::string_view name, std::uint_fast32_t seed)\n :player_name{name}, seed{seed}\n {\n }\n\n void run();\n\n // ...\nprivate:\n std::string player_name;\n int total_rounds = 0;\n int won_rounds = 0;\n int lost_rounds = 0;\n int tie_rounds = 0;\n\n // requires <random>\n std::mt19937 seed;\n};\n</code></pre>\n\n<p>Then, you can initialize the game and run it like this: (I omitted the greeting part for the sake of simplicity)</p>\n\n<pre><code>int main()\n{\n std::string name;\n std::cout << \"What is your name? \";\n getline(std::cin, name);\n\n auto seed = static_cast<std::uint_fast32_t>(std::random_device{}());\n RPS_game game{name, seed};\n\n game.run();\n}\n</code></pre>\n\n<p>You may have noticed that I stored the seed as a <code>std::mt19937</code> random number engine and use <code>std::random_device</code> to seed it, instead of using <code>rand</code> and <code>time</code>. In C++, <code>std::rand</code> is considered to be a low quality random number generator because the underlying algorithm is not specified and the low bits are often non-uniform. See <a href=\"https://stackoverflow.com/q/53040940\">Why is the new random library better than <code>std::rand()</code>?</a>.</p>\n\n<p>The following code generates the random move:</p>\n\n<blockquote>\n<pre><code>// generating a random number \n\nsrand(static_cast<unsigned int>(time(NULL)));\ncomputerNumber = rand() % 3 + 1;\n\n// ________________________________ computer picking a element\n\nif (computerNumber == 1) {\n computerchoice = \"rock\";\n}\nelse if (computerNumber == 2) {\n computerchoice = \"paper\";\n}\nelse {\n computerchoice = \"scissor\";\n}\n</code></pre>\n</blockquote>\n\n<p>This should be made into its own function:</p>\n\n<pre><code>class RPS_game {\npublic:\n // ...\n Move generate_move();\n // ...\n};\n</code></pre>\n\n<p>and you can implement it like this:</p>\n\n<pre><code>Move RPS_game::generate_move()\n{\n std::uniform_int_distribution<int> dist(0, 2);\n return static_cast<Move>(dist(seed));\n}\n</code></pre>\n\n<p>Now is the game logic. <code>goto</code> is not recommended because it makes the code harder to understand. See <a href=\"https://homepages.cwi.nl/~storm/teaching/reader/Dijkstra68.pdf\" rel=\"noreferrer\">Edgar Dijkstra's <em>Go To Statement Considered Harmful</em> </a>.</p>\n\n<p>When I try to summarize the game logic in the simplest way possible, here's what I get for one round:</p>\n\n<pre><code>Result RPS_game::round()\n{\n Move player_move = get_player_move();\n Move computer_move = generate_move();\n\n auto result = compete(player_move, computer_move);\n switch (result) {\n case Result::win:\n ++won_rounds;\n break;\n case Result::lose:\n ++lost_rounds;\n break;\n case Result::tie:\n ++tie_rounds;\n break;\n }\n ++total_rounds;\n return result;\n}\n</code></pre>\n\n<p>And for the whole game:</p>\n\n<pre><code>void RPS_game::run()\n{\n do {\n round();\n display_stats();\n } while (wanna_play_again());\n\n std::cout << \"Goodbye!\";\n}\n</code></pre>\n\n<p>Following this approach, you can make your code more organized and more readable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:17:06.057",
"Id": "445776",
"Score": "0",
"body": "I'll put this together and post an improved version later if I have time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:45:07.903",
"Id": "445782",
"Score": "0",
"body": "I agree with most of what is posted in this answer, but keep in mind the original posters (OP) level of expertise. Classes might be beyond the scope of this review. https://codereview.meta.stackexchange.com/questions/9327/why-is-the-beginner-tag-appropriate-here-as-opposed-to-e-g-stack-overflow/9328#9328"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:54:05.470",
"Id": "445785",
"Score": "2",
"body": "@pacmaninbw Hmm ... You are probably right. I didn't really consider that too much. Maybe the OP can still understand some of it (breaking down to functions, etc.) and anyway, the OP can still refer back after he learns classes :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:16:48.110",
"Id": "229243",
"ParentId": "229211",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "229243",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T22:32:15.610",
"Id": "229211",
"Score": "6",
"Tags": [
"c++",
"beginner",
"game",
"console",
"rock-paper-scissors"
],
"Title": "rock paper scissor"
}
|
229211
|
<blockquote>
<p>I understand this code is running properly and is grabbing from each excel file individually, but I want to create a for loop for using this data across multiple excel files </p>
</blockquote>
<pre><code>kinematic_viscosity = []
kinematic_viscosity_1= []
kinematic_viscosity_2= []
#*empty arrays for creating after loop in completed*
for dynamic_viscosity in DV:
kinematic_viscosities = dynamic_viscosity/Density_PE_298k
kinematic_viscosity.append(kinematic_viscosities)
for dynamic_viscosity_1 in DV_1:
kinematic_viscosities_1 = dynamic_viscosity_1/Density_PE_298k
kinematic_viscosity_1.append(kinematic_viscosities_1)
#second loop
for dynamic_viscosity_2 in DV_2:
kinematic_viscosities_2 = dynamic_viscosity_2/Density_PE_298k
kinematic_viscosity_2.append(kinematic_viscosities_2)
#third loop
</code></pre>
|
[] |
[
{
"body": "<p>One possible solution is using <a href=\"https://docs.python.org/3/library/functions.html#zip\" rel=\"nofollow noreferrer\"><code>zip()</code></a>. This allows you to iterate, in your case, through multiple lists at a time. You can also condense creating the lists into one line. And, you can remove assigning <code>dynamic_viscosity_#/Density_PE_298k</code> to a variable, just append that to the lists. Consider the following:</p>\n\n<pre><code>kinematic_viscosity, kinematic_viscosity_1, kinematic_viscosity_2 = [], [], []\n\nfor dynamic_viscosity, dynamic_viscosity_1, dynamic_viscosity_2 in zip(DV, DV_1, DV_2):\n kinematic_viscosity.append(dynamic_viscosity/Density_PE_298k)\n kinematic_viscosity_1.append(dynamic_viscosity_1/Density_PE_298k)\n kinematic_viscosity_2.append(dynamic_viscosity_2/Density_PE_298k)\n</code></pre>\n\n<p>While it looks more blocky, it allows you to only loop through the lists once.</p>\n\n<p>Another solution is to keep the three loops, but append the returns directly into the list. Consider the following:</p>\n\n<pre><code>kinematic_viscosity = [dynamic_viscosity/Density_PE_298k for dynamic_viscosity in DV]\n\nkinematic_viscosity_1= [dynamic_viscosity_1/Density_PE_298k for dynamic_viscosity_1 in DV_1]\n\nkinematic_viscosity_2= [dynamic_viscosity_2/Density_PE_298k for dynamic_viscosity_2 in DV_2]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T01:05:44.677",
"Id": "229218",
"ParentId": "229215",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "229218",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T00:25:16.007",
"Id": "229215",
"Score": "0",
"Tags": [
"python",
"pandas"
],
"Title": "Pulling data from multiple excel files in Python"
}
|
229215
|
<blockquote>
<p>DESCRIPTION:<br>
[Inspired by Chandler's GameOfCups with Joey in "Friends"].
Program gets 5-digit zipcode from user. (Assume user won't make a
mistake, and will enter exactly 5 digits).
Program awards points based on a series of rules, and reports the total
points earned at the end.
The 8 rules are embedded as comments in the code.
For each rule, besides adding points (or not) to the total, rule displays
"Rule _ got _ points, so total is now _"
(It prints this even if rule added 0 points to total).</p>
</blockquote>
<pre><code>"""
RULES
+5 when first and last digit match
+6 when second digit is twice the first AND third digit is greater than second or fourth digit
+7 if any 7 is in the zipcode
+8 when there's no "13" in MIDDLE the zipcode
+9 when all three middle digits match
+10 when third and fourth digits match
+11 when zipcode is palindrome (12121 == 12121, while 12345 != 54321)
"""
</code></pre>
<p>Here is my solution to the challenge above:</p>
<pre><code>zipcode = input("Enter your zipcode: ")
total_points = 0
#Rule 1
points = 5 if zipcode[0] == zipcode[-1] else 0
total_points += points
print(f"Rule 1 got {points} points, so total is now {total_points}")
#Rule 2
points = 6 if (int(zipcode[1]) * 2) > int(zipcode[0]) and (int(zipcode[2]) > int(zipcode[1]) or int(zipcode[2]) > int(zipcode[3])) else 0
total_points += points
print(f"Rule 2 got {points} points, so total is now {total_points}")
#Rule 3
points = 7 if "7" in zipcode else 0
total_points += points
print(f"Rule 3 got {points} points, so total is now {total_points}")
#Rule 4
points = 8 if "13" not in zipcode[1:-1] else 0
total_points += points
print(f"Rule 4 got {points} points, so total is now {total_points}")
#Rule 5
points = 9 if zipcode[1] == zipcode[2] == zipcode[3] else 0
total_points += points
print(f"Rule 5 got {points} points, so total is now {total_points}")
#Rule 6
points = 10 if zipcode[2] == zipcode[3] else 0
total_points += points
print(f"Rule 6 got {points} points, so total is now {total_points}")
#Rule 7
points = 11 if zipcode == reversed(zipcode) else 0
total_points += points
print(f"Rule 7 got {points} points, so total is now {total_points}")
print(f"{zipcode} got {total_points} points!")
</code></pre>
<p>I feel like there is a much better way to do this. The print statements are repetitious, and reassigning <code>points</code> each time I check the zip code feels weird. Any suggestions are helpful and appreciated.</p>
|
[] |
[
{
"body": "<p>Your code can be simplified using a simple loop, eliminating most of the duplicated code:</p>\n\n<pre><code>def game_of_cups(zipcode, rules):\n\n total_points = 0\n\n for num, rule in enumerate(rules, 1):\n rule_passes = rule(zipcode)\n points = num + 4 if rule_passes else 0\n total_points += points\n print(f\"Rule {num} got {points} points, so total is now {total_points}\")\n\n print(f\"{zipcode} got {total_points} points!\")\n</code></pre>\n\n<p>You just need the appropriate rule functions, like:</p>\n\n<pre><code>def rule1(zipcode):\n return zipcode[0] == zipcode[-1]\n\ndef rule2(zipcode):\n a, b, c, d, e = map(int, zipcode)\n return b * 2 > a and c > min(b, d)\n\n... etc ...\n</code></pre>\n\n<p>And then a list of <code>rules</code> to pass to the game:</p>\n\n<pre><code>rules = [ rule1, rule2, rule3, rule4, rule5, rule6, rule7 ]\n</code></pre>\n\n<p>Feel free to name the functions more appropriately; they don’t need to be named <code>rule#</code>.</p>\n\n<hr>\n\n<p>Are you missing a rule? You said there were 8 rules. </p>\n\n<hr>\n\n<p>Your implementation of rule#2 doesn’t match the comment description of rule #2. I think it should be <code>b == a * 2</code>, not <code>b * 2 > a</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T06:05:44.570",
"Id": "229221",
"ParentId": "229217",
"Score": "13"
}
},
{
"body": "<p>Just a modification on AJNeufeld's</p>\n\n<pre><code>def game_of_cups(zipcode, rules):\n for num, rule in enumerate(rules, 1):\n points = rule(zipcode)\n total_points += points\n ...\n\ndef rule1(zipcode):\n return 5 if (zipcode[0] == zipcode[-1]) else 0\n\ndef rule2(zipcode):\n a, b, c, d, e = map(int, zipcode)\n return 6 if (b == 2 * a and c > min(b, d)) else 0\n\n...\n</code></pre>\n\n<p>As long as there aren't participation points awarded for any given rule, then this method works for testing to see if the is passed based on the fact that points were awarded.</p>\n\n<p><code>rule_passes</code> was never really used aside from adding the points.</p>\n\n<p>Finally, this allows for more robust point system (and is just as hard coded as the former answer).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T08:44:22.473",
"Id": "229227",
"ParentId": "229217",
"Score": "4"
}
},
{
"body": "<p>I think this is a beautiful opportunity to put them all in a dictionary.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>\"\"\"\nRULES\n +5 when first and last digit match\n +6 when second digit is twice the first AND third digit is greater than second or fourth digit\n +7 if any 7 is in the zipcode\n +8 when there's no \"13\" in MIDDLE the zipcode\n +9 when all three middle digits match\n +10 when third and fourth digits match\n +11 when zipcode is palindrome (12121 == 12121, while 12345 != 54321)\n\"\"\"\ndef rule1(code):\n return code[0] == code[-1]\n\ndef rule2(code):\n return int(code[1]) == 2*int(code[0]) and int(code[2]) > int(code[1]) or int(code[2]) > int(code[3])\n\ndef rule3(code):\n return \"7\" in code\n\ndef rule4(code):\n return \"13\" not in code[1:-1]\n\ndef rule5(code):\n return len(set(code[1:-1])) == 1 # Only 1 unique symbol in this part of the string.\n\ndef rule6(code):\n return code[2] == code[3]\n\ndef rule7(code):\n return code == code[::-1] # Checks for equality against it's own reverse.\n\nrules = {\n rule1: 5,\n rule2: 6,\n rule3: 7,\n rule4: 8,\n rule5: 9,\n rule6: 10,\n rule7: 11,\n}\n\ncode = input(\"Please enter code: \")\ntotal = 0\nfor is_valid, worth in rules.items():\n if is_valid(code):\n total += worth\n print(f\"{is_valid.__name__} got {worth} points, so total is now {total}\")\n else:\n print(f\"{is_valid.__name__} got 0 points, so total is now {total}\")\n\n</code></pre>\n\n<p>First we define all our rules, in such way that they return a boolean value to show whether they apply or not. Then we put them in a dictionary, with the functions themselves as keys, and the worth as value - this allows us to have duplicate values in a hypothetical future. And yes, functions are perfectly valid dictionary keys, like all hashable objects. </p>\n\n<p>Then we simply loop over the dictionary, adding up the values that belong to those functions that return true.</p>\n\n<p>If printing wasn't necessary, it would be a lot easier to add the values up and print them right away with a <a href=\"https://docs.python.org/3/reference/expressions.html#generator-expressions\" rel=\"nofollow noreferrer\">Generator Expression</a>, one of the tools responsible for making python as awesome as it is.:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(f\"Total value: {sum(worth for is_valid, worth in rules.items() if is_valid(code))}\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T15:11:28.020",
"Id": "445799",
"Score": "0",
"body": "This omits the `For each rule, besides adding points (or not) to the total, rule displays \"Rule _ got _ points, so total is now _\"` requirement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T15:14:27.537",
"Id": "445800",
"Score": "0",
"body": "You should also mention Python 3.6+ is required to guarantee rules are processed in the correct order. For Python 3.5 and earlier, an [`OrderedDict`](https://docs.python.org/3.5/library/collections.html#collections.OrderedDict) is required."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T15:18:00.987",
"Id": "445801",
"Score": "0",
"body": "A dictionary is actually unnecessary. A list of `tuple`s would be better: `rules = [(rule1, 5), (rule2, 6), ... (rule7, 11)]`. Then the `.items()` call is unnecessary; simply use `for is_valid, worth in rules`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T15:32:32.387",
"Id": "445804",
"Score": "0",
"body": "No, hash values are unique at least for Cython - they're based on the memory address of the code. Yes, tuples could work to. But dicts aren't that much worse. Dictionary order is completely irrelevant for this and many other purposes. I'll update for the printing. And Python 3.6 is required only for the f-strings. Python dicts are implemented with hash-tables, not equality tests. All keys are required to give a good representation when hash() is called on them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T15:46:49.750",
"Id": "445810",
"Score": "0",
"body": "It's just as guaranteed as any other result for the hash() function. We all know hash collisions can happen. However, we still consider dictionary keys to be as unique as those of their set cousins. Any caveat goes for all other types of dictionary keys like object() subclasses the very same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T16:04:43.213",
"Id": "445813",
"Score": "0",
"body": "Rule #4 is wrong: `return \"13\" in code[1:-1]` should be `return \"13\" not in code[1:-1]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T16:14:55.773",
"Id": "445816",
"Score": "1",
"body": "Still can't see a reason why functions as dictionary keys would be a bad idea. hash collissions is still the only way stuff goes wrong. Why exactly would that second identity check somehow mess up more?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T16:15:13.227",
"Id": "445817",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/98820/discussion-between-ajneufeld-and-gloweye)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T14:53:33.200",
"Id": "229249",
"ParentId": "229217",
"Score": "3"
}
},
{
"body": "<p>Personally, I think it's excessive to have a function for each of the rules. IMO, if you only need the function in a single context, you probably don't need to make a function out of it unless it's sufficiently complex to warrant one - and even then, make sure it's \"private.\"</p>\n\n<p>Because the values for the rule set start at 5 and simply increment in value from rule to rule, you can just iterate over a boolean list, like:</p>\n\n<pre><code>total = 0\nfor x, rule in enumerate(rules):\n score = (x+5) * rule\n total += score\n print(f\"Rule {x+1} got {score} points, so total is {total}.\")\n</code></pre>\n\n<p><br>\nAs for that boolean list, you could do something like:</p>\n\n<pre><code>digits = list(map(int, zipcode))\nrules = [\n zipcode[0] == zipcode[-1],\n digits[1] == 2*digits[0] and digits[2] > min(digits[1], digits[3]),\n \"7\" in zipcode,\n \"13\" not in zipcode[1:-1],\n min(digits[1:-1]) == max(digits[1:-1]),\n zipcode[2] == zipcode[3],\n zipcode == zipcode[::-1]\n]\n</code></pre>\n\n<p>This way you have an list of zeroes and ones for multiplication in the previous loop. In particular, though, rule 2 looks pretty ugly when just slapped into the list here. If you want to make the list look a bit less ugly, maybe you could define rule1 through rule7 to equal each of those conditions and then construct the array that way.</p>\n\n<p><br>\nI also stuck the code into an <code>if __name__ == '__main__'</code> for good practice, and called <code>cupgame</code> from within there. My final program looks like this:</p>\n\n<pre><code>\"\"\"\nRULES\n +5 when first and last digit match\n +6 when second digit is twice the first AND third digit is greater than second or fourth digit\n +7 if any 7 is in the zipcode\n +8 when there's no \"13\" in MIDDLE the zipcode\n +9 when all three middle digits match\n +10 when third and fourth digits match\n +11 when zipcode is palindrome (12121 == 12121, while 12345 != 54321)\n\"\"\"\n\ndef cupgame(zipcode):\n digits = list(map(int, zipcode))\n\n rules = [\n zipcode[0] == zipcode[-1],\n digits[1] == 2*digits[0] and digits[2] > min(digits[1], digits[3]),\n \"7\" in zipcode,\n \"13\" not in zipcode[1:-1],\n min(digits[1:-1]) == max(digits[1:-1]),\n zipcode[2] == zipcode[3],\n zipcode == zipcode[::-1]\n ]\n\n total = 0\n for x, rule in enumerate(rules):\n score = (x+5) * rule\n total += score\n print(f\"Rule {x+1} got {score} points, so total is {total}.\")\n\nif __name__ == '__main__':\n zipcode = input(\"Enter your zipcode: \")\n cupgame(zipcode)\n</code></pre>\n\n<p>I do apologize if this is at all unclear - this is my first time reviewing code outside of a classroom, but hopefully this is of some use.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T15:32:41.750",
"Id": "445805",
"Score": "1",
"body": "`for x in range(len(rules))` is un-Pythonic, and inefficient since it requires an indexing operation `rules[x]` in the loop. Use `for x, rule in enumerate(rules)` instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T15:34:46.593",
"Id": "445806",
"Score": "0",
"body": "`1 in mid and 3 in mid and mid.index(3) > mid.index(1)` will generate `True` for the zipcode `\"91939\"`, but `\"13\" in \"91939\"` returns `False`, which means your implementation of rule #4 differs from the original."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T15:55:48.627",
"Id": "445811",
"Score": "0",
"body": "Rule #4 is still wrong. It fails for `\"91139\"`, claiming there is no \"13\", but there is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T16:17:25.027",
"Id": "445818",
"Score": "1",
"body": "@AJNeufeld Updated, hopefully that should do it on the silly bugs. xD"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T19:27:39.917",
"Id": "445843",
"Score": "0",
"body": "\"make a function out of it unless it's sufficiently complex to warrant one\" This kind of thinking leads to god classes and untestable 100 line functions."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T15:24:12.743",
"Id": "229253",
"ParentId": "229217",
"Score": "4"
}
},
{
"body": "<p>Your code is a straight-line solution to a straight-line problem. So congratulations! You are off to a much better start than you might feel.</p>\n\n<p>Here are some obvious issues:</p>\n\n<h2>Why did you separate your docblock from your code? And why is the rationale not included in the docblock?</h2>\n\n<p>One of the ways to become a <a href=\"https://www.youtube.com/watch?v=IYWlfVqBQLc\" rel=\"nofollow noreferrer\">better programmer</a> is to try to show empathy to \"future you.\" You can do this by including more information than you might think is necessary about <strong>what you are doing</strong> and <strong>why you are doing it.</strong></p>\n\n<p>In this case, if you have written a program with these rules included, the by all means include the challenge itself in the program, as well as a link to the URL of the challenge, and the circumstances under which you are taking the challenge:</p>\n\n<pre><code>\"\"\" rule-of-cups.py\n\n Dave K. and I were drinking last night (17 Sep 2019) and he bet me a round \n of beers that I couldn't get more than +5 points on CodeReview for posting\n the solution to this question.\n\n DESCRIPTION:\n (Inspired by Chandler's GameOfCups with Joey in \"Friends\".)\n\n Program gets 5-digit zipcode from user. (Assume user won't make a mistake, and\n will enter exactly 5 digits). Program awards points based on a series of \n rules, and reports the total points earned at the end. The 8 rules are \n embedded as comments in the code. For each rule, besides adding points (or \n not) to the \n total, rule displays \"Rule _ got _ points, so total is now _\" (It prints this \n even if rule added 0 points to total).\n\n RULES\n +5 when first and last digit match\n +6 when second digit is twice the first AND third digit is greater than \n second or fourth digit\n +7 if any 7 is in the zipcode\n +8 when there's no \"13\" in MIDDLE the zipcode\n +9 when all three middle digits match\n +10 when third and fourth digits match\n +11 when zipcode is palindrome (12121 == 12121, while 12345 != 54321)\n\"\"\" \n</code></pre>\n\n<h2>Why are you not using functions?</h2>\n\n<p>Yes, it's true that the individual steps here are small and simple. That's no reason not to put them into functions that express what they do. When you add that little bit of abstraction, it makes the program easier to understand. When you add a docstring to\nyour function it makes things even easier, and gives you a place to help FutureYou understand what you were doing or not doing.</p>\n\n<pre><code>def get_zipcode() -> str:\n \"\"\" Get a zip code from the user.\n\n A zip code is \\d{5}. No validation, though, because of the spec.\n \"\"\"\n zipcode = input(\"Enter your zipcode: \")\n return zipcode\n\ndef rule1(zipcode: str) -> int:\n \"\"\" +5 when first and last digit match \"\"\"\n points = 5 if zipcode[0] == zipcode[-1] else 0\n return points\n\ndef rule2(zipcode: str) -> int: ...\ndef rule3(zipcode: str) -> int: ...\ndef rule4(zipcode: str) -> int: ...\ndef rule5(zipcode: str) -> int: ...\ndef rule6(zipcode: str) -> int: ...\ndef rule7(zipcode: str) -> int: ...\n</code></pre>\n\n<h2>Why are you not following Python's convention for main?</h2>\n\n<p>Simple rule: the only time you don't do this is inside <code>python -c \"<code>\"</code>.</p>\n\n<pre><code>if __name__ == '__main__':\n total_points = 0\n zipcode = get_zipcode()\n\n points = rule1(zipcode)\n total_points += points\n print(f\"Rule 1 got {points} points, so total is now {total_points}\")\n\n ...\n\n points = rule7(zipcode)\n total_points += points\n print(f\"Rule 7 got {points} points, so total is now {total_points}\")\n\n print(f\"{zipcode} got {total_points} points!\")\n</code></pre>\n\n<h2>Why are you not making your code testable?</h2>\n\n<p>Especially when you are asking for suggestions on CodeReview, it's important to have\nconfidence that some suggested changes doesn't cause a failure. So encapsulate your\ncode in functions that you can call in some kind of <a href=\"https://docs.python.org/3/library/doctest.html?highlight=doctest#module-doctest\" rel=\"nofollow noreferrer\">test harness.</a></p>\n\n<p>In this case, it means that your points calculation should also be a function:</p>\n\n<pre><code>if __name__ == '__main__':\n zipcode = get_zipcode()\n total_points = game_of_cups(zipcode)\n print(f\"{zipcode} got {total_points} points!\")\n</code></pre>\n\n<p>Once you have that, you can write some test cases:</p>\n\n<pre><code>def game_of_cups(zipcode: str) -> int:\n \"\"\" Compute total points according to the rules. Print the score\n of each rule, with a running total.\n\n +5 when first and last digit match\n +6 when second digit is twice the first AND third digit is greater than \n second or fourth digit\n +7 if any 7 is in the zipcode\n +8 when there's no \"13\" in MIDDLE the zipcode\n +9 when all three middle digits match\n +10 when third and fourth digits match\n +11 when zipcode is palindrome (12121 == 12121, while 12345 != 54321)\n\n >>> game_of_cups('12345') == 8\n Rule 1 got 0 points, so total is now 0\n Rule 2 got 0 points, so total is now 0\n Rule 3 got 0 points, so total is now 0\n Rule 4 got 8 points, so total is now 8\n Rule 5 got 0 points, so total is now 8\n Rule 6 got 0 points, so total is now 8\n Rule 7 got 0 points, so total is now 8\n True\n >>> game_of_cups('12321')\n Rule 1 got 5 points, so total is now 5\n Rule 2 got 6 points, so total is now 11\n Rule 3 got 0 points, so total is now 11\n Rule 4 got 8 points, so total is now 19\n Rule 5 got 0 points, so total is now 19\n Rule 6 got 0 points, so total is now 19\n Rule 7 got 11 points, so total is now 30\n 30\n \"\"\"\n total_points = 0\n ... etc ...\n</code></pre>\n\n<p>Then you can run <code>python -m doctest game-of-cups.py</code> and see some discouraging news:</p>\n\n<pre><code>(so) aghast@laptop:~/Code/so$ python -m doctest game-of-cups.py \n**********************************************************************\nFile \"/home/aghast/Code/so/game-of-cups.py\", line 92, in game-of-cups.game_of_cups\nFailed example:\n game_of_cups('12345')\nExpected:\n Rule 1 got 0 points, so total is now 0\n Rule 2 got 0 points, so total is now 6\n Rule 3 got 0 points, so total is now 6\n Rule 4 got 8 points, so total is now 14\n Rule 5 got 0 points, so total is now 14\n Rule 6 got 0 points, so total is now 14\n Rule 7 got 0 points, so total is now 14\n 14\nGot:\n Rule 1 got 0 points, so total is now 0\n Rule 2 got 6 points, so total is now 0\n Rule 3 got 0 points, so total is now 0\n Rule 4 got 8 points, so total is now 8\n Rule 5 got 0 points, so total is now 8\n Rule 6 got 0 points, so total is now 8\n Rule 7 got 0 points, so total is now 8\n 8\n**********************************************************************\nFile \"/home/aghast/Code/so/game-of-cups.py\", line 101, in game-of-cups.game_of_cups\nFailed example:\n game_of_cups('12321')\nExpected:\n Rule 1 got 5 points, so total is now 5\n Rule 2 got 6 points, so total is now 11\n Rule 3 got 0 points, so total is now 11\n Rule 4 got 8 points, so total is now 19\n Rule 5 got 0 points, so total is now 19\n Rule 6 got 0 points, so total is now 19\n Rule 7 got 11 points, so total is now 30\n 30\nGot:\n Rule 1 got 5 points, so total is now 5\n Rule 2 got 6 points, so total is now 11\n Rule 3 got 0 points, so total is now 11\n Rule 4 got 8 points, so total is now 19\n Rule 5 got 0 points, so total is now 19\n Rule 6 got 0 points, so total is now 19\n Rule 7 got 0 points, so total is now 19\n 19\n</code></pre>\n\n<p>Which leads me to point out that:</p>\n\n<h2>If you have functions, you can insert doctests in lots of places.</h2>\n\n<p>Like this:</p>\n\n<pre><code>def rule2(zipcode: str) -> int:\n \"\"\" +6 when second digit is twice the first AND third digit is greater \n than second or fourth digit\n\n >>> rule2('12345')\n 6\n >>> rule2('13431')\n 0\n >>> rule2('12321')\n 6\n \"\"\"\n points = 6 if (int(zipcode[1]) * 2) > int(zipcode[0]) and (int(zipcode[2]) > int(zipcode[1]) or int(zipcode[2]) > int(zipcode[3])) else 0\n return points\n</code></pre>\n\n<p>And yeah, your code here is wrong. You compute <code>d1 * 2 > d0</code> but the rule says \"is twice\", which means <code>==</code>. Also, the second clause could be interpreted two ways. You have interpreted it as <code>d1 < d2 or d3 < d2</code>, but it's probably worth some emphasis or clarification or something.</p>\n\n<p>Also here:</p>\n\n<pre><code>def rule7(zipcode: str) -> int:\n \"\"\" +11 when zipcode is palindrome (12121 == 12121, while 12345 != 54321)\n >>> rule7('12321')\n 11\n \"\"\"\n # points = 11 if zipcode == reversed(zipcode) else 0\n points = 11 if zipcode == zipcode[::-1] else 0\n return points\n</code></pre>\n\n<p>This fails because <code>reversed()</code> returns a <code>reversed</code> iterator object, not a string. Using the <code>[::-1]</code> reversing idiom works, though.</p>\n\n<h2>Finally, some repetition!</h2>\n\n<p>Finally, you'll notice that while the structure of the rules is similar, the contents of the rule functions is all different. I'm going to ignore that, since this is a pretty simple script.</p>\n\n<p>However, the high-level <code>gap_of_cups</code> function has got 7 calls to rule-functions which look identical except for the rule number in two places.</p>\n\n<pre><code> points = rule1(zipcode)\n total_points += points\n print(f\"Rule 1 got {points} points, so total is now {total_points}\")\n</code></pre>\n\n<p>We can take advantage of the fact that in Python, functions are first-class \nobjects. Just put the functions in an iterable, and iterate over them.</p>\n\n<p>However, there's the question of how to print \"Rule 1\". We could use <a href=\"https://docs.python.org/3/library/functions.html?highlight=enumerate#enumerate\" rel=\"nofollow noreferrer\"><code>enumerate</code></a> to keep an integer value, or we could actually use the <code>f.__name__</code> attribute of function objects. Since it's shorter and easier, let's just use <code>enumerate</code>:</p>\n\n<pre><code>for i, rule in enumerate([rule1, rule2, rule3, rule4, rule5, rule6, rule7]):\n points = rule(zipcode)\n total_points += points\n print(f\"Rule {i} got {points} points, so total is now {total_points}\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T19:16:39.223",
"Id": "229267",
"ParentId": "229217",
"Score": "2"
}
},
{
"body": "<p>Like other answers, this one uses a separate function for each rule. Unlike the others it automatically collects the rules, so you don't need to keep a list or dictionary of all the rules. Each function implementing a rule has a name that matches a pattern -- it ends with \"_rule\". <code>calculate_score()</code> the scans <code>globals()</code> looking for the names of functions that match the pattern. The same kind of thing is done by some testing frameworks.</p>\n\n<pre><code>def first_and_last_digits_match_rule(zipcode):\n '''+5 when first and last digit match'''\n return 5 if zipcode[0] == zipcode[-1] else 0\n\ndef second_rule(zipcode):\n '''\n +6 when second digit is twice the first AND \n third digit is greater than second or fourth digit\n '''\n return 6 if zipcode[:2] in ('12','24','36','48') and not (zipcode[1] <= zipcode[2] >= zipcode[3]) else 0\n\ndef any_7_rule(zipcode):\n '''+7 if any 7 is in the zipcode'''\n return 7 if '7' in zipcode else 0\n\ndef no_13_rule(zipcode):\n '''+8 when there's no \"13\" in MIDDLE the zipcode'''\n return 8 if '13' not in zipcode[1:-1] else 0\n\ndef triplet_rule(zipcode):\n '''+9 when all three middle digits match'''\n return 9 if zipcode[1] == zipcode[2] == zipcode[3] else 0\n\ndef digits_3_and_4_match_rule(zipcode):\n '''+10 when third and fourth digits match'''\n return 10 if zipcode[2] == zipcode[3] else 0\n\ndef palindrome_rule(zipcode):\n '''+11 when zipcode is palindrome (12121 == 12121, while 12345 != 54321)'''\n return 11 if zipcode == zipcode[::-1] else 0\n\n\ndef calculate_score(zipcode):\n score= 0\n\n rules = [(name,func) for name,func in globals().items() if name.endswith(\"_rule\") and callable(func)]\n\n for name,rule in rules:\n points = rule(zipcode)\n score += points\n print(f\"\"\"The \"{name[:-5].replace('_',' ')}\" rule got {points} points. Score is now {score}.\"\"\")\n\n return score\n\nif __name__ == \"__main__\":\n zipcode = input(\"Enter zipcode\")\n calculate_score(zipcode)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T13:38:31.730",
"Id": "445944",
"Score": "0",
"body": "Nice, but how do you ensure rules and their results are printed in ascending rule number order?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T17:18:58.013",
"Id": "445968",
"Score": "0",
"body": "@AJNeufeld I don't see a requirement to run/print them in order. However, the line `rules = [ ... ]` can be changed to `rules = sorted( ... )` to sort the rules. Change the rule function names to rule1, rule2, etc. Or provide a key function for more complex sorting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:42:29.010",
"Id": "445990",
"Score": "0",
"body": "It doesn’t explicitly say they have to be sorted, but the OP’s code did have them in rule # order, so it seems implicit. It does say to output `Rule _ got ...`, not `The \"_\" rule got ...` so perhaps you should have `f\"Rule {name[-1:]} got ...\"`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:55:21.943",
"Id": "445992",
"Score": "0",
"body": "Actually, since you're using f-strings, you're Python 3.6+ ... and since dictionaries in Python 3.6+ are insertion ordered, the `globals()` actually maintains source-code ordering of the rules (at least in my Python 3.7 tests). No need for `rules = sorted( ... , key=...)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T19:01:31.540",
"Id": "445994",
"Score": "0",
"body": "I thought `globals()` might return them in order, but didn't have time to check."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T22:54:46.280",
"Id": "229279",
"ParentId": "229217",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229221",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T00:59:26.967",
"Id": "229217",
"Score": "11",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"game"
],
"Title": "Pseudo Game of Cups in Python"
}
|
229217
|
<p><a href="https://github.com/dmitrynogin/drylogs" rel="noreferrer">GitHub</a>, <a href="https://www.nuget.org/packages/Dry.Logs/" rel="noreferrer">NuGet</a></p>
<p>This component traces execution in a logical order instead of chronological as everybody else :)</p>
<p>For example, the following code:</p>
<pre><code> static async Task MainAsync()
{
Op.Log.Subscribe(WriteLine);
using (new Op())
await Task.WhenAll(
from i in Range(0, 4)
select AlphaAsync());
}
private static async Task AlphaAsync()
{
using (new Op("Alpha function"))
await BetaAsync();
}
private static async Task BetaAsync()
{
using (var op = new Op())
{
op.Trace("Waiting...");
await Task.Delay(100);
op.Trace("Continue");
}
}
</code></pre>
<p>Will generate:</p>
<pre><code>MainAsync took 116 ms
Alpha function took 109 ms
BetaAsync took 108 ms
Waiting... after 0 ms
Continue after 108 ms
Alpha function took 109 ms
BetaAsync took 109 ms
Waiting... after 0 ms
Continue after 109 ms
Alpha function took 109 ms
BetaAsync took 109 ms
Waiting... after 0 ms
Continue after 109 ms
Alpha function took 111 ms
BetaAsync took 111 ms
Waiting... after 0 ms
Continue after 111 ms
</code></pre>
<p>Which is a way more readable…</p>
<p>The <code>Op</code> class is defined as:</p>
<pre><code>public class Op : IDisposable
{
public static IObservable<string> Log => Subject;
static Subject<string> Subject { get; } = new Subject<string>();
static AsyncLocal<Op> Context { get; } = new AsyncLocal<Op>();
public Op([CallerMemberName] string text = null)
{
Parent = Context.Value;
Context.Value = this;
Stopwatch = Stopwatch.StartNew();
Indent = Parent == null ? "" : Parent.Indent + " ";
Frame = new List<(string, Func<string>)>();
Frame.Add((Indent + text, () => $"took {Stopwatch.ElapsedMilliseconds} ms"));
}
Op Parent { get; }
Stopwatch Stopwatch { get; }
string Indent { get; }
List<(string Text, Func<string> Time)> Frame { get; }
public void Dispose()
{
Stopwatch.Stop();
Context.Value = Parent;
if(Parent != null)
lock(Parent.Frame)
lock(Frame)
Parent.Frame.AddRange(Frame);
else
Subject.OnNext(ToString());
}
public void Trace(string text)
{
var ms = $"after {Stopwatch.ElapsedMilliseconds} ms";
lock(Frame)
Frame.Add((Indent + " " + text, () => ms));
}
public override string ToString()
{
lock(Frame)
return Join(NewLine,
from row in Frame
select $"{row.Text} {row.Time()}");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T06:43:12.783",
"Id": "445730",
"Score": "1",
"body": "I nominate this as _question of the day_ I need some time to study _AsyncLocal_ :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T07:11:34.953",
"Id": "445732",
"Score": "1",
"body": "Some impressive code you posted, the only issue I would have for this in logging is the scope captured in the async state machine in production code as well as the rather large usage of the ThreadPool. I'm afraid that when using this in production code that your production code will get delayed. We had to remove quite a lot of Async code as we noticed delays of up-to several seconds on a 4x 32 Core server. One other thing, you should consider ConfigureAwait(false) not having it actually is considered an anti-pattern"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T08:23:48.173",
"Id": "445738",
"Score": "0",
"body": "@PPann _ConfigureAwait(false)_ is a good pattern in .NET Framework; however, in .NET Core (as far as I know) synchronization contexts are no longer used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T08:59:28.793",
"Id": "445743",
"Score": "1",
"body": "@dfhwze asynclocal is awesome. I use it a couple of projects and it is a great help. Actually I use the same way as Dmitry :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T09:09:37.067",
"Id": "445744",
"Score": "1",
"body": "https://github.com/he-dev/reusable/blob/dev/Reusable.OmniLog/src/LoggerScope.cs @dfhwze this is the helper that encapsulates that logic"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:03:33.350",
"Id": "445772",
"Score": "1",
"body": "@dfhwze, I use Core 3.0 on winforms and I can confirm that it is causing the execution on the same or UI thread. If omitting you will need to use Invoke. Also not sure if the above logging excluding any framework."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T20:50:14.187",
"Id": "445858",
"Score": "0",
"body": "@dfhwze that sounds mildly horrifying; do you have a reference for that at hand? Brief search doesn't turn up anything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T04:26:55.427",
"Id": "445889",
"Score": "0",
"body": "@VisualMelon It appears to be just the case for ASP.NET Core: https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html"
}
] |
[
{
"body": "<p>One drawback I can think of this way of logging is that (correct me if I'm wrong) it is lazy. That's to say, until the root <code>Op</code> object is <code>Disposed</code>, all of the log items are kept in memory. This means that you are relying entirely on the functionality of the topmost <code>using</code> statement to ensure the log gets properly written somewhere. If due to some external error your process happens to exit unexpectedly, you might end up losing your entire log.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if(Parent != null)\n lock(Parent.Frame)\n lock(Frame)\n Parent.Frame.AddRange(Frame);\n else\n Subject.OnNext(ToString());\n</code></pre>\n</blockquote>\n\n<p>No-one has died from using some <code>{}</code>-braces. Why not use them?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T09:31:56.620",
"Id": "445748",
"Score": "4",
"body": "Haha, yeah, this part is pretty scary without braces."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T10:50:43.873",
"Id": "445753",
"Score": "1",
"body": "@t3chb0t At least there are indentations.. but the white-space police has some concerns :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T17:32:40.600",
"Id": "445827",
"Score": "1",
"body": "`Python##` eyes ask for `Parent == null` check here :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T07:14:52.190",
"Id": "229223",
"ParentId": "229222",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "229223",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T06:24:20.867",
"Id": "229222",
"Score": "8",
"Tags": [
"c#",
"logging",
"async-await"
],
"Title": "Operation logger"
}
|
229222
|
<p>This is working code for input KML files into leaflet map</p>
<pre><code>// Load kml file
fetch('lotA.kml')
.then( res => res.text() )
.then( kmltext => {
// Create new kml overlay
parser = new DOMParser();
kml = parser.parseFromString(kmltext,"text/xml");
console.log(kml)
const track = new L.KML(kml)
map.addLayer(track)
// Adjust map to show the kml
const bounds = track.getBounds()
map.fitBounds( bounds )
})
fetch('lotB.kml')
.then( res => res.text() )
.then( kmltext => {
// Create new kml overlay
parser = new DOMParser();
kml = parser.parseFromString(kmltext,"text/xml");
console.log(kml)
const track = new L.KML(kml)
map.addLayer(track)
// Adjust map to show the kml
const bounds = track.getBounds()
map.fitBounds( bounds )
})
fetch('Schematic.kml')
.then( res => res.text() )
.then( kmltext => {
// Create new kml overlay
parser = new DOMParser();
kml = parser.parseFromString(kmltext,"text/xml");
console.log(kml)
const track = new L.KML(kml)
map.addLayer(track)
// Adjust map to show the kml
const bounds = track.getBounds()
map.fitBounds( bounds )
})
fetch('LotC.kml')
.then( res => res.text() )
.then( kmltext => {
// Create new kml overlay
parser = new DOMParser();
kml = parser.parseFromString(kmltext,"text/xml");
console.log(kml)
const track = new L.KML(kml)
map.addLayer(track)
// Adjust map to show the kml
const bounds = track.getBounds()
map.fitBounds( bounds )
})
fetch('LotD.kml')
.then( res => res.text() )
.then( kmltext => {
// Create new kml overlay
parser = new DOMParser();
kml = parser.parseFromString(kmltext,"text/xml");
console.log(kml)
const track = new L.KML(kml)
map.addLayer(track)
// Adjust map to show the kml
const bounds = track.getBounds()
map.fitBounds( bounds )
})
</code></pre>
<p>Is there a way to write this code shorter? I would like to use it for multiple KML layers.</p>
|
[] |
[
{
"body": "<p>This code is quite repetitive, and doesn’t adhere to the <a href=\"https://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\">Don't Repeat Yourself principle</a>.</p>\n\n<p>One way to DRY it out is to abstract the latter promise callback to a separate function:</p>\n\n<pre><code>const addTrackAndBoundsFromKml = kmltext => {\n\n // Create new kml overlay\n const parser = new DOMParser();\n kml = parser.parseFromString(kmltext,\"text/xml\");\n\n const track = new L.KML(kml);\n map.addLayer(track);\n\n // Adjust map to show the kml\n map.fitBounds( track.getBounds() );\n\n};\n</code></pre>\n\n<p>Note that <code>const</code> was added before the assignment of <code>parser</code> to avoid a global variable from being created, and <code>bounds</code> was eliminated because it was only used once. Also, semi-colons were added- while they are only required <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion\" rel=\"nofollow noreferrer\">after a handful of statements</a>, it could lead to errors if somehow whitespace got removed. It is a good habit to default to terminating lines with them.</p>\n\n<p>Then use (a reference to) that function whenever it is needed:</p>\n\n<pre><code>// Load kml file\nfetch('lotA.kml')\n .then( res => res.text() )\n .then( addTrackAndBoundsFromKml );\n\nfetch('lotB.kml')\n .then( res => res.text() )\n .then( addTrackAndBoundsFromKml );\n\n//etc...\n</code></pre>\n\n<p>This way if a change needed to happen in that function that parses the KML, adds the track layer and fits the bounds, it could be done in one place instead of each occurrence. </p>\n\n<p>The file names could also be stored in an array and iterated over:</p>\n\n<pre><code>const files = ['lotA.kml', 'lotB.kml', 'Schematic.kml', 'lotC.kml', 'lotD.kml'];\nfor ( const file of files ) {\n fetch(file)\n .then( res => res.text() )\n .then( addTrackAndBoundsFromKml );\n}\n</code></pre>\n\n<p>It may not be useful but you could consider using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all\" rel=\"nofollow noreferrer\"><code>Promise.all()</code></a> though the need to call the asynchronous <code>.text()</code> method on each result might make that really complicated. </p>\n\n<p>You could also consider using the <a href=\"/questions/tagged/ecmascript-8\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-8'\" rel=\"tag\">ecmascript-8</a> feature <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function\" rel=\"nofollow noreferrer\">async functions</a> with the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await\" rel=\"nofollow noreferrer\"><code>await</code> operator</a> on the promises, as long as the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Browser_compatibility\" rel=\"nofollow noreferrer\">browser requirements</a> are sufficient. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T06:32:53.750",
"Id": "229289",
"ParentId": "229225",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229289",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T08:17:37.473",
"Id": "229225",
"Score": "2",
"Tags": [
"javascript",
"ecmascript-6",
"ajax",
"promise",
"leaflet"
],
"Title": "Loading KML files into leaflet Javascript map"
}
|
229225
|
<p>I want to increase the performance of this code:</p>
<pre><code>Dim...
...
...
...
...
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set wb = objExcel.Workbooks.Open("C:\Dateipfad\Dateiname.xlsx", True)
Set rs = db.OpenRecordset("Select DataPointVID from My_ValidReport", dbOpenSnapshot)
Do Until rs.EOF = True
For Each ws In wb.Worksheets
Set ValidMeldeposition = ws.UsedRange.Cells.Find(What:=rs!DataPointVID)
If Not (ValidMeldeposition Is Nothing) Then ValidMeldeposition.Interior.ColorIndex = 43
Next ws
rs.MoveNext
Loop
j = 0
Do While Dir(Dokumentenpfad) <> ""
j = j + 1
Dokumentenpfad = CurrentProject.Path & "\Dateiname" & Format(Date, " dd.mm.yyyy") & " (" & j & ")" & ".xlsx"
Loop
NeuerReport = Dokumentenpfad
wb.SaveCopyAs (NeuerReport)
MsgBox "Your file was saved here: " & vbCrLf & "'" & NeuerReport & "'"
objExcel.Visible = True
Set objWorkbook = Nothing
Set objExcel = Nothing
End Sub
</code></pre>
<p>The problem is that the Excel file contains over 70 Worksheets and every Sheet includes ID's which are checked by the code and also by the Access-Query which includes the ID's.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T20:13:28.967",
"Id": "454686",
"Score": "0",
"body": "This sounds like a really fun use case for a 3 dimensional array. I hope you dont mind getting some grey hairs LOL"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T08:55:24.850",
"Id": "454722",
"Score": "0",
"body": "what? :D I don't know how i can solve this :D never.. :D"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T09:23:46.973",
"Id": "229230",
"Score": "0",
"Tags": [
"performance",
"vba",
"excel",
"ms-access"
],
"Title": "Performance of ID's checking between Access and Excel"
}
|
229230
|
<p>I have some data…</p>
<pre><code>let points = [(718, 620), (4596, 1280), (410, 333), (4597, 993),
(410, 337), (4597, 996), (428, 337), (4597, 1000), (431, 335), (4599, 1044)]
</code></pre>
<p>… that follows the pattern</p>
<pre><code>[(pointStartOne.x, pointStartOne.y), (pointEndOne.x, pointEndOne.y),
(pointStartTwo.x, pointStartTwo.x) // ...
</code></pre>
<p>I need to structure it to </p>
<pre><code>typealias PointPair = [(start: Point, end: Point)]
struct Point {
let x: Int
let y: Int
}
</code></pre>
<p>Here is my code:</p>
<pre><code>var result: PointPair = []
while i < points.count{
result.append((Point(x: points[i].0, y: points[i].1), Point(x: points[i+1].0, y: points[i+1].1)))
i+=2
}
</code></pre>
<p>I think maybe it is nice situation to use functional programming <code>reduce</code></p>
<p>Here is code ituitive:</p>
<pre><code>let result = zip((points.enumerated().filter({ (offset: Int, element: (Int, Int)) -> Bool in
return offset%2==0
})), (points.enumerated().filter({ (offset: Int, element: (Int, Int)) -> Bool in
return offset%2==1
}))).reduce(PointPair(), { (result: PointPair, arg) -> PointPair in
let (one, other) = arg
let (offset, point) = one
let (offsetTwo, otherPoint) = other
return result + [(Point(x: point.0,y: point.1), Point(x: otherPoint.0,y: otherPoint.1))]
})
</code></pre>
<p>It is messy. Trying to use functional programming conveniently and elegantly.</p>
<p>Here is the improved code:</p>
<pre><code>result = points.enumerated().reduce(into: PointPair(), {(temp, arg) in
let (offset, point) = arg
if offset % 2 == 0{
temp += [(Point(x: point.0, y: point.1), Point(x: 0, y: 0) )]
}
else if let last = temp.last {
temp[temp.count - 1] = (last.0, Point(x: point.0, y: point.1))
}
})
</code></pre>
|
[] |
[
{
"body": "<p>Let's start with the first version: A loop </p>\n\n<pre><code>var i = 0\nwhile i < points.count {\n // ...\n i += 2\n}\n</code></pre>\n\n<p>can be written as a for-loop over a <em>stride:</em></p>\n\n<pre><code>for i in stride(from: 0, to: points.count, by: 2) {\n // ...\n}\n</code></pre>\n\n<p>which restricts the scope of <code>i</code> to the loop body, and makes it a constant. Now each loop iteration appends exactly one element to <code>var result: PointPair</code>, which means that we can write this as a <code>map</code> operation:</p>\n\n<pre><code>let result: PointPair = stride(from: 0, to: points.count, by: 2)\n .map { i in\n (start: Point(x: points[i].0, y: points[i].1),\n end: Point(x: points[i+1].0, y: points[i+1].1))\n }\n</code></pre>\n\n<p>This may already be the “functional” version that you are looking for, but let's also have a look at your other two variants.</p>\n\n<p>The “intuitive code” creates two additional arrays by filtering the original one for even/odd indices. After filtering the arrays the offsets are not needed, giving the warnings</p>\n\n<pre>\nImmutable value 'offset' was never used; consider replacing with '_' or removing it\nImmutable value 'offsetTwo' was never used; consider replacing with '_' or removing it\n</pre>\n\n<p>This can be fixed with</p>\n\n<pre><code>let (_, point) = one\nlet (_, otherPoint) = other\n</code></pre>\n\n<p>A better way is to use <code>compactMap()</code> (which can be thought of as a combination of <code>filter()</code> and <code>map()</code>) to create arrays of the points with even/odd indices, without the element offsets.</p>\n\n<p>Using <code>reduce()</code> for creating the result array is inefficient, as it creates intermediate arrays for each iteration. <code>reduce(into:_:)</code> would be an improvement, but actually this is just a <code>map()</code>:</p>\n\n<pre><code>let result: PointPair = zip(\n points.enumerated().compactMap { (offset, element) -> Point? in\n offset % 2 == 0 ? Point(x: element.0, y: element.1) : nil },\n points.enumerated().compactMap { (offset, element) -> Point? in\n offset % 2 == 1 ? Point(x: element.0, y: element.1) : nil }\n).map { ($0, $1) }\n</code></pre>\n\n<p>This looks a lot “less messy” than your original version, but still has the disadvantage of creating intermediate arrays.</p>\n\n<p>I have not much to say about your last version. It uses <code>reduce(into:)</code> which is good to avoid the creation of intermediate arrays. The only disadvantage is that temporary pairs are created and modified in every second step.</p>\n\n<p>So the “stride + map” variant looks like the best to me: It is efficient and easy to read.</p>\n\n<p>A final remark: The type alias </p>\n\n<pre><code>typealias PointPair = [(start: Point, end: Point)]\n</code></pre>\n\n<p>is misleading, because it does not define a pair of points but an <em>array</em> of pairs of points. I would probably define a dedicated type for a pair of points instead</p>\n\n<pre><code>struct Line {\n let from: Point\n let to: Point\n}\n</code></pre>\n\n<p>and then use <code>[Line]</code> as the result type.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T15:03:10.320",
"Id": "229250",
"ParentId": "229235",
"Score": "6"
}
},
{
"body": "<p>one other idea is to add <code>chunked</code> to <code>Array</code> (source: <a href=\"https://www.hackingwithswift.com/example-code/language/how-to-split-an-array-into-chunks\" rel=\"nofollow noreferrer\">HackingWithSwift</a>):</p>\n\n<pre class=\"lang-swift prettyprint-override\"><code>import UIKit\n\nextension Array {\n func chunked(into size: Int) -> [[Element]] {\n return stride(from: 0, to: count, by: size).map {\n Array(self[$0 ..< Swift.min($0 + size, count)])\n }\n }\n}\n\nstruct Point {\n let x: Int\n let y: Int\n}\n\n\nstruct Line {\n let from: Point\n let to: Point\n}\n</code></pre>\n\n<p>just for better prints in Playground -> it removes the <code>__lldb_expr</code> prefix:</p>\n\n<pre class=\"lang-swift prettyprint-override\"><code>extension Point: CustomStringConvertible {\n var description: String { return \"Point( x:\\(x), y:\\(y) )\" }\n}\nextension Line: CustomStringConvertible {\n var description: String { return \"Line( \\(from) -> \\(to) )\" }\n}\n</code></pre>\n\n<p>test it:</p>\n\n<pre class=\"lang-swift prettyprint-override\"><code>let points = [(718, 620), (4596, 1280), (410, 333), (4597, 993),\n(410, 337), (4597, 996), (428, 337), (4597, 1000), (431, 335), (4599, 1044)]\n\nlet lines = points.map{ point in Point(x: point.0, y: point.1) }\n .chunked(into: 2)\n .map{ pointpair in Line(from: pointpair[0],to:pointpair[1]) }\n\ndump(lines)\n\n\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>▿ 5 elements\n ▿ Line( Point( x:718, y:620 ) -> Point( x:4596, y:1280 ) )\n ▿ from: Point( x:718, y:620 )\n - x: 718\n - y: 620\n ▿ to: Point( x:4596, y:1280 )\n - x: 4596\n - y: 1280\n ▿ Line( Point( x:410, y:333 ) -> Point( x:4597, y:993 ) )\n ▿ from: Point( x:410, y:333 )\n - x: 410\n - y: 333\n ▿ to: Point( x:4597, y:993 )\n - x: 4597\n - y: 993\n ▿ Line( Point( x:410, y:337 ) -> Point( x:4597, y:996 ) )\n ▿ from: Point( x:410, y:337 )\n - x: 410\n - y: 337\n ▿ to: Point( x:4597, y:996 )\n - x: 4597\n - y: 996\n ▿ Line( Point( x:428, y:337 ) -> Point( x:4597, y:1000 ) )\n ▿ from: Point( x:428, y:337 )\n - x: 428\n - y: 337\n ▿ to: Point( x:4597, y:1000 )\n - x: 4597\n - y: 1000\n ▿ Line( Point( x:431, y:335 ) -> Point( x:4599, y:1044 ) )\n ▿ from: Point( x:431, y:335 )\n - x: 431\n - y: 335\n ▿ to: Point( x:4599, y:1044 )\n - x: 4599\n - y: 1044\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T22:17:05.703",
"Id": "229668",
"ParentId": "229235",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229250",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T11:05:53.330",
"Id": "229235",
"Score": "4",
"Tags": [
"functional-programming",
"swift"
],
"Title": "Reducing a list of points into a list of pairs of points"
}
|
229235
|
<p>Can I use <code>#define fori(i,n) for(int i=0;i<=n;i++)</code> in Java?</p>
<p>And of course, Java doesn't have precompiler so we cannot do that in java. So I thought we can do that <code>fori</code> method either using <code>stream()</code> or manually defining a method. But I thought instead of just traversing why can't I put the third parameter as lambda expression that operates.</p>
<h3>Functional interface:</h3>
<pre><code>interface func
{
int calculate(int a,int b);
}
</code></pre>
<h3>Method implementation:</h3>
<pre><code> int run(int[] array,int start,int end,func t)
{
int result =0;
for(int i=start;i<=end;i++)
{
System.out.println(result);
result = t.calculate(array[i], result);
}
return result;
}
</code></pre>
<h3>Usage:</h3>
<pre><code>public static void main(String[] args)
{
int[] array = {1,2,3,4,5,3,5,3,2,2,3,2,23,2};
System.out.println(run(array, 0, 5, (a,b) -> a + b ));
}
</code></pre>
<p>I would like a review on this code pattern. My major concern is that how much complicated lambda expression I can use here. Also, what is the future scope of this what could be done with this pattern?</p>
|
[] |
[
{
"body": "<p>The pattern you have implemented is basically a <code>reduction</code> or <code>foldLeft</code> method.<br>\nCompare it to the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#reduce-java.util.function.BinaryOperator-\" rel=\"noreferrer\"><code>Stream#reduce</code> method</a> in Java, it is very similar.</p>\n\n<p>To answer your question about the complexity of the lambda to put into the method: There is no limit. You can do everything you like in there. A lambda expression is nothing more than an implementation of the single-method interface you have created. And there is no limit on the complexity of a class implementing an interface.</p>\n\n<p>Now for some real code review:</p>\n\n<h3>Use proper and understandable names and use built-in types</h3>\n\n<p>Your interface is simply named <code>func</code>. This probably means \"function\" but you don't have to save on characters, Java is already quite verbose.<br>\nWhat you have, is a special kind of <code>BiFunction</code> or more precisely, <code>BinaryOperator</code>. Now I know that generics don't allow you to specify primitive types for the generic arguments, but your <code>func</code> interface is not necessary and can be replaced by a <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/function/BinaryOperator.html\" rel=\"noreferrer\"><code>BinaryOperator<Integer></code></a>.</p>\n\n<p>Your <code>run</code> method has a very generic name. Sure, there is code that is run, but it doesn't explain, what this method does.<br>\nIt would be more precise to call your method <code>reduce</code> or <code>foldLeft</code> or something similar, that explains in the name, what this method does.</p>\n\n<h3>Make your method do one thing</h3>\n\n<p>Currently your method calculates a result and, in addition to that, prints the value of <code>result</code> for every iteration. What if you or someone who uses your method does not want to have every single intermediate result printed to them?</p>\n\n<p>If you want to print the intermediate values, do so in your lambda.</p>\n\n<h3>You wanted to think about the future</h3>\n\n<p>Your method currently only works with primitive integer arrays. Nothing stops you from making it work with generic types or even lists.<br>\nAnd if you go that far, you'll probably use streams anyway.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T12:37:59.000",
"Id": "445767",
"Score": "0",
"body": "really helpful. I got your point. what should I do to define a method that supports various lambda expressions what we use in streams?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:06:35.643",
"Id": "445773",
"Score": "0",
"body": "What exactly do you mean with \"various lambda expressions\"? You can use any expression that satisfies the interface (ie. takes two integers as input and returns one integer). You can't really chain the expressions one after another because a `reduce` operation is terminal and returns exactly one value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T15:24:17.313",
"Id": "445802",
"Score": "0",
"body": "by Various I mean arithmetic operations ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T16:25:59.833",
"Id": "445819",
"Score": "1",
"body": "Ah, yeah, you can do *anything* in the lambda expression. There are no limits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T16:30:01.760",
"Id": "445821",
"Score": "0",
"body": "Can I delete Array elements with lambda ? Im sure that won’t be as like reduce method"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T18:40:40.407",
"Id": "445837",
"Score": "0",
"body": "Given that you don't have a reference to the array and that array instances are of constant size, no. You can only change them, if you had the reference to the array. Resizing an array is not possible and as such, removing elements is also not simply possible. For this, use dynamic memory structures such as lists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T01:45:29.097",
"Id": "445880",
"Score": "0",
"body": "Ok fine. If I define a method that will set current value to zero instead of deleting. But my point is it will different because it won’t be a terminal operation Right ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T07:33:01.857",
"Id": "445894",
"Score": "0",
"body": "Well, yes, using 0 instead of removing the value leaves it in. And in certain circumstances it might have a different meaning than you anticipated. Setting certain values to 0 is no terminal operation, the term \"terminal operation\" only really makes sense in the context of streams. And if you want more advanced algorithms, filtering of values and whatnot, use streams."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T14:36:41.143",
"Id": "447960",
"Score": "0",
"body": "In cpp macro I state above I can do something like 'forn(i,3) cin>> arr[i];' to take input for elements in array. how can do that using lamda in my pattern @GiantTree"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T12:23:11.963",
"Id": "229238",
"ParentId": "229236",
"Score": "6"
}
},
{
"body": "<p>Most is already said by GiantTree, so only one additional remark: after replacing <code>func</code> with <code>BinaryOperator</code> (or in this case <code>IntBinaryOperator</code>) and the calculation with reduce, the only thing your run method really does is an array lookup.</p>\n\n<p>You can solve this directly with the existing standard library - the following is equivalent to your code:</p>\n\n<pre><code>IntStream.rangeClosed(0, 5).map(i -> array[i]).reduce(0, (a, b) -> a + b);\n</code></pre>\n\n<p>My advice: don't reinvent the wheel, get a good grip on the basic libraries instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T14:29:27.633",
"Id": "447959",
"Score": "0",
"body": "I know `IntStream` and reduce but It doesn't allow me to modify the underlying array. But In my pattern, I might modify the original array elements."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T15:14:15.910",
"Id": "229252",
"ParentId": "229236",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229238",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T11:53:43.933",
"Id": "229236",
"Score": "6",
"Tags": [
"java"
],
"Title": "Automate tasks with Lambdas"
}
|
229236
|
<p>Next script returns NRPE friendly output. It checks percentage usage of all local filesystems. </p>
<p>Desired output if everything is ok:</p>
<p><strong>OK | /=56;;;; /boot=20;;;; /opt=40;;;; /var=60;;;;</strong> <em>(and <code>exit_code</code>0 = ok)</em></p>
<p>Desired output if something is wrong:</p>
<p><strong>CHECK /var | /=56;;;; /boot=20;;;; /opt=40;;;; /var=93;;;;</strong> <em>(and <code>exit_code</code>1 = warning, 2 = error)</em></p>
<pre><code>#!/usr/bin/env bash
set -o errexit -o nounset -o pipefail
warning=80
critical=95
declare -a output_text
declare -a output_data
exit_code="0"
while read -r filesystem _ _ _ used mountpoint; do
if [[ ${filesystem:0:4} = "/dev" ]] && [[ ${filesystem:0:8} != "/dev/sr0" ]]; then
code="$(( ( ${used%"%"} > warning ) + ( ${used%"%"} > critical ) ))"
# Never decrease the exit_code value!
if [[ $code -gt $exit_code ]]; then
exit_code="$code"
output_text+=("$mountpoint")
fi
output_data+=("${mountpoint}=${used%"%"};;;;")
fi
done < <( df -P )
if [[ exit_code -gt 0 ]]; then
echo "CHECK" "${output_text[@]}" "|" "${output_data[@]}"
else
echo "OK |" "${output_data[@]}"
fi
exit $exit_code
</code></pre>
<p>Could I do something better?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:07:47.527",
"Id": "229241",
"Score": "3",
"Tags": [
"bash",
"linux",
"shell",
"plugin",
"status-monitoring"
],
"Title": "NRPE script for monitoring filesystems usage"
}
|
229241
|
<p>The code consists of three functions:</p>
<ol>
<li><p>Spans arbitrary vector (takes dimension as an argument)</p></li>
<li><p>Spans vector orthogonal to the one passed in the argument</p></li>
<li><p>Finds cross product between two vectors.</p></li>
</ol>
<p>The code is following:</p>
<pre><code>def span_vector(n):
'''n represents dimension of the vector.'''
return [random.randrange(-1000,1000) for x in range(n)]
def span_orthogonal(vec):
'''vec represents n-dimensional vector'''
'''Function spans an arbitrary vector that is orthogonal to vec'''
dimension = len(vec)
orthogonal_vec = []
for k in range(dimension-1):
orthogonal_vec.append(random.randrange(-1000,1000))
last_k = ((-1)*sum([vec[x]*orthogonal_vec[x] for x in range(dimension-1)]))/vec[-1]
orthogonal_vec.append(last_k)
return orthogonal_vec
def cross_product(v1,v2):
return sum(v1[x]*v2[x] for x in range(len(v1)))
</code></pre>
<hr>
<p>What can be improved?</p>
<hr>
<p><strong>EDIT</strong> The last function must read <code>dot_product</code>, but not <code>cross_product</code>. I made a mistake.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:42:11.700",
"Id": "445781",
"Score": "2",
"body": "Is there a reason that you aren't using Numpy?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T14:27:28.110",
"Id": "445790",
"Score": "0",
"body": "@Reinderien I've just tried to write something without using Numpy. But well, I concede that using Numpy would be a way better choice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T14:41:45.830",
"Id": "445792",
"Score": "8",
"body": "Two points: (1) \"span\" has a [technical meaning in linear algebra](https://en.wikipedia.org/wiki/Linear_span) so I do not think the names `span_vector` and `span_orthogonal` are appropriate (sth. like `generate_vector` should be fine); (2) if it is not required that `span_orthogonal` returns a random vector, one can directly construct a vector orthogonal to the input from the input's coordinates."
}
] |
[
{
"body": "<p>You should probably be using Numpy, although I don't know enough about your situation to comment any further.</p>\n\n<p>Assuming that you need to retain \"pure Python\", the following improvements can be made:</p>\n\n<h2>Negation</h2>\n\n<p>Replace <code>(-1)*</code> with <code>-</code></p>\n\n<h2>Generators</h2>\n\n<p>Replace your <code>for k in range(dimension-1):</code> loop with</p>\n\n<pre><code>orthogonal_vec = [\n random.randrange(-1000,1000)\n for _ in range(dimension-1)\n]\n</code></pre>\n\n<h2>Type hints</h2>\n\n<p><code>n: int</code>, <code>vec: typing.Sequence[float]</code> (probably) . And the first two functions return <code>-> typing.List[float]</code>. <code>cross_product</code> both accepts and returns <code>float</code>.</p>\n\n<h2>Inner list</h2>\n\n<pre><code>sum([ ... ])\n</code></pre>\n\n<p>shouldn't use an inner list. Just pass the generator directly to <code>sum</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:49:41.090",
"Id": "229246",
"ParentId": "229244",
"Score": "11"
}
},
{
"body": "<p>This is only a minor observation on top of what <a href=\"https://codereview.stackexchange.com/users/25834/\">@Reinderien</a> already wrote about your code.</p>\n\n<p>Writing function documentation like you did with </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def span_orthogonal(vec):\n '''vec represents n-dimensional vector'''\n '''Function spans an arbitrary vector that is orthogonal to vec'''\n</code></pre>\n\n<p>does not work as expected.</p>\n\n<p>If you were to use <code>help(span_orthogonal)</code> you'd see</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Help on function span_orthogonal in module __main__:\n\nspan_orthogonal(vec)\n vec represents n-dimensional vector\n</code></pre>\n\n<p>The reason is that only the first block of text is interpreted as documentation. Also the usual convention is to write documentation \"the other way round\", by which I mean first give a short summary on what your function does, than go on to provide details such as the expected input. Both aspects can also be found in the infamous official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">Style Guide for Python Code</a> (aka PEP 8) in the section on <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"noreferrer\">documentation strings</a>.</p>\n\n<p>With</p>\n\n<pre><code>def span_orthogonal(vec):\n '''Function spans an arbitrary vector that is orthogonal to vec\n\n vec represents n-dimensional vector\n '''\n</code></pre>\n\n<p>calling <code>help(...)</code> gives you</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Help on function span_orthogonal in module __main__:\n\nspan_orthogonal(vec)\n Function spans an arbitrary vector that is orthogonal to vec\n\n vec represents n-dimensional vector\n</code></pre>\n\n<p>Also since @Reinderien also hinted you towards numpy, just let me tell you that there is also \"special\" documentation convention (aka <a href=\"https://numpydoc.readthedocs.io/en/latest/format.html\" rel=\"noreferrer\">numpydoc</a>) often used in the scientific Python stack.</p>\n\n<p>An example:</p>\n\n<pre><code>def span_orthogonal(vec):\n '''Function spans an arbitrary vector that is orthogonal to vec\n\n Parameters\n ----------\n vec : array_like\n represents n-dimensional vector\n '''\n</code></pre>\n\n<p>This style is closer to what's possible with type hints in current versions of Python, as in that it's more structured. The idea behind numpydoc is to facilitate automated documentation generation using tools like <a href=\"http://www.sphinx-doc.org/en/master/\" rel=\"noreferrer\">Sphinx</a>, but this goes a little bit beyond what I was trying to convey here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T14:54:00.690",
"Id": "445795",
"Score": "0",
"body": "That's a very useful information. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T14:48:05.010",
"Id": "229248",
"ParentId": "229244",
"Score": "10"
}
},
{
"body": "<p>Besides what @Reinderein and @AlexV already mentioned, you could have added the following to your code to deliver a complete runnable example:</p>\n\n<p>at the top:</p>\n\n<pre><code>import random\n</code></pre>\n\n<p>at he bottom something like:</p>\n\n<pre><code>def main():\n v1 = span_vector(3)\n v2 = span_orthogonal(v1)\n print(v1)\n print(v2)\n print(cross_product(v1,v2))\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>For the <code>1000</code>'s (and in <code>-1000</code>) you could use a 'constant':</p>\n\n<pre><code>MAX_COOR_VAL = 1000\n</code></pre>\n\n<p>The definition of (<code>cross</code>)<code>dot_product(v1,v2)</code> could be made a bit clearer and more consistent with <code>span_orthogonal(vec)</code>:</p>\n\n<pre><code>def dot_product(vec1, vec2):\n</code></pre>\n\n<p>The method <code>span_orthogonal(vec)</code> is not bulletproof, it might result in a ZeroDivisionError exception when <code>vec</code> equals <code>[1,0]</code> and the random creation of <code>orthogonal_vec</code> happens to be <code>[1]</code> (or <code>[2]</code>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T17:38:20.930",
"Id": "229262",
"ParentId": "229244",
"Score": "5"
}
},
{
"body": "<p>It would be more Pythonic to use <code>zip()</code> in your <strike><code>cross_product(v1, v2)</code></strike> <code>dot_product(v1, v2)</code> function:</p>\n\n<pre><code> return sum(a * b for a, b in zip(v1, v2))\n</code></pre>\n\n<p>This iterates over both vectors simultaneously, extracting one component from each, and calling those components <code>a</code> and <code>b</code> respectively ... and multiplying them together and summing them as normal. No need for the \"vulgar\" <code>for x in range(len(v1))</code> antipattern.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T20:41:50.140",
"Id": "229271",
"ParentId": "229244",
"Score": "5"
}
},
{
"body": "<p>Your <code>span_orthogonal(vec)</code> function is doing stuff from your other functions, so rather than rewriting the code, you can just use those functions:</p>\n\n<pre><code>last_k = -dot_product(span_vector(dimension-1),vec[:-1])/vec[-1]\n</code></pre>\n\n<p>However, your method of giving all but the last coordinate random values, and then calculating the last coordinate's value based on that, gives an error when the sum for the rest of the components. So you should find a nonzero coordinate, exit the function if none such exists, then find the dot product of the remaining coordinates, then check whether that's zero.</p>\n\n<pre><code>try:\n nonzero_index, nonzero_value = next([(i,v) for (i,v) in enumerate(vec) if v)])\nexcept StopIteration:\n print(\"Vector must be nonzero.\")\n return \northogonal_vec = span_vector(dimension-1)\nreduced_vec = vec.copy()\nreduced_vec.pop(nonzero_index) \ninitial_product = -dot_product(orthogonal_vec,reduced_vector)\nif initial_product:\n orthogonal_vec.insert(nonzero_index,-initial_product/nonzero_value)\nelse:\n orthogonal_vec.insert(non_zero_index,0)\nreturn orthogonal_vec\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T16:37:35.250",
"Id": "446463",
"Score": "1",
"body": "My friends [Gram and Schmidt](https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process) also have a nice method to suggest for this task."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:34:55.330",
"Id": "229335",
"ParentId": "229244",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229246",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:34:05.613",
"Id": "229244",
"Score": "12",
"Tags": [
"python",
"coordinate-system"
],
"Title": "Algorithm that spans orthogonal vectors: Python"
}
|
229244
|
<p>I'm creating a filter with Linq in an ASP.NET MVC application. I was hoping I could get some tips on performance enhancements, aside from any possible performance enhancements.</p>
<p>I have a few questions:</p>
<ul>
<li>Should I <code>ToList</code> before my extension methods that use .<code>Select</code>?</li>
<li>Would adding <code>AsNoTracking</code> help performance? If so, if my <code>GetAllIncluding</code> method returns <code>IEnumerable</code>, where should I add <code>AsQueriable().AsNoTracking()</code>?</li>
<li>The Entities <code>SubProject</code> and <code>Activity</code> are self referencing Entities I'm trying to eager load them as all the lazy loading looping is extremely slow. Am I doing this in the correct manner?</li>
</ul>
<p>I know this is using Repo pattern and UOW, but that's just the way this app was built so I would like to build this around that.</p>
<p>Here is the <code>DTO</code> I'm sending to the client:</p>
<pre><code>public class GanttDto
{
public IEnumerable<ProductLineDto> ProductLines { get; set; }
public IEnumerable<ProjectDto> Projects { get; set; }
public IEnumerable<SubProjectDto> Subprojects { get; set; }
public IEnumerable<ActivityDto> Activities { get; set; }
public IEnumerable<ProjectTypeDto> ProjectTypes { get; set; }
}
</code></pre>
<p>Here are my filter methods</p>
<pre><code> public GanttDto Filter(GanttFilterDto filterCriteria)
{
FilterCriteria = filterCriteria;
var projects = FilterProjects().ToList();
var pIds = projects.Select(x => x.ProjectID);
var data = new GanttDto {
ProductLines = FilterProductLines(),
Projects = projects.ToProjectDtoEnumerable(),
Subprojects = FilterSubProjects(pIds),
Activities = GetActivities(pIds),
ProjectTypes = UnitOfWork.ProjectTypeRepository.GetAll().OrderBy(z => z.SortOrder).ToList().ToProjectTypeDtoEnumerable()
};
return data;
}
</code></pre>
<p>Here is the <code>GetAllIncluding</code> method I'm using for each method below:</p>
<pre><code> public IEnumerable<TEntity> GetAllIncluding(params Expression<Func<TEntity, object>>[] includesProperties)
{
return includesProperties.Aggregate<Expression<Func<TEntity, object>>,
IQueryable<TEntity>>(_dbSet, (current, includeProperty)
=> current.Include(includeProperty));
}
</code></pre>
<p>Filter projects</p>
<pre><code> private IEnumerable<Project> FilterProjects()
{
var productLineIds = FilterCriteria.SelectedProjects.Where(x => x.ProductLineId != null).Select(x => x.ProductLineId).ToList();
var projectTypeIds = FilterCriteria.SelectedProjects.Where(x => x.ProjectTypeId != null).Select(x => x.ProjectTypeId).ToList();
var projectIds = FilterCriteria.SelectedProjects.Where(x => x.ProjectId != null).Select(x => x.ProjectId).ToList();
return UnitOfWork.ProjectRepository.GetAllIncluding(x => x.ProjectPersons,
x => x.ProjectPersons.Select(y => y.ProjectPersonRoles))
.Where(prj => ((productLineIds.Count == 0 || productLineIds.Any(id => id == prj.ProductLineID)) //filter by ProductLine
&& (projectTypeIds.Count == 0 || projectTypeIds.Any(id => id == prj.ProjectTypeID)) // ProjectType
&& (projectIds.Count == 0 || projectIds.Any(id => id == prj.ProjectID)) // Project
&& (FilterCriteria.StatusId.Contains(prj.ProjectStatusTypeID)) //project status
)).ToList();
}
</code></pre>
<p>To Project Dto</p>
<pre><code> public static IEnumerable<ProjectDto> ToProjectDtoEnumerable(this IEnumerable<Project> projects)
{
return projects.Select(x => new ProjectDto
{
ProjectId = x.ProjectID,
ProjectName = x.Name,
StartDate = x.StartDate,
//Children = x.SubProjects.Where(y => y.ParentSubProjectID == null).ToSubProjectDtoEnumerable(),
Organization = x.Organization.ToOrganizationDto(),
ProjectStatus = x.ProjectStatusType.Description,
ProjectTypeRowId = x.ProjectType.RowID,
ProjectTypeDescription = x.ProjectType.Description,
SortOrder = x.SortOrder,
ProjectPersons = x.ProjectPersons.ToProjectPersonDtoEnuemrable(),
ProjectStatusId = x.ProjectStatusTypeID,
ProductLineId = x.ProductLineID,
ProjectTypeId = x.ProjectTypeID,
OrganizationId = x.OrganizationID,
ProductLineName = x.ProductLine.Description,
IsShotgun = x.IsShotgun,
ShotgunLink = x.ShotgunLink,
Description = x.Description,
Flow = x.Flow,
ModelType = x.ModelType,
ModelYear = x.ModelYear,
BudgetCode = x.BudgetCode,
ProjectCode = x.ProjectCode,
ProjectLeaderDescription = x.ProjectLeaderDescription
});
}
</code></pre>
<p>Filter ProductLines</p>
<pre><code> private IEnumerable<ProductLineDto> FilterProductLines() {
var productLineIds = FilterCriteria.SelectedProjects.Where(x => x.ProductLineId != null).Select(x => x.ProductLineId).ToList();
return UnitOfWork.ProductLineRepository.Where(x => productLineIds.Count == 0 || productLineIds.Contains(x.ProductLineID)).OrderBy(z => z.SortOrder).ToList().ToProductLineDtoEnumerable();
}
</code></pre>
<p>To ProductLine Dto</p>
<pre><code> public static IEnumerable<ProductLineDto> ToProductLineDtoEnumerable(this IEnumerable<ProductLine> productLines)
{
return productLines.Select(x => new ProductLineDto
{
Name = x.Description,
ProductLineId = x.ProductLineID,
SortOrder = x.SortOrder
});
}
</code></pre>
<p>Filter SubProjects</p>
<pre><code> private IEnumerable<SubProjectDto> FilterSubProjects(IEnumerable<Guid> projectIds)
{
var sp = UnitOfWork.SubProjectRepository.GetAllIncluding(x => x.SubProject1,
x => x.SubProjectPersons,
x => x.SubProjectPersons.Select(y => y.SubProjectPersonRoles),
x => x.SubProjectTeams)
.Where(y => y.ParentSubProjectID == null && projectIds.Contains(y.ProjectID)).OrderBy(z => z.SortOrder).ToList();
return sp.ToSubProjectDtoEnumerable();
}
</code></pre>
<p>To SubProjectDto</p>
<pre><code>public static IEnumerable<SubProjectDto> ToSubProjectDtoEnumerable(this IEnumerable<SubProject> projects)
{
return projects.Select(x => new SubProjectDto
{
ProjectId = x.ProjectID,
SubProjectId = x.SubProjectID,
ProjectName = x.Name,
Children = x.SubProject1.Where(y => y.ParentSubProjectID == x.SubProjectID).ToSubProjectDtoEnumerable(),
ParentId = x.ParentSubProjectID,
SubProjectPersons = x.SubProjectPersons.ToSubProjectPersonDtoEnuemrable(),
SubProjectTypeId = x.SubProjectTypeID,
OrganizationId = x.OrganizationID,
SortOrder = x.SortOrder,
IsShotgun = x.IsShotgun,
ExpandToCustomLevel = x.expandToCustomLevel,
Teams = x.SubProjectTeams?.ToSubProjectTeamDtoEnumerable()
});
}
</code></pre>
<p>Filter Activities</p>
<pre><code>private IEnumerable<ActivityDto> GetActivities(IEnumerable<Guid> projectIds) {
if (FilterCriteria.ActivityTypeId == null)
FilterCriteria.ActivityTypeId = new List<Guid>();
if (FilterCriteria.MileStoneTypeId == null)
FilterCriteria.MileStoneTypeId = new List<Guid>();
var acts = UnitOfWork.ActivityRepository.GetAllIncluding(
x => x.ActivityTypeCustomForms,
x => x.Activity1,
x => x.ActivityPersons,
x => x.ActivityMachines,
x => x.ActivityType
).Where(act =>
(FilterCriteria.MileStoneTypeId.Contains(act.ActivityTypeID))
||
(act.ParentActivityID == null && projectIds.Contains(act.ProjectID.Value)) //by project
&&// start date - if start date is between start and end get them too
(FilterCriteria.StartDateFrom == null || (((act.EndDate >= FilterCriteria.StartDateFrom) && (act.StartDate <= FilterCriteria.StartDateFrom)) ||
((act.StartDate >= FilterCriteria.StartDateFrom && act.EndDate <= FilterCriteria.StartDateFrom)) ||
(act.StartDate >= FilterCriteria.StartDateFrom)))
&&// End date - if End date is between start and end get them too
(FilterCriteria.EndDateFrom == null || (((act.EndDate >= FilterCriteria.EndDateFrom) && (act.StartDate <= FilterCriteria.EndDateFrom)) ||
((act.StartDate >= FilterCriteria.EndDateFrom && act.EndDate <= FilterCriteria.EndDateFrom)) ||
(act.EndDate <= FilterCriteria.EndDateFrom)))
&& //activity type
(FilterCriteria.ActivityTypeId.Contains(act.ActivityTypeID))
&&//resource type
(FilterCriteria.ResourceTypeIds == null || act.ActivityPersons.Any(ap => FilterCriteria.ResourceTypeIds.Contains(ap.ResourceTypeID.Value)))
&&//PersonID
(FilterCriteria.PersonId == null || act.ActivityPersons.Any(ap => (ap.PersonID != null && FilterCriteria.PersonId.Contains(ap.PersonID.Value))))
).OrderBy(z => z.SortOrder).ToList().ToActivityDtoEnumerable();
return acts;
}
</code></pre>
<p>To Activity Dto</p>
<pre><code>public static IEnumerable<ActivityDto> ToActivityDtoEnumerable(this IEnumerable<Activity> activities)
{
return activities.Select(x => new ActivityDto
{
ActivityId = x.ActivityID,
ActivityName = x.Name,
Description = x.SpecialDescription,
ActivityType = x.ActivityType.ToActivityTypeDto(),
ActivityDateRange = new DateRange(x.StartDate, x.EndDate),
StartDate = x.StartDate,
EndDate = x.EndDate,
Duration = x.Duration,
PctComplete = x.PctComplete,
Name = x.Name,
ActivityPersons = x.ActivityPersons.ToActivityPersonDtoEnumerable(),
ActivityMachines = x.ActivityMachines.ToActivityMachineDtoEnumerable(),
Organization = x.Organization.ToOrganizationDto(),
OrganizationId = x.OrganizationID,
SortOrder = x.SortOrder,
ProjectName = x.Project == null ? "Not Found" : x.Project.Name,
PlannedStart = x.EarliestStartDate,
PlannedEnd = x.EarliestEndDate,
LaserProcessId = x.LaserProcessID,
LaserThicknessId = x.LaserThicknessID,
MaterialId = x.MaterialID,
MillingMinimumRadiusId = x.MillingMinimumRadiusID,
MillingScallopHeightId = x.MillingScallopHeightID,
ModelCategoryId = x.ModelCategoryID,
ModelTypeId = x.ModelTypeID,
RpfdmNozzleId = x.RPFDMNozzleID,
RpfillTypeId = x.RPFillTypeID,
RpsparseId = x.RPSparseID,
VarianceId = x.VarianceID,
QuantityId = x.QuantityID,
SpecNotes = x.SpecNotes,
Children = x.Activity1.ToActivityDtoEnumerable(),
CustomForm = x.ActivityTypeCustomForms.Any() ? x.ActivityTypeCustomForms.ToActivityCustomFormDto() : new List<ActivityTypeCustomFormDto>(),
PartsDetailsDescription = x.PartsDetailsDescription,
});
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T14:33:52.813",
"Id": "447482",
"Score": "1",
"body": "Simple optimization is not using `IEnumerable.Contains()` but using `HashSet` or `Dictionary` will reduce number of loops. I would change the 3 vars by HashSet since they are all list of `native` values (Ids)"
}
] |
[
{
"body": "<p>It might be boring to hear it again, but I have to ask :)</p>\n\n<ol>\n<li>Why do you think your application need performance optimisations?</li>\n<li>Is your bottle neck in these parts of code which you provided?</li>\n<li>Maybe problem is with database/external service/network?</li>\n<li>Have you measured processing and communication time? <a href=\"https://docs.microsoft.com/pl-pl/dotnet/api/system.diagnostics.stopwatch?view=netframework-4.8\" rel=\"nofollow noreferrer\">Stopwatch</a></li>\n<li>Do you have some kind of monitoring of application, that shows\nexactly that its performance is degrading? <a href=\"https://grafana.com/\" rel=\"nofollow noreferrer\">Grafana</a></li>\n<li>Have you tried benchmarking? <a href=\"https://benchmarkdotnet.org/articles/overview.html\" rel=\"nofollow noreferrer\">BenchmarkDotNet</a></li>\n<li>How about full GC? <a href=\"https://prodotnetmemory.com/\" rel=\"nofollow noreferrer\">Pro .NET memory management</a></li>\n<li>Have you tried profiling? <a href=\"https://github.com/microsoft/perfview\" rel=\"nofollow noreferrer\">PerfView</a></li>\n</ol>\n\n<p>If you're not sure if it's a problem, then don't do optimisations. As <a href=\"https://en.wikipedia.org/wiki/Donald_Knuth\" rel=\"nofollow noreferrer\">Donald Knuth</a> said </p>\n\n<blockquote>\n <p>Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.</p>\n</blockquote>\n\n<p>Back to the code, it's my personal opinion, but I don't like LINQ, because of <a href=\"https://devblogs.microsoft.com/pfxteam/know-thine-implicit-allocations/\" rel=\"nofollow noreferrer\">implicit allocations</a> which lead to pressure on GC (you've made few of them). Also I don't get it, why you're invoking ToList() method? You operate on IEnumerables everywhere. If you invoke ToList() then you're allocating list and killing main feature of LINQ - laziness. Condition you wrote is really hard to read, I would work on that to simplify it somehow. I know it's not related with performance, but it's still code review :).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T10:24:29.677",
"Id": "445915",
"Score": "1",
"body": "You write that only profiled/benchmarked code should be optimized but at the same time treat linq as being always bad. This is simply not true. I have a lot o libraries built virtually entirely with linq and they are super fast. I cannot imagine doing it any other way which would mean a lot of work. The few edge cases where you need the last tick of prefomance don't prove linq bad. On the contrary, linq is best for the majority of tasks. That's why you get +1 for the first part and - 1 for the second one. The sum is 0."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T11:56:03.877",
"Id": "445931",
"Score": "1",
"body": "I totally agree that LINQ is best for the majority of tasks. I didn't say that it's bad, I said that I don't like it, it's not the same :) as in attached blog post it can lead to some implicit allocations that can put more pressure on GC. In OP code you can find few of them, but as I wrote in the first part of the answer - measure, measure, measure.\n\nI'm sorry if my answer wasn't clear enough. I didn't want to discredit anything.\n\nAlso, thank you for your comment. It was very constructive and I will have in my all your points in mind."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T09:56:07.063",
"Id": "229302",
"ParentId": "229251",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229302",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T15:06:36.237",
"Id": "229251",
"Score": "1",
"Tags": [
"c#",
"performance",
"linq",
"entity-framework",
"asp.net-mvc"
],
"Title": "ASP.NET MVC 5, EF 6 filter performance"
}
|
229251
|
<p>I have been working through a <a href="http://neuralnetworksanddeeplearning.com" rel="nofollow noreferrer">tutorial on neural networks</a>. I have then been translating the code to java, to help improve my understanding of what the code is doing.</p>
<p><a href="http://neuralnetworksanddeeplearning.com/chap2.html#backprop_over_minibatch" rel="nofollow noreferrer">The book</a> mentions a way of speeding up the program:</p>
<blockquote>
<p>Our implementation of stochastic gradient descent loops over training examples in a mini-batch. It's possible to modify the backpropagation algorithm so that it computes the gradients for all training examples in a mini-batch simultaneously. The idea is that instead of beginning with a single input vector, x, we can begin with a matrix X=[x1x2…xm] whose columns are the vectors in the mini-batch. We forward-propagate by multiplying by the weight matrices, adding a suitable matrix for the bias terms, and applying the sigmoid function everywhere. We backpropagate along similar lines.</p>
</blockquote>
<p>I get the concept of treating the items in a mini-batch as an array of items, but I'm struggling to figure out the maths for implementing this change.</p>
<p>I've posted because the code is working; I'm just wanting to implement this improvement to get it to run faster.</p>
<p>In the code below, the comments are (mostly) the python code that the java was translated from:</p>
<p><strong>SGD</strong></p>
<pre><code>// for j in xrange(epochs):
for (int j = 1; j <= maxEpochs; j++)
{
// random.shuffle(training_data)
Collections.shuffle(trainingData);
// mini_batches = [training_data[k:k+mini_batch_size] for k in xrange(0, trainingData.size, mini_batch_size)]
ArrayList<ArrayList<MnistEntry>> miniBatches = MLMaths.segment(trainingData, miniBatchSize);
// for mini_batch in mini_batches:
for (ArrayList<MnistEntry> miniBatch : miniBatches)
{
// self.update_mini_batch(mini_batch, eta)
if (!miniBatch.isEmpty())
{
updateMiniBatch(miniBatch, schedule.eta, lambda, nTraining, regStrategy);
}
}
// etc.
}
</code></pre>
<p><strong>updateMiniBatch</strong></p>
<pre><code>private void updateMiniBatch(ArrayList<MnistEntry> miniBatch, double eta, double lambda, int totalSizeOfTrainingSet
, RegularisationStrategy regStrategy)
{
// nabla_b = [np.zeros(b.shape) for b in self.biases]
ArrayList<double[][]> nablaB = MLMaths.fill(0.0, biases);
// nabla_w = [np.zeros(w.shape) for w in self.weights]
ArrayList<double[][]> nablaW = MLMaths.fill(0.0, weights);
// for x, y in mini_batch:
// TODO: Speed improvement by multiplying over the minibatch all at once (see http://neuralnetworksanddeeplearning.com/chap2.html#backprop_over_minibatch)
for (int i = 0; i < miniBatch.size(); i++)
{
MnistEntry e = miniBatch.get(i);
// double[pixels_in_image][1] - each pixel in the image is represented by a double[] containing a single value in the range 0..1 (white..black)
double[][] x = e.getImageDataAsDoubles();
double[][] y = e.getLabelAsArray(); // answer, vectorised array of length 10, where each entry is a double[1] containing either {0} for the incorrect answer; or {1} for the correct answer.
// delta_nabla_b, delta_nabla_w = self.backprop(x, y)
// note: using SimpleEntry as the simplest Pair type in java - they're not really key-value
SimpleEntry<ArrayList<double[][]>, ArrayList<double[][]>> deltaNablas = backprop(x,y);
ArrayList<double[][]> deltaNablaB = deltaNablas.getKey();
ArrayList<double[][]> deltaNablaW = deltaNablas.getValue();
// nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
ArrayList<double[][][]> zipB = MLMaths.zip(nablaB, deltaNablaB);
for (int n = 0; n <zipB.size(); n++)
{
double[][] nb = zipB.get(n)[0];
double[][] dnb = zipB.get(n)[1];
nablaB.set(n, MLMaths.add(nb, dnb));
}
// nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]
ArrayList<double[][][]> zipW = MLMaths.zip(nablaW, deltaNablaW);
for (int n = 0; n <zipW.size(); n++)
{
double[][] nw = zipW.get(n)[0];
double[][] dnw = zipW.get(n)[1];
nablaW.set(n, MLMaths.add(nw, dnw));
}
}
// eta/len(mini_batch)
double etaOverMBSize = (eta / miniBatch.size()); // calculate here to save repeated calcualtion, as these values don't change
double regularisationRate = 1;
if (regStrategy == RegularisationStrategy.L1 || regStrategy == RegularisationStrategy.L2)
{
regularisationRate = ((eta*lambda)/(double)totalSizeOfTrainingSet);
}
else if(regStrategy == RegularisationStrategy.NONE)
{
regularisationRate = 1;
}
// for L2 regularisation,
// self.weights = [(1-eta*(lmbda/n))*w-(eta/len(mini_batch))*nw for w, nw in zip(self.weights, nabla_w)]
// for L1 reg:
// self.weights = [w-((eta*(lmbda/n))*sgn(w))-(eta/len(mini_batch))*nw for w, nw in zip(self.weights, nabla_w)]
ArrayList<double[][][]> zipW = MLMaths.zip(weights, nablaW);
for (int n = 0; n <zipW.size(); n++)
{
double[][] w = zipW.get(n)[0];
double[][] nw = zipW.get(n)[1];
if (regStrategy == RegularisationStrategy.L1)
{
weights.set(n, MLMaths.subtract(MLMaths.subtract(w, MLMaths.multiply(regularisationRate, MLMaths.sign(w))),MLMaths.multiply(etaOverMBSize, nw)));
}
else if (regStrategy == RegularisationStrategy.L2)
{
weights.set(n, MLMaths.multiply(1-regularisationRate, MLMaths.subtract(w, MLMaths.multiply(etaOverMBSize, nw))));
}
else if (regStrategy == RegularisationStrategy.NONE)
{
weights.set(n, MLMaths.subtract(w, MLMaths.multiply(etaOverMBSize, nw)));
}
else
{
throw new IllegalArgumentException("Regularisation Strategy " + regStrategy + " not implemented.");
}
}
// self.biases = [b-(eta/len(mini_batch))*nb for b, nb in zip(self.biases, nabla_b)]
ArrayList<double[][][]> zipB = MLMaths.zip(biases, nablaB);
for (int n = 0; n <zipB.size(); n++)
{
double[][] b = zipB.get(n)[0];
double[][] nb = zipB.get(n)[1];
biases.set(n, MLMaths.subtract(b, MLMaths.multiply(etaOverMBSize, nb)));
}
}
</code></pre>
<p><strong>Backpropagation</strong></p>
<pre><code>private SimpleEntry<ArrayList<double[][]>, ArrayList<double[][]>> backprop(double[][] x, double[][] y)
{
// nabla_b = [np.zeros(b.shape) for b in self.biases]
ArrayList<double[][]> nablaB = MLMaths.fill(0.0, biases);
// nabla_w = [np.zeros(w.shape) for w in self.weights]
ArrayList<double[][]> nablaW = MLMaths.fill(0.0, weights);
// # feedforward
// activation = x
double[][] activation = x;
// activations = [x] # list to store all the activations, layer by layer
ArrayList<double[][]> activations = new ArrayList<>();
activations.add(x);
// zs = [] # list to store all the z vectors, layer by layer
ArrayList<double[][]> zs = new ArrayList<>();
// for b, w in zip(self.biases, self.weights):
ArrayList<double[][][]> zip = MLMaths.zip(biases, weights);
for (double[][][] bw : zip)
{
double[][] b = bw[0];
double[][] w = bw[1];
//z = np.dot(w, activation)+b
double[][] z = MLMaths.dotProduct(w, activation);
z = MLMaths.add(z, b);
// zs.append(z)
zs.add(z);
// activation = sigmoid(z)
activation = MLMaths.sigmoid(z);
// activations.append(activation)
activations.add(activation);
}
// # backward pass
// delta = (self.cost).delta(zs[-1], activations[-1], y)
double[][] delta = cost.delta(zs.get(zs.size()-1), activations.get(activations.size()-1), y);
// nabla_b[-1] = delta
nablaB.set(nablaB.size()-1, delta);
//nabla_w[-1] = np.dot(delta, activations[-2].transpose())
nablaW.set(nablaW.size()-1, MLMaths.dotProduct(delta, MLMaths.transpose(activations.get(activations.size()-2))));
// for l in xrange(2, self.num_layers):
for (int l = 2; l < numLayers; l++)
{
// z = zs[-l]
double[][] z = zs.get(zs.size()-l);
// sp = sigmoid_prime(z)
double[][] sp = MLMaths.sigmoidPrime(z);
// delta = np.dot(self.weights[-l+1].transpose(), delta) * sp
delta = MLMaths.multiply(MLMaths.dotProduct(MLMaths.transpose(weights.get((weights.size()-l)+1)),delta), sp);
// nabla_b[-l] = delta
nablaB.set(nablaB.size()-l, delta);
// nabla_w[-l] = np.dot(delta, activations[-l-1].transpose())
nablaW.set(nablaW.size()-l, MLMaths.dotProduct(delta,MLMaths.transpose(activations.get((activations.size()-l)-1))));
}
// return (nabla_b, nabla_w)
return new SimpleEntry<>(nablaB, nablaW);
}
</code></pre>
<p>My intuition is saying that I should be able to get rid of the loop <code>for (int i = 0; i < miniBatch.size(); i++)</code> in the <code>updateMiniBatch</code> method altogether, by merging the x's into a double[][][]; and passing that into the <code>backprop</code> method instead.</p>
<p>The questions are:</p>
<ul>
<li>What is the maths (matrix transformations) required to make this work?</li>
<li>Is this actually only a saving in Python, because it has more fully-formed mathematical operations?</li>
</ul>
<p>The <code>MLMaths</code> class is a helper class I have written to do matrix mathematics on arrays in Java, specifically for this project. It's based on <a href="https://gist.github.com/Jeraldy/7d4262db0536d27906b1e397662512bc" rel="nofollow noreferrer">this</a>.</p>
<p>The <code>MnistEntry</code> class simply stores the data in the correct format.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T15:47:59.820",
"Id": "229254",
"Score": "1",
"Tags": [
"java",
"performance",
"array",
"matrix",
"machine-learning"
],
"Title": "Stochastic gradient descent - backpropagation over mini-batches in one go"
}
|
229254
|
<p>I wrote a simple timestamping filter that prepends each line with the UNIX timestamp in nanosecond precision as returned by clock_gettime, as well as the difference to the previous timestamp.</p>
<pre class="lang-bash prettyprint-override"><code>for i in {01..15}; do printf '%s\n' "input $i"; sleep 0."$i"; done | ./timestamper
BEGIN CLOCK_REALTIME. No monotonicity guaranteed.
1568821823.653421652 ▒ 0.00 ▒ input 01
1568821823.664177279 ▒ 10.76 ▒ input 02
1568821823.688901171 ▒ 24.72 ▒ input 03
1568821823.720398267 ▒ 31.50 ▒ input 04
1568821823.761946412 ▒ 41.55 ▒ input 05
1568821823.813324331 ▒ 51.38 ▒ input 06
1568821823.874711521 ▒ 61.39 ▒ input 07
1568821823.946274595 ▒ 71.56 ▒ input 08
1568821824.027733690 ▒ 81.46 ▒ input 09
1568821824.119107230 ▒ 91.37 ▒ input 10
1568821824.220571393 ▒ 101.46 ▒ input 11
1568821824.331862345 ▒ 111.29 ▒ input 12
1568821824.453478061 ▒ 121.62 ▒ input 13
1568821824.584820550 ▒ 131.34 ▒ input 14
1568821824.726266816 ▒ 141.45 ▒ input 15
END CLOCK_REALTIME
</code></pre>
<p>I mainly wrote this program because the shell code</p>
<pre class="lang-bash prettyprint-override"><code>while IFS= read -r line
do
printf '%s | %s\n' "$(date -u '+%F %T.%4N')" "$line"
done
</code></pre>
<p>forks a "date" process for every line, which is about 800 times slower than the C program, on some unspecified amd64 system at uni.</p>
<p>A quick test:</p>
<pre class="lang-bash prettyprint-override"><code>$ time cat /dev/urandom | tr -dc '[[:print:]]' | tr 'A' '\n' | head -n 10000000 > /dev/null
real 0m23.280s
$ time cat /dev/urandom | tr -dc '[[:print:]]' | tr 'A' '\n' | head -n 10000000 | ./timestamper > /dev/null
real 0m26.624s
</code></pre>
<p>which makes for an overhead of about 14 per cent, on some unspecified amd64 system at uni.</p>
<p>In this review, I'd like to focus on code quality and readability while not completely forgetting performance. In particular, </p>
<ul>
<li><p>Should I do away with the #defines and use functions instead?</p></li>
<li><p>Any more error conditions to check for?</p></li>
</ul>
<p>More questions (less important today):</p>
<ul>
<li><p>Is there a nice way of handling really long lines, short of splitting and joining them by hand? I don't want to allocate tons of memory, even if it has to be done only once.</p></li>
<li><p>Any suggestions on the column separator? (Doing <code>... | ./timestamper | tr $'\x1a' '|'</code> is easy enough, though.) TAB does not work because "git status" output uses it, which came as a surprise. I would like to be able to pass anything through the filter that could reasonably be produced by verbose programs. I'm thinking of SSH clients and the like.</p></li>
<li><p>I took the liberty to replace CR with LF because I do not want to lose information. Any thoughts on that?</p></li>
<li><p>What about locale issues? Should I worry about them at all or just pass through whatever comes in?</p></li>
</ul>
<p>Oh, and is there a magic pill that forces me to write comments consistently in English?</p>
<p>So, finally, here is the code:</p>
<pre><code>/*
NAME
timestamper - timestamp and kill-carriage-return
SYNOPSIS
./timestamper
DESCRIPTION
Ersetzt in jeder über die Standardeingabe eingelesenen Zeile,
nachdem die Dauer seit Eintreffen der vorhergehenden Zeile
festgehalten wurde, das Wagenrücklaufzeichen (ASCII 13 = 0x0D)
durch ein Neue-Zeile-Zeichen (ASCII 10 = 0x0A) und schreibt den
Zeitstempel des Eintreffens und die Dauer, gefolgt von
der veränderten Zeile, auf die Standardausgabe. Als
Trennzeichen wird der "substitute character" (ASCII 26 = 0x1A)
genutzt, damit alle gewöhnlichen druckbaren Zeichen die
Prozedur unbeschadet überstehen.
nach https://stackoverflow.com/a/12722972
2019-09-14
Dieser Code wurde bisher unter Debian GNU/Linux 9 und unter
Ubuntu 18.04 LTS getestet.
OPTIONS, ARGUMENTS, PARAMETERS
Nichts von alledem.
EXIT STATUS
0 bei erfolgreicher Ausführung,
1 bei Fehler.
Ein Fehler liegt insbesondere dann vor, wenn
- von der Standardeingabe nicht gelesen werden kann;
- auf die Standardausgabe nicht geschrieben werden kann;
- das Abfragen der Uhrzeit fehlschlägt.
HOW TO COMPILE
Für schnelle Tests kann man
gcc timestamper.c -o timestamper
nutzen. Man kann aber auch
gcc -std=c99 -Wall -Wextra -Wunused -Wfatal-errors -pedantic -Os timestamper.c -o timestamper
versuchen.
WHAT THE FUCK?
Die Existenzberechtigung dieses Programms ergibt sich aus der
Tatsache, dass jeder "date"-Aufruf in der Shell einen neuen
Prozess startet, was, wenn es einmal pro gelesener Zeile
passiert, etwas viel ist. Details sind am Ende dieser Datei
nachzulesen.
BUGS
Bisher werden von jeder Zeile, die 10000 oder mehr Zeichen
enthält, nur die ersten 9999 Zeichen verarbeitet.
COPYRIGHT
(c) Thure Dührsen, 2019-09-15...18
Permission is hereby granted, free of charge, to anyone
obtaining a copy of this software and the accompanying
documentation files, to do WHATEVER THEY WANT, subject to the
following conditions:
(a) Read and understand the file 'license.txt' in the project
repository's root directory.
(b) Acknowledge that this software draws substantially from
StackOverflow posts, and that any public releases must
comply with the terms laid out in the Creative Commons
Attribution-ShareAlike 4.0 International Public License,
https://creativecommons.org/licenses/by-sa/4.0/legalcode
*/
#define _POSIX_C_SOURCE 199309L /* man 2 clock_getres */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
void usage(void) {
fprintf (stderr, "%s\n",
"\n\
Usage: \n\
\n\
timestamper\n\
\n\
No options, no arguments.\n"
);
}
#define sep ((char)0x1A) /* ASCII substitute character */
/* Speed is everything. No functions. Just #defines. */
#define PROCESSLINE \
\
/* search for first '\n' and change it to \0 */ \
/* nach https://stackoverflow.com/a/28462221 */ \
buf[strcspn(buf, "\n")] = 0; \
\
/* Logdateien sind ohne Wagenrücklauf einfacher zu lesen */ \
for (i = 0; (b = buf[i]) != 0; i++) { \
if (b == '\r') {buf[i] = '\n';} \
} /************************************************************/
#define READCLOCK(i) \
\
/* CLOCK_MONOTONIC has an unspecified starting point */ \
/* CLOCK_REALTIME starts on 1970-01-01 */ \
\
r = clock_gettime(CLOCK_REALTIME, &t##i); \
\
if (r != 0) { \
fprintf(stderr, "%s\n", "Cannot read clock"); \
exit(1); \
} /************************************************************/
#define WRITELINE(duration, i) \
\
r = printf ("%010ld.%09ld %c %10.2f %c %s\n", \
\
/* tv_sec ist vom Typ time_t */ \
(long int) t##i.tv_sec, \
/* time_t ist auf amd64-Rechnern ein Synonym für long int,
was bei anderen Architekturen nicht der Fall sein muss.
Der Cast nach long int ist daher vermutlich nötig. */ \
\
/* tv_nsec ist ein long int */ \
t##i.tv_nsec, \
\
sep, \
\
duration, \
\
sep, \
\
buf); \
\
if (r < 0) { \
fprintf(stderr, "%s\n" ,"Cannot write to stdout"); \
exit(1); \
} \
\
if (r > bufsize * 0.95) { \
fprintf(stderr, "%s\n", \
"That's some jolly long lines you have there..."); \
} /************************************************************/
int main (int argc, char** argv) {
if (argc != 1 || argv[1] != NULL) {
/* suppress compiler warnings about argc and argv */
usage();
exit(1);
}
struct timespec t1, t2;
const int bufsize = 10000;
char buf[bufsize];
int i;
int b; /* ein einzelnes Zeichen */
int r; /* Rückgabewert von clock_gettime, printf */
void* rp; /* Rückgabewert von fgets */
long int d; /* Differenz zweier Zeitstempel */
double df; /* wie oben, aber Millisekunden */
printf("%s\n","BEGIN CLOCK_REALTIME. No monotonicity guaranteed.");
rp = fgets(buf, bufsize, stdin);
if (rp == NULL) {
fprintf(stderr, "%s\n" ,"Nothing on stdin");
exit(1);
}
PROCESSLINE;
READCLOCK(1);
/* Gib 0 als Zeitdifferenz sowie die Zeile aus */
WRITELINE((double)0, 1);
/* Solange noch Zeilen über stdin eingelesen werden können... */
while (fgets(buf, bufsize, stdin) != NULL) {
PROCESSLINE;
READCLOCK(2);
/* Bilde Differenz */
d = ((t2.tv_sec - t1.tv_sec)*1000000000L
+t2.tv_nsec) - t1.tv_nsec;
df = d / 1000000.0;
/* Rette vorigen Zeitstempel: setze t1 := t2 */
t1 = t2;
/* Gib Differenz und eingelesene Zeile
auf der Standardausgabe aus */
WRITELINE(df, 2);
}
printf("%s\n","END CLOCK_REALTIME");
return 0;
}
/*
performance tests omitted here,
see description in the question
*/
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>Should I do away with the #defines and use functions instead?</p>\n</blockquote>\n\n<p>Probably.</p>\n\n<blockquote>\n <p>Speed is everything. No functions. Just #defines.</p>\n</blockquote>\n\n<p>Are you so sure? Have you tested the speed of your application when using regular functions? Optimizing C compilers are pretty good. They'll be able to inline away the functions that you write. Defaulting to writing <code>#define</code> macros based on the belief that it will make things faster is classic premature optimization. The macros might even <em>be</em> faster, but you haven't proven so, and they aren't the first thing you should reach for. Instead, you should first make your program correct; then you should profile your application to find bottlenecks. It's going to be unlikely that you'll find a bottleneck caused by writing functions, and using macros comes at a heavy cost of legibility and maintainability.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T18:40:01.973",
"Id": "446192",
"Score": "0",
"body": "To be honest, I haven't, and I took my numerical analysis instructor's word in good faith. But it's the weekend now, so I'll write a little test harness for good measure."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T17:23:36.047",
"Id": "229258",
"ParentId": "229255",
"Score": "1"
}
},
{
"body": "<p>Firstly, I must apologies that my German understanding isn't fluent enough to read all your comments.</p>\n\n<p>I think your intuition is right that you ought to be using functions rather than preprocessor macros - the latter are just too fragile, and anyway, good compilers are able to inline functions. I would recommend <code>-O3 -march=native</code> in your GCC flags if speed is your main concern.</p>\n\n<p>The code builds mostly clean, and gives Valgrind no cause to grumble - well done!</p>\n\n<hr>\n\n<p>A better way to run your tests might be to time only the timestamper itself:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code></dev/urandom tr -dc '[[:print:]]' | tr 'A' '\\n' | head -n10000000 \\\n | time ./timestamper >/dev/null\n</code></pre>\n\n<p>This saves you having to do a subtraction. Note that overhead \"percentage\" is somewhat meaningless here, as we could make the input stream arbitrarily complex and reduce the percentage to any figure we want!</p>\n\n<p>I've also eliminated the unnecessary <code>cat</code>, even though this isn't a <a href=\"/questions/tagged/sh\" class=\"post-tag\" title=\"show questions tagged 'sh'\" rel=\"tag\">sh</a> review.</p>\n\n<hr>\n\n<p>There's a bug, which is easily demonstrated: we always print a time offset of zero for the first line, but it would be more useful to print the time since the program was started. I'd be happy to go with a compromise, and just use the time that <code>main()</code> is entered.</p>\n\n<hr>\n\n<p>I'm not convinced of the need for the buffer (and certainly not of the need to remove the final newline, only to add one when we print), as we can work on a character by character basis, and lean on the buffering inside <code><stdio.h></code>:</p>\n\n<pre><code>#include <stdbool.h>\nint main(void)\n{\n int c;\n bool is_first = true;\n\n if (clock_gettime(CLOCK_REALTIME, &last_time)) {\n perror(\"Cannot read clock\");\n exit(EXIT_FAILURE);\n }\n\n while ((c = getchar()) != EOF) {\n if (is_first) {\n print_time_prefix();\n is_first = false;\n }\n putchar(c);\n if (c == '\\n') {\n is_first = true;\n }\n }\n}\n</code></pre>\n\n<p>This is a little slower (8.4 seconds, compared with 5.8 seconds for the original), but much easier to work with.</p>\n\n<hr>\n\n<p>My take on the separator is that control characters are a poor choice for printing; I'd much rather see tabs than <code>^Z</code> in the output. Most tools that read tab-separated values can be told how many fields to use.</p>\n\n<hr>\n\n<p>My full program uses no macros, and a single global variable:</p>\n\n<pre><code>#define _POSIX_C_SOURCE 199309L /* man 2 clock_getres */\n\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\nstruct timespec last_time;\n\nstatic void print_time_prefix(void)\n{\n struct timespec now;\n if (clock_gettime(CLOCK_REALTIME, &now)) {\n perror(\"Cannot read clock\");\n exit(EXIT_FAILURE);\n }\n\n double interval = now.tv_sec - last_time.tv_sec\n + .000000001 * (now.tv_nsec - last_time.tv_nsec);\n\n printf(\"%010ld\" \".\" \"%09ld\" \"\\t\" \"%10.2f\" \"\\t\",\n now.tv_sec, now.tv_nsec, interval);\n\n last_time = now;\n}\n\nint main(void)\n{\n if (clock_gettime(CLOCK_REALTIME, &last_time)) {\n perror(\"Cannot read clock\");\n exit(EXIT_FAILURE);\n }\n\n bool is_first = true;\n int c;\n while ((c = getchar()) != EOF) {\n if (is_first) {\n print_time_prefix();\n is_first = false;\n }\n putchar(c);\n if (c == '\\n') {\n is_first = true;\n }\n }\n}\n</code></pre>\n\n<p>Some things of note:</p>\n\n<ul>\n<li>I use the predefined <code>EXIT_FAILURE</code> macro as exit status in the error case.</li>\n<li>Unless we're stuck in the 20th century, we don't need to declare all the variables at the beginning of their scope.</li>\n<li><code>clock_gettime()</code> sets <code>errno</code> on failure, so use <code>perror()</code> to report that.</li>\n<li>I wrote the format string as multiple concatenated segments to help it line up with the arguments, and separate the literal parts from the conversions.</li>\n</ul>\n\n<p>Things not addressed in my version:</p>\n\n<ul>\n<li>We might consider keeping the interval as a pair of integral values (as with the timestamps), rather than creating and printing a floating-point value.</li>\n<li>We ought to print using the user's expected decimal separator (e.g. <code>,</code>), instead of hard-coded <code>.</code> in the format string. I've not done this myself, but I believe what we need to do is\n\n<ol>\n<li><code>setlocale(LC_ALL, \"\");</code> early on, as usual for a locale-aware program.</li>\n<li>Obtain the formatting rules using <code>localeconv()</code>.</li>\n<li>Examine the <code>decimal_point</code> member of the resulting <code>lconv</code> object.</li>\n</ol></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T09:35:33.593",
"Id": "445909",
"Score": "0",
"body": "Many thanks for your suggestions! Reading input on a char by char basis is the sort of thing I tend to miss when writing the algorithm on paper without a computer in front of me :) Also, while `if (clock_gettime(...)) {perror(...)}` is correct, it reads like `if you can query the clock, throw an error`. But that's just me, I guess ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T12:23:53.107",
"Id": "445933",
"Score": "0",
"body": "Well, you can throw in a `!= 0` if that makes it read easier for you (yes, I also find it reads that way, but years of C have inured me to the different error returns of library calls!). The `perror()` call is the real point here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T12:37:06.763",
"Id": "445936",
"Score": "0",
"body": "@Thure, I've updated with some handwaving to answer your specific question about locale handling. I hope that's helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T18:36:17.387",
"Id": "446190",
"Score": "0",
"body": "thanks, I'll take a look. BTW what compiler do you use, as you say the code builds mostly clean? Using `gcc -std=c99 -Wall -Wextra -Wunused -Wfatal-errors -pedantic -Os timestamper.c -o timestamper` gives no output on my machine. I'm using gcc 6.3.0 on Debian 9."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T07:42:15.703",
"Id": "446409",
"Score": "0",
"body": "I also had ` -Warray-bounds -Wstrict-prototypes -Wconversion -Wwrite-strings` (with GCC 9.2.1). There's a conversion warning when promoting the time values to `double`, but I believe the code is fine for the values that could actually be present, on any actual Unix or Linux platform."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T17:25:14.053",
"Id": "229259",
"ParentId": "229255",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229259",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T16:03:48.167",
"Id": "229255",
"Score": "4",
"Tags": [
"c",
"datetime",
"logging",
"interval"
],
"Title": "Simple timestamping filter in C"
}
|
229255
|
<p>I have been working on a vector library for a little bit now. And at this point the basics are down and I am looking for some tips and advic - this may include: </p>
<ol>
<li>suggestions for things that might be missing and should be added</li>
<li>improvements for readability and of-course efficiency </li>
<li>if you have an important tip or advice that I didn't think of, please feel free to add it :)</li>
</ol>
<p>See the code below for a <code>Vector3</code> struct and a <code>VectorX</code> struct. I have left out the Vector2, 4 for now because those are build in the exact same way as <code>Vector3</code>. <code>VectorX</code> is a struct for vectors which have no predefined length. See code below: </p>
<p>Vector3: </p>
<pre><code>using System;
namespace Development
{
public struct Vector3 : IEquatable<Vector3>
{
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
public int VectorCount { get { return 3; } }
public Vector3(float value)
{
X = value;
Y = value;
Z = value;
}
public Vector3(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
public Vector3(Vector3 vector)
{
X = vector.X;
Y = vector.Y;
Z = vector.Z;
}
public Vector3(float[] arr)
{
X = arr[0];
Y = arr[1];
Z = arr[2];
}
public Vector3(float[] arr, int startIndex)
{
if (startIndex > arr.Length - 3) { throw new Exception("start index doesnt leave enough space to fill all vector parameters"); }
else
{
X = arr[startIndex];
Y = arr[startIndex + 1];
Z = arr[startIndex + 2];
}
}
public override string ToString()
{
return "<" + X + ", " + Y + ", " + Z + ">";
}
public float[] ToArray()
{
return new float[] { X, Y, Z };
}
public Vector3 UpdateFromArray(float[] arr)
{
if (arr.Length < 3) throw new Exception("Array is too small to convert to vector");
else
{
X = arr[0];
Y = arr[1];
Z = arr[2];
}
return this;
}
public Vector3 UpdateFromArray(float[] arr, int startIndex)
{
if (startIndex + 2 > arr.Length - 1) throw new Exception("startindex is too high to fill vector");
else
{
X = arr[startIndex];
Y = arr[startIndex + 1];
Z = arr[startIndex + 2];
}
return this;
}
public bool Equals(Vector3 other) // not implemented
{
throw new NotImplementedException();
}
public Vector3 Abs()
{
X = (X < 0) ? X *= -1 : X;
Y = (Y < 0) ? Y *= -1 : Y;
Z = (Z < 0) ? Z *= -1 : Z;
return this;
}
public float Length()
{
return MathF.Sqrt(MathF.Pow(X, 2) + MathF.Pow(Y, 2) + MathF.Pow(Z, 2));
}
public float Dist(Vector3 other)
{
return MathF.Sqrt(MathF.Pow((this.X - other.X), 2) + MathF.Pow((this.Y - other.Y), 2) + MathF.Pow((this.Z - other.Z), 2));
}
public Vector3 Min(Vector3 min)
{
this.X = (this.X < min.X) ? this.X : min.X;
this.Y = (this.Y < min.Y) ? this.Y : min.Y;
this.Z = (this.Z < min.Z) ? this.Z : min.Z;
return this;
}
public Vector3 Max(Vector3 max)
{
this.X = (this.X > max.X) ? this.X : max.X;
this.Y = (this.Y > max.Y) ? this.Y : max.Y;
this.Z = (this.Z > max.Z) ? this.Z : max.Z;
return this;
}
public Vector3 Clamp(Vector3 min, Vector3 max)
{
this.X = (this.X < min.X) ? min.X : this.X = (this.X > max.X) ? max.X : this.X;
this.Y = (this.Y < min.Y) ? min.Y : this.Y = (this.Y > max.Y) ? max.Y : this.Y;
this.Z = (this.Z < min.Z) ? min.Z : this.Z = (this.Z > max.Z) ? max.Z : this.Z;
return this;
}
public Vector3 Lerp(Vector3 to, float amount)
{
amount = Math.Clamp(amount, 0, 1);
this.X = (this.X - to.X) * amount + to.X;
this.Y = (this.Y - to.Y) * amount + to.Y;
this.Z = (this.Z - to.Z) * amount + to.Z;
return this;
}
public Vector3 Normalize()
{
float scalar = 1 / MathF.Sqrt(MathF.Pow(X, 2) + MathF.Pow(Y, 2) + MathF.Pow(Z, 2));
X *= scalar;
Y *= scalar;
Z *= scalar;
return this;
}
public float Dot(Vector3 other)
{
return this.X * other.X + this.Y * other.Y + this.Z * other.Z;
}
public static Vector3 Abs(Vector3 value)
{
return value.Abs();
}
public static Vector3 Clamp(Vector3 value, Vector3 min, Vector3 max)
{
return value.Clamp(min, max);
}
public static Vector3 Min(Vector3 value, Vector3 min)
{
return value.Min(min);
}
public static Vector3 Max(Vector3 value, Vector3 max)
{
return value.Max(max);
}
public static float Dist(Vector3 value1, Vector3 value2)
{
return value1.Dist(value2);
}
public static float Dot(Vector3 value1, Vector3 value2)
{
return value1.Dot(value2);
}
public static float Length(Vector3 value)
{
return value.Length();
}
public static Vector3 Lerp(Vector3 from, Vector3 to, float amount)
{
return from.Lerp(to, amount);
}
public static Vector3 Normalize(Vector3 value)
{
return value.Normalize();
}
public static Vector3 Zero { get { return new Vector3(0); } }
public static Vector3 Unit { get { return new Vector3(1); } }
public static Vector3 UnitX { get { return new Vector3(1, 0, 0); } }
public static Vector3 UnitY { get { return new Vector3(0, 1, 0); } }
public static Vector3 UnitZ { get { return new Vector3(0, 0, 1); } }
public static Vector3 operator +(Vector3 left, float value)
{
left.X += value;
left.Y += value;
left.Z += value;
return left;
}
public static Vector3 operator +(Vector3 left, Vector3 right)
{
left.X += right.X;
left.Y += right.Y;
left.Z += right.Z;
return left;
}
public static Vector3 operator -(Vector3 left)
{
left.X = (-left.X);
left.Y = (-left.Y);
left.Z = (-left.Z);
return left;
}
public static Vector3 operator -(Vector3 left, float value)
{
left.X -= value;
left.Y -= value;
left.Z -= value;
return left;
}
public static Vector3 operator -(Vector3 left, Vector3 right)
{
left.X -= right.X;
left.Y -= right.Y;
left.Z -= right.Z;
return left;
}
public static Vector3 operator /(Vector3 left, float value)
{
left.X /= value;
left.Y /= value;
left.Z /= value;
return left;
}
public static Vector3 operator /(Vector3 left, Vector3 right)
{
left.X /= right.X;
left.Y /= right.Y;
left.Z /= right.Z;
return left;
}
public static Vector3 operator *(Vector3 left, float value)
{
left.X *= value;
left.Y *= value;
left.Z *= value;
return left;
}
public static Vector3 operator *(Vector3 left, Vector3 right)
{
left.X *= right.X;
left.Y *= right.Y;
left.Z *= right.Z;
return left;
}
// do these size comparisions make sense?
public static bool operator <(Vector3 left, Vector3 right)
{
return (left.Length() < right.Length()) ? true : false;
}
public static bool operator >(Vector3 left, Vector3 right)
{
return (left.Length() > right.Length()) ? true : false;
}
public static bool operator >=(Vector3 left, Vector3 right)
{
return (left.Length() >= right.Length()) ? true : false;
}
public static bool operator <=(Vector3 left, Vector3 right)
{
return (left.Length() <= right.Length()) ? true : false;
}
// end question
public static bool operator ==(Vector3 left, Vector3 right)
{
return (left.X == right.X && left.Y == right.Y && left.Z == right.Z) ? true : false;
}
public static bool operator !=(Vector3 left, Vector3 right)
{
return (left.X != right.X || left.Y != right.Y || left.Z != right.Z) ? true : false;
}
}
}
</code></pre>
<p>VectorX: </p>
<pre><code>using System;
namespace Development
{
public struct VectorX : IEquatable<VectorX>
{
// private float[] VectorValues;
public float[] VectorValues { get; set; }
public int VectorCount { get; private set; }
public VectorX(int vectorCount)
{
VectorValues = new float[vectorCount];
VectorCount = vectorCount;
}
public VectorX(int vectorCount, float defaultValue)
{
VectorCount = vectorCount;
VectorValues = new float[vectorCount];
for (int i = 0; i < vectorCount; i++)
{
VectorValues[i] = defaultValue;
}
}
public VectorX(params float[] values)
{
VectorValues = values;
VectorCount = values.Length;
}
public VectorX(float[] arr, int startIndex)
{
VectorCount = arr.Length - 1 - startIndex;
VectorValues = new float[VectorCount];
for (int i = startIndex; i < arr.Length; i++)
{
VectorValues[i - startIndex] = arr[i];
}
}
public VectorX(float[] arr, int startIndex, int endIndex)
{
VectorCount = endIndex - startIndex;
VectorValues = new float[VectorCount];
for (int i = startIndex; i < endIndex; i++)
{
VectorValues[i - startIndex] = arr[i];
}
}
public VectorX(VectorX vector)
{
VectorCount = vector.VectorCount;
VectorValues = vector.VectorValues;
}
public override string ToString()
{
string ret = "<";
for (int i = 0; i < VectorCount; i++)
{
if (i == VectorCount - 1) ret += VectorValues[i];
else ret += VectorValues[i] + ", ";
}
return ret += ">";
}
public float[] ToArray()
{
return VectorValues;
}
public VectorX UpdateFromArray(float[] arr)
{
if (arr.Length < VectorCount) throw new Exception("Array is too small to convert to vector");
else
{
for (int i = 0; i < VectorCount; i++)
{
VectorValues[i] = arr[i];
}
}
return this;
}
public VectorX UpdateFromArray(float[] arr, int startIndex)
{
if (startIndex + VectorCount > arr.Length - 1) throw new Exception("startindex is too high to fill vector");
else
{
for (int i = 0; i < VectorCount; i++)
{
VectorValues[i] = arr[startIndex + i];
}
}
return this;
}
public float GetAt(int pos)
{
if (pos >= VectorCount || pos < 0) throw new Exception("Supplied position is too large or less then 0");
else return VectorValues[pos - 1];
}
public VectorX SetAt(int pos, float value)
{
if (pos >= VectorCount || pos < 0) throw new Exception("Supplied position is too large or less then 0");
else
{
VectorValues[pos - 1] = value;
return this;
}
}
public bool Equals(VectorX other) // not implemented
{
throw new NotImplementedException();
}
public float Length()
{
float total = 0;
for (int i = 0; i < VectorCount; i++)
{
total += MathF.Pow(VectorValues[i], 2);
}
return MathF.Sqrt(total);
}
public VectorX Normalize()
{
float scalar = 1 / this.Length();
for (int i = 0; i < VectorCount; i++)
{
VectorValues[i] *= scalar;
}
return this;
}
public VectorX Abs()
{
for (int i = 0; i < VectorCount; i++)
{
VectorValues[i] = (VectorValues[i] < 0) ? VectorValues[i] *= -1 : VectorValues[i];
}
return this;
}
public float Dist(VectorX other)
{
if (other.VectorCount != this.VectorCount) throw new Exception("Vectors are not of same length");
else
{
float sqrtValue = 0;
for (int i = 0; i < this.VectorCount; i++)
{
sqrtValue += MathF.Pow((this.VectorValues[i] - other.GetAt(i)), 2);
}
return MathF.Sqrt(sqrtValue);
}
}
public VectorX Min(VectorX min)
{
if (min.VectorCount != this.VectorCount) throw new Exception("Vectors are not of same length");
else
{
for (int i = 0; i < this.VectorCount; i++)
{
this.VectorValues[i] = (this.VectorValues[i] > min.GetAt(i)) ? this.VectorValues[i] : min.GetAt(i);
}
}
return this;
}
public VectorX Max(VectorX max)
{
if (max.VectorCount != this.VectorCount) throw new Exception("Vectors are not of same length");
else
{
for (int i = 0; i < VectorCount; i++)
{
VectorValues[i] = (VectorValues[i] < max.GetAt(i)) ? VectorValues[i] : max.GetAt(i);
}
}
return this;
}
public VectorX Clamp(VectorX min, VectorX max)
{
if (max.VectorCount != VectorCount || min.VectorCount != VectorCount) throw new Exception("Vectors are not of same length");
else
{
for (int i = 0; i < VectorCount; i++)
{
VectorValues[i] = (VectorValues[i] < min.GetAt(i)) ? min.GetAt(i) : VectorValues[i] = (VectorValues[i] > max.GetAt(i)) ? max.GetAt(i) : VectorValues[i];
}
return this;
}
}
public VectorX Lerp(VectorX to, float amount)
{
if (to.VectorCount != VectorCount) throw new Exception("Vectors have different length");
else
{
amount = Math.Clamp(amount, 0, 1);
for (int i = 0; i < VectorCount; i++)
{
VectorValues[i] = (VectorValues[i] - to.GetAt(i)) * amount + to.GetAt(i);
}
return this;
}
}
public float Dot(VectorX other)
{
if(other.VectorCount != VectorCount) throw new Exception("Vectors are not the same length");
else{
float d = 0;
for (int i = 0; i < VectorCount; i++)
{
d += VectorValues[i] * other.GetAt(i);
}
return d;
}
}
public static VectorX NewUnit(int size)
{
return new VectorX(size, 1);
}
public static VectorX NewUnitIndex(int size, int index)
{
VectorX vec = new VectorX(size);
vec.SetAt(index, 1);
return vec;
}
public static float Length(VectorX vector)
{
return vector.Length();
}
public static VectorX Normalize(VectorX vector)
{
return vector.Normalize();
}
public static VectorX Abs(VectorX vector)
{
return vector.Abs();
}
public static float Dist(VectorX vector1, VectorX vector2)
{
return vector1.Dist(vector2);
}
public static VectorX Min(VectorX vector, VectorX min)
{
return vector.Min(min);
}
public static VectorX Max(VectorX vector, VectorX min)
{
return vector.Max(min);
}
public static VectorX Clamp(VectorX vector, VectorX min, VectorX max)
{
return vector.Clamp(min, max);
}
public static VectorX Lerp(VectorX vector, VectorX to, float amount)
{
return vector.Lerp(to, amount);
}
public static float Dot(VectorX vector1, VectorX vector2)
{
return vector1.Dot(vector2);
}
public static VectorX operator +(VectorX left, float value)
{
for (int i = 0; i < left.VectorCount; i++)
{
left.SetAt(i, left.GetAt(i) + value);
}
return left;
}
public static VectorX operator +(VectorX left, VectorX right)
{
if(left.VectorCount != right.VectorCount) throw new Exception("Vectors not same length");
else{
for (int i = 0; i < left.VectorCount; i++)
{
left.SetAt(i, left.GetAt(i) + right.GetAt(i));
}
return left;
}
}
public static VectorX operator -(VectorX left)
{
for (int i = 0; i < left.VectorCount; i++)
{
left.SetAt(i, left.GetAt(i) * -1);
}
return left;
}
public static VectorX operator -(VectorX left, float value)
{
for (int i = 0; i < left.VectorCount; i++)
{
left.SetAt(i, left.GetAt(i) - value);
}
return left;
}
public static VectorX operator -(VectorX left, VectorX right)
{
if(left.VectorCount != right.VectorCount) throw new Exception("Vectors not same length");
else{
for (int i = 0; i < left.VectorCount; i++)
{
left.SetAt(i, left.GetAt(i) - right.GetAt(i));
}
return left;
}
}
public static VectorX operator /(VectorX left, float value)
{
for (int i = 0; i < left.VectorCount; i++)
{
left.SetAt(i, left.GetAt(i) / value);
}
return left;
}
public static VectorX operator /(VectorX left, VectorX right)
{
if(left.VectorCount != right.VectorCount) throw new Exception("Vectors not same length");
else{
for (int i = 0; i < left.VectorCount; i++)
{
left.SetAt(i, left.GetAt(i) / right.GetAt(i));
}
return left;
}
}
public static VectorX operator *(VectorX left, float value)
{
for (int i = 0; i < left.VectorCount; i++)
{
left.SetAt(i, left.GetAt(i) * value);
}
return left;
}
public static VectorX operator *(VectorX left, VectorX right)
{
if(left.VectorCount != right.VectorCount) throw new Exception("Vectors not same length");
else{
for (int i = 0; i < left.VectorCount; i++)
{
left.SetAt(i, left.GetAt(i) * right.GetAt(i));
}
return left;
}
}
// do these size comparisions make sense?
public static bool operator <(VectorX left, VectorX right)
{
if(left.VectorCount != right.VectorCount) throw new Exception("Vectors not same length");
else return (left.Length() < right.Length()) ? true : false;
}
public static bool operator >(VectorX left, VectorX right)
{
if(left.VectorCount != right.VectorCount) throw new Exception("Vectors not same length");
else return (left.Length() > right.Length()) ? true : false;
}
public static bool operator >=(VectorX left, VectorX right)
{
if(left.VectorCount != right.VectorCount) throw new Exception("Vectors not same length");
else return (left.Length() >= right.Length()) ? true : false;
}
public static bool operator <=(VectorX left, VectorX right)
{
if(left.VectorCount != right.VectorCount) throw new Exception("Vectors not same length");
else return (left.Length() <= right.Length()) ? true : false;
}
// end question
public static bool operator ==(VectorX left, VectorX right)
{
if(left.VectorCount != right.VectorCount) throw new Exception("Vectors not same length");
else
{
for (int i = 0; i < left.VectorCount; i++)
{
if(left.GetAt(i) != right.GetAt(i)) return false;
}
return true;
}
}
public static bool operator !=(VectorX left, VectorX right)
{
if(left.VectorCount != right.VectorCount) throw new Exception("Vectors not same length");
else
{
for (int i = 0; i < left.VectorCount; i++)
{
if(left.GetAt(i) != right.GetAt(i)) return true;
}
return false;
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T18:03:53.377",
"Id": "445831",
"Score": "1",
"body": "This seems alot like a javascript library (three.js) ported to C#."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T18:09:54.900",
"Id": "445832",
"Score": "1",
"body": "Have you considered using Vector class from System.Numerics?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T18:33:06.597",
"Id": "445835",
"Score": "0",
"body": "@RickDavin yes i started out with `System.Numerics` but ran into some limitations, so now i am building my own to circumvent those. But for what i have atm it looks similar to `System.Numerics`, but i hope to change that soon :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T10:34:36.610",
"Id": "445916",
"Score": "3",
"body": "Could you name the limitations?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T21:30:57.610",
"Id": "446031",
"Score": "2",
"body": "Welcome to Code Review! Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 6 → 3"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T13:48:53.280",
"Id": "446116",
"Score": "0",
"body": "@FutureCake could you tell the limitations you encountered with the `System.Numerics.Vector<>` class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T21:17:42.127",
"Id": "446210",
"Score": "1",
"body": "@t3chb0t I will try to explain what i was missing in the `System.numerics` namespace. First of all i wanted to be able to implicitly convert vectors between types to go from `Vector3` to `Vector2`, I wanted some extra constructors, A bunch of methods that don't exist in the `Numerics` vector. And A vector of user defined length, Generics that i still have to make :) And probably some other stuff i cant think of right now... And most of all it is a great learning exercise :)"
}
] |
[
{
"body": "<p>You are inconsistent with your use of the <code>this.</code> 'suffix'. Nobody can agree on this, but you should try to be consistent without projects.</p>\n\n<hr />\n\n<p>I would remove the return values from every method which modifies <code>Vector3</code>: you have 2 copies of <code>Min</code>, and one is very confusing. All of the methods which happen to produce a vector (e.g. <code>Abs</code>, <code>Min</code>, Max<code>) happen to modify</code>this<code>and then return</code>this<code>. This is, in my opinion, a terrible API, and inconsistent with operations (like</code>Length<code>) which just happen to _not_ produce a vector. Anyone looking at the signature will assume it does not modify the vector, and you just open yourself to all the nightmares associated with mutable</code>struct`s. Do not mix an immutable/mutable API like you are now, because it will only infuriate your consumers.</p>\n\n<p>Methods like <code>UpdateFromArray</code> are for some reason returning <code>this</code> as well.</p>\n\n<hr />\n\n<p>You seem to be trying to provide a consistent API between <code>VectorX</code> (which I would just call <code>Vector</code>) and <code>Vector3</code>, so you might consider an <code>IVector</code> interface.</p>\n\n<p><code>VectorCount</code> is a mildly confusing name. It's the element count, or the length of the vector.</p>\n\n<hr />\n\n<p>I would suggest not using <code>Math.Pow(, 2)</code> just to square something: even if it is optimised to detect this exact case (I don't know), it is just harder to read than <code>X * X</code>. I would rewrite <code>Dist</code> as <code>(this - other).length</code> for the sake of simplicity.</p>\n\n<p>It's also common to provide a <code>LengthSquared</code> member which returns the sum before the squareroot, since often this is all that is needed and saves an expensive operation.</p>\n\n<hr />\n\n<p>The parameter names for <code>Min</code> and <code>Max</code> are odd: <code>other</code> would be fine, but again I don't like the API.</p>\n\n<hr />\n\n<p>I would expect <code>public Vector3(float[] arr)</code> to throw a nice exception if <code>arr</code> is null, or had a length other than 3.</p>\n\n<p>It's good that most of your methods in <code>VectorX</code> are performing range checks (I didn't notice any that didn't). You don't need to put the 'non-exceptional' code in an else for these.</p>\n\n<hr />\n\n<p><code>VectorX</code> has many constructors which just provide 'defaults' for others. I would make these call directly the more general versions. E.g.</p>\n\n<pre><code>public VectorX(int vectorCount) : this(vectorCount, default(float))\n{ }\n\npublic VectorX(params float[] values) : this(values, 0, values.Length)\n{ }\n</code></pre>\n\n<p>This will significantly reduce redundancy and so improve maintainability.</p>\n\n<hr />\n\n<p>Your <code>ToString</code> methods could be nicer: I would use string interpolation for <code>Vector3</code> (i.e. <code>$\"<{X}, {Y}, {Z}>\"</code>) and you should use a <code>StringBuilder</code> for <code>VectorX</code> (currently <code>VectorX.ToString()</code> is a quadratic memory operation when it should be linear).</p>\n\n<hr />\n\n<blockquote>\n <p>// do these size comparisions make sense?</p>\n</blockquote>\n\n<p>No, I would say no; though, it does atleast provide an ordering, so it could be much worse.</p>\n\n<p>The comparisons are also performing 2 unnecessary square-roots (you could compare the <code>LengthSquared</code>).</p>\n\n<p>All your <code>Vector3</code> comparisions also include a completely redundant ternay clause, which will just get in the way of maintaince efforts and provide a greater surface overwhich bugs can will appear.</p>\n\n<p>I would consider describing negatives in terms of the positives, e.g.</p>\n\n<pre><code>public static bool operator !=(Vector3 left, Vector3 right)\n{\n return !(left == right);\n}\n</code></pre>\n\n<hr >\n\n<p>Why isn't <code>VectorX.Equals(VectorX other)</code> implemented? What is the point of declaring you implement <code>IEquatable<VectorX></code> if you do not?</p>\n\n<hr />\n\n<p>I don't like all your single-line <code>if</code>s and <code>else</code>s. Even if you don't want to add braces, a line at the end of the condition or <code>else</code> helps significantly with readbility, and reduces the amount of code which is 'off side'.</p>\n\n<hr />\n\n<p>All of your types and methods would benefit from inline documention (<code>///</code>). This would help to explain the confusing bits of the API, and clarify what methods like <code>Length</code> and <code>Normalise</code> mean.</p>\n\n<hr />\n\n<blockquote>\n<pre><code>VectorValues[i] = (VectorValues[i] < 0) ? VectorValues[i] *= -1 :\nVectorValues[i];\n</code></pre>\n</blockquote>\n\n<p>What is wrong with <code>Math.Abs(VectorValues[i])</code>.</p>\n\n<hr />\n\n<blockquote>\n <p><code>public int VectorCount { get { return 3; } }</code></p>\n</blockquote>\n\n<p>This can be made a little more concise:</p>\n\n<pre><code>public int VectorCount => 3;\n</code></pre>\n\n<p>You could do the same with the <code>static</code> <code>Unit</code> and <code>Zero</code> members.</p>\n\n<hr />\n\n<p>You have some odd line-spacing in places (e.g. around <code>VectorX.NewUnit</code>). I can see no reason for this, so it just looks untidy and makes the code harder to scan.</p>\n\n<hr />\n\n<p>Consider using an indexer instead of the <code>SetAt</code> and <code>GetAt</code> methods. These could be part of the <code>IVector</code> interface also.</p>\n\n<hr />\n\n<p><code>VectorX.VectorValues</code> should not be mutable, and probably shouldn't be public. At the moment it is possible for someone to change <code>VectorValues</code> such that <code>VectorCount</code> will be wrong, or even to change it <code>null</code> and wreck everything. Hide it away so that people can't shoot themselves in the foot with your API.</p>\n\n<p>You could re-write <code>VectorX.VectorCount</code> in terms of <code>VectorValues</code> to reduce redunancy and simplify the constructors.</p>\n\n<pre><code>public int VectorCount => VectorValues.Length;\n</code></pre>\n\n<p>Less redundancy again means there is less to go wrong, which makes the code easier to maintain.</p>\n\n<hr />\n\n<p>The <code>VectorX(VectorX)</code> constructor is not good: all the other constructors duplicate the array they are given, but this just copies the reference. There is no point in this constructor (it's the same as a value-copy) and it will only create confusion. If instead it copied the array, then it would be fine.</p>\n\n<pre><code>public VectorX(VectorX vector) : this(vector.VectorValues)\n{ }\n</code></pre>\n\n<p><code>ToArray</code> would also imply a copy, and with <code>VectorValues</code> public does nothing useful. It should take a copy. This is as easy as <code>VectorValues.ToArray()</code> if you have <code>using System.Linq</code> at the top of your file. The fact that it does/doesn't copy should be in the documention.</p>\n\n<hr />\n\n<p>I'm going to stop for now, but I may add to this answer when I have time, though I'm sure someone else will take up the slack long before then if there is more to be said.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T17:55:14.070",
"Id": "445830",
"Score": "1",
"body": "It will be hard writing a _complement_ answer without having some kind of _intersection_ with this answer :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T18:31:31.100",
"Id": "445833",
"Score": "1",
"body": "About the status of `Pow(x, 2)`, it is not (yet) optimized by the main implementations, there is an [open issue for coreclr](https://github.com/dotnet/coreclr/issues/26434), so maybe someday"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T18:44:31.547",
"Id": "445838",
"Score": "0",
"body": "VisualMelon, Thank you so much for the extensive list of improvements!!! As you may have seen from my code i am no pro ;) But this sure as hell will help with my improvement of skills :) I will be working on this list in the next few days probably :) Please keep adding indeed if you feel like it :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T18:48:58.760",
"Id": "445839",
"Score": "0",
"body": "@FutureCake you're welcome. It's customary to hold off before marking any answer as 'the' answer for at least a day or two, so as not to discourage more answers. I didn't add it to my answer, because it's not something I have much experience with, but you may want to look into the [SIMD](https://devblogs.microsoft.com/dotnet/the-jit-finally-proposed-jit-and-simd-are-getting-married/) support in .NET if you really want serious performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T18:51:08.483",
"Id": "445840",
"Score": "0",
"body": "@VisualMelon I unchecked the answer, i will get back to it in a few days then :) And i will go and check out what SIMD is! Thanks again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T10:36:59.670",
"Id": "445917",
"Score": "1",
"body": "You didn't mention the _new_ `readonly struct`, or I missed it. This would cure all of the mutability issues already on the compile level."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T10:44:01.693",
"Id": "445919",
"Score": "1",
"body": "@t3chb0t I had a section about mutability, but frankly that would remove most of the API (so I removed it). Please do write your own answer about that (if you want), because I won't be adding it."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T17:36:38.357",
"Id": "229261",
"ParentId": "229256",
"Score": "13"
}
},
{
"body": "<p>Ok, I think I found something noteworthy not yet mentioned by VisualMelon.</p>\n\n<p>You are already using <code>MathF</code> to perform some operations for you, why not redirect some others to <code>Math</code>?</p>\n\n<blockquote>\n<pre><code>public Vector3 Min(Vector3 min)\n{\n this.X = (this.X < min.X) ? this.X : min.X;\n this.Y = (this.Y < min.Y) ? this.Y : min.Y;\n this.Z = (this.Z < min.Z) ? this.Z : min.Z;\n return this;\n}\n</code></pre>\n</blockquote>\n\n<p>could be written as:</p>\n\n<pre><code>public Vector3 Min(Vector3 min)\n{\n this.X = Math.Min(this.X, min.X);\n this.Y = Math.Min(this.Y, min.Y);\n this.Z = Math.Min(this.Z, min.Z);\n return this;\n}\n</code></pre>\n\n<p>You could do the equivalent for method <code>Max</code>.</p>\n\n<p>Note an inconsistency or at least a very confusing meaning of the variables <code>min</code> and <code>max</code>. In methods <code>Min</code> and <code>Max</code> you take the min, respectively max of the current value with the provided value. While in <code>Clamp</code> you turn the meaning of min and max around.</p>\n\n<p>I would refactor <code>Min</code> and <code>Max</code> to use the same definition for min and max as <code>Clamp</code>. This way, the provided variable is a boundary, just as in <code>Clamp</code>.</p>\n\n<pre><code>public Vector3 Min(Vector3 max)\n{\n this.X = Math.Min(this.X, max.X);\n this.Y = Math.Min(this.Y, max.Y);\n this.Z = Math.Min(this.Z, max.Z);\n return this;\n}\n\npublic Vector3 Max(Vector3 min)\n{\n this.X = Math.Max(this.X, min.X);\n this.Y = Math.Max(this.Y, min.Y);\n this.Z = Math.Max(this.Z, min.Z);\n return this;\n}\n</code></pre>\n\n<p>Clamp could then be rewritten (you could also add some validation that max > min):</p>\n\n<pre><code>public Vector3 Clamp(Vector3 min, Vector3 max)\n{\n this.Max(min);\n this.Min(max);\n return this;\n}\n</code></pre>\n\n<p>One other thing about the original <code>Clamp</code> code:</p>\n\n<blockquote>\n<pre><code>public Vector3 Clamp(Vector3 min, Vector3 max)\n{\n this.X = (this.X < min.X) ? min.X : this.X = (this.X > max.X) ? max.X : this.X;\n this.Y = (this.Y < min.Y) ? min.Y : this.Y = (this.Y > max.Y) ? max.Y : this.Y;\n this.Z = (this.Z < min.Z) ? min.Z : this.Z = (this.Z > max.Z) ? max.Z : this.Z;\n return this;\n}\n</code></pre>\n</blockquote>\n\n<p>You don't have to assign this.* to itself in the ternary operations. You could simplify to:</p>\n\n<pre><code>public Vector3 Clamp(Vector3 min, Vector3 max)\n{\n this.X = (this.X < min.X) ? min.X : (this.X > max.X) ? max.X : this.X;\n this.Y = (this.Y < min.Y) ? min.Y : (this.Y > max.Y) ? max.Y : this.Y;\n this.Z = (this.Z < min.Z) ? min.Z : (this.Z > max.Z) ? max.Z : this.Z;\n return this;\n}\n</code></pre>\n\n<p>Or a bit more compact using <code>Math</code>:</p>\n\n<pre><code>public Vector3 Clamp(Vector3 min, Vector3 max)\n{\n this.X = Math.Min(Math.Max(this.X, min.X), max.X);\n this.Y = Math.Min(Math.Max(this.Y, min.Y), max.Y);\n this.Z = Math.Min(Math.Max(this.Z, min.Z), max.Z);\n return this;\n}\n</code></pre>\n\n<p>Beyond this, I would also favor to use immutable classes. So instead of changing the instance coordinates, I would create a new instance of a <code>Vector3</code> instead. If the entire API is written this way, your fluent methods make sense and would consistently return new instances on chaining.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T10:42:11.653",
"Id": "446089",
"Score": "0",
"body": "+1 Thanks for the advice! Just one question about the using of `Math.Min, Math.Max` etc. Isn't this less efficient because then i am first calling an other class which calls a method and then returns the result? Instead of just doing it with statements? Or is the difference negligible?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T11:09:14.403",
"Id": "446090",
"Score": "2",
"body": "The performance penalty of calling another method is negligible, as you say :) usability and reusability should definately be favored here"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T05:05:23.367",
"Id": "229355",
"ParentId": "229256",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "229261",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T16:27:09.687",
"Id": "229256",
"Score": "9",
"Tags": [
"c#",
"performance",
"coordinate-system"
],
"Title": "C# vector library"
}
|
229256
|
<p>Let's suppose I have two lists:</p>
<pre><code>list_b = ['cat.2','dog.6','bear.10','zebra.13']
list_a = ['cat','dog','bear','zebra']
</code></pre>
<p>I would like to create a dictionary with the desired output:</p>
<pre><code>dict_ = {'cat.2':'cat','dog.6':'dog','bear':'bear.10','zebra.13':'zebra'}
</code></pre>
<p>I have two possible solutions. I am assuming the lists are not ordered so I cannot simply do a <code>dict(zip(list_a,list_b))</code> or something along those lines.</p>
<p>Solution 1:</p>
<pre><code>dict_ = {}
for i in list_a:
for j in list_b:
if i.startswith(j):
dict_[i] = j
</code></pre>
<p>Solution 2:</p>
<pre><code>dict_ = {key:value for key in list_a for value in list_b if key.startswith(value)}
</code></pre>
<p>I prefer solution two because, if I recall correctly, comprehensions should be much faster, but I do not know if there is a more efficient way of doing this.</p>
<p>Thanks in advance!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T17:30:53.783",
"Id": "445826",
"Score": "2",
"body": "Hey, welcome to Code Review! Here we take a look at complete and working code and try to make it better. For this it is paramount to see the code in its actual environment. The more code you can show, the better. Hypothetical code, code stubs without context or general best practice questions are off-topic here. Have a look at our [help/dont-ask] for more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T22:52:31.030",
"Id": "445869",
"Score": "0",
"body": "I think the context is clear, even if implicit: \"for each key in `list_b`, split on '.' and find the corresponding partial-match from `list_a` and use it as the value\". Don't even need regex. Now if you mean the question is toy, that's different..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T22:54:10.290",
"Id": "445870",
"Score": "0",
"body": "As @Reinderien showed, can we totally ignore `list_a` and just assume each key in `list_b` has a match in `list_a` when we split on '.'? What should we do if key has no matches? multiple matches?"
}
] |
[
{
"body": "<p>You don't even need to use the second list. You can do a dict comprehension:</p>\n\n<pre><code>{k: k.split('.', 1)[0] for k in list_b}\n</code></pre>\n\n<p>This assumes that the data are all structured as you've shown, with a prefix, a dot and a number.</p>\n\n<p>p.s. don't call your variable <code>dict_</code>. Name it according to its application function - <code>animals</code>, or whatever.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T17:33:19.920",
"Id": "445828",
"Score": "0",
"body": "The data is indeed structured as shown. This is much more readable!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T17:30:18.443",
"Id": "229260",
"ParentId": "229257",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229260",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T17:07:14.953",
"Id": "229257",
"Score": "-1",
"Tags": [
"python",
"hash-map"
],
"Title": "Dictionary comprehension with nested for loop and conditional if"
}
|
229257
|
<p>I'm currently halfway through a Python project, but would like a review before I spend too much more time on this to avoid going too far down a rabbit hole.</p>
<p>I had previously wanted to use HTML, CSS, and JavaScript, but I swapped to Python so I can get the current Window's user while opening my app.</p>
<p>At my work, we have labels that look like this:</p>
<p><a href="https://i.stack.imgur.com/0LvSb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0LvSb.jpg" alt="demo paper label"></a></p>
<p>We print out this paper and put a label on the left-hand side, and then get written sign-off on it from various stakeholders. The labels are for products such as seeds, nuts, beans, etc. The specific design and layout of the label will vary based on our customer.</p>
<p>Current, paper workflow:</p>
<ol>
<li>The originator creates the form and hands it to the managers who need to sign off</li>
<li>The managers initial (the two rightmost columns) to show that they have signed off. Sometimes only person needs to sign off, sometimes two.</li>
<li>Once everything is done, someone will sign and date the label to verify that the label is good to go.</li>
</ol>
<p>With the new Python application, I would like to be able to accomplish the same workflow without ever needing the physical piece of paper being passed around. </p>
<p>Here is my current (but incomplete) code:</p>
<pre><code>from tkinter import *
import glob
import os
from PIL import Image, ImageTk, ImageGrab
import tkinter as tk
import datetime
#date & time
now = datetime.datetime.now()
root = tk.Tk()
root.title("SIGN OFF")
root.minsize(840, 800)
# Add a grid
mainframe = tk.Frame(root)
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
mainframe.pack(pady=100, padx=100)
# Create a Tkinter variable
tkvar = tk.StringVar(root)
# Directory
directory = "C:/Users/eduards/Desktop/work/data/to-do"
choices = glob.glob(os.path.join(directory, "*.jpg"))
tkvar.set('...To Sign Off...') # set the default option
# Dropdown menu
popupMenu = tk.OptionMenu(mainframe, tkvar, *choices)
tk.Label(mainframe, text="Choose your sign off here:").grid(row=1, column=1)
popupMenu.grid(row=2, column=1)
label2 = tk.Label(mainframe, image=None)
label2.grid(row = 4, column = 1, rowspan = 10)
# On change dropdown callback.
def change_dropdown(*args):
""" Updates label2 image. """
imgpath = tkvar.get()
img = Image.open(imgpath)
img = img.resize((240,250))
photo = ImageTk.PhotoImage(img)
label2.image = photo
label2.configure(image=photo)
tk.Button(mainframe, text="Open", command=change_dropdown).grid(row=3, column=1)
def var_states():
text_file = open("logfile.txt", "a")
text_file.write("TIME: %s, USER: %s, One %d, Two %d\n" % (now,os.getlogin(), var1.get(), var2.get()))
text_file.close()
print("One %d, Two %d" % (var1.get(), var2.get()))
var1 = IntVar()
Checkbutton(mainframe, text="Ingredients present in full (any allergens in bold with allergen warning if necessary)", variable=var1).grid(column = 2, row=1, sticky=W)
var2 = IntVar()
Checkbutton(mainframe, text="May Contain Statement.", variable=var2).grid(column = 2, row=2, sticky=W)
var3 = IntVar()
Checkbutton(mainframe, text="Cocoa Content (%).", variable=var3).grid(column = 2, row=3, sticky=W)
var4 = IntVar()
Checkbutton(mainframe, text="Vegetable fat in addition to Cocoa butter", variable=var4).grid(column = 2, row=4, sticky=W)
var5 = IntVar()
Checkbutton(mainframe, text="Instructions for Use.", variable=var5).grid(column = 2, row=5, sticky=W)
var6 = IntVar()
Checkbutton(mainframe, text="Additional warning statements (pitt/stone, hyperactivity etc)", variable=var6).grid(column = 2, row=6, sticky=W)
var7 = IntVar()
Checkbutton(mainframe, text="Nutritional Information Visible", variable=var7).grid(column = 2, row=7, sticky=W)
var8 = IntVar()
Checkbutton(mainframe, text="Storage Conditions", variable=var8).grid(column = 2, row=8, sticky=W)
var9 = IntVar()
Checkbutton(mainframe, text="Best Before & Batch Information", variable=var9).grid(column = 2, row=9, sticky=W)
var10 = IntVar()
Checkbutton(mainframe, text="Net Weight & Correct Font Size.", variable=var10).grid(column = 2, row=10, sticky=W)
var11 = IntVar()
Checkbutton(mainframe, text="Barcode - Inner", variable=var11).grid(column = 2, row=11, sticky=W)
var12 = IntVar()
Checkbutton(mainframe, text="Address & contact details correct", variable=var12).grid(column = 2, row=12, sticky=W)
def user():
user_input = os.getlogin()
tk.Label(mainframe, text = user_input, font='Helvetica 18 bold').grid(row = 0, column = 1)
user()
def save():
# pyautogui.press('alt')
# pyautogui.press('printscreen')
# img = ImageGrab.grabclipboard()
# img.save('paste.jpg', 'JPEG')
var_states()
tk.Button(mainframe, text = "Save", command = save).grid(row = 20, column = 1)
root.mainloop()
</code></pre>
<p>Here is the output:</p>
<p><a href="https://i.stack.imgur.com/0STgj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0STgj.jpg" alt="digitized label"></a></p>
<p>The top part in bold (<code>Label</code> in the sample image) is the current Windows user's username. The dropdown menu below that is the list of JPG files that need signing (TODO: structure the files to only show specific file names that need signing).</p>
<p>When you click "Save", a log file will be generated that shows your timestamped choices (TODO: add code to return which image was touched).</p>
<p>I've also realized that this currently only supports a single person signing, but I will need to restructure to support allowing multiple (currently up to 2) people to sign it.</p>
<p>Below is the file system for labels in JPG. Customer account number which is unique, as an example SFDG001 is one customer and ALPI001 is another. 2nd is the product code, each customer takes different product codes and never will have the same product code. (I know the images look the same, but its for test purposes)</p>
<p><a href="https://i.stack.imgur.com/yFLv3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yFLv3.jpg" alt="sample JPGs that would need signing"></a></p>
<p><strong>UPDATE 26/09/2019 - NEW CODE</strong></p>
<p>here is my updated code:</p>
<pre><code>from tkinter import *
from tkinter import DISABLED
import tkinter.ttk as ttk
import os
import glob
from PIL import Image, ImageTk, ImageGrab
from pathlib import Path
# from openpyxl import load_workbook
class App():
def __init__(self,master):
notebook = ttk.Notebook(master)
notebook.pack(expand = 1, fill = "both")
#Frames
main = ttk.Frame(notebook)
manual = ttk.Frame(notebook)
notebook.add(main, text='Main-Screen')
notebook.add(manual, text='Manual')
#Check boxes
#Assigning Integers to variables
var1 = IntVar()
var1a = IntVar()
var2 = IntVar()
var2a = IntVar()
var3 = IntVar()
var3a = IntVar()
var4 = IntVar()
var4a = IntVar()
var5 = IntVar()
var5a = IntVar()
var6 = IntVar()
var6a = IntVar()
var7 = IntVar()
var7a = IntVar()
var8 = IntVar()
var8a = IntVar()
var9 = IntVar()
var9a = IntVar()
var10 = IntVar()
var10a = IntVar()
var11 = IntVar()
var11a = IntVar()
var12 = IntVar()
var12a = IntVar()
#Text boxes for initials
#Displaying checkboxes and assigning to variables
self.Checkbox1 = Checkbutton(main, text="Ingredients present in full (any allergens in bold with allergen warning if necessary)", variable=var1)
self.Checkbox1.grid(column = 2, row = 1, sticky = W)
self.Checkbox2 = Checkbutton(main, variable = var1a)
self.Checkbox2.grid(column = 1, row = 1, sticky = W)
self.Checkbox3 = Checkbutton(main, text="May Contain Statement.", variable=var2)
self.Checkbox3.grid(column = 2, row = 2, sticky = W)
self.Checkbox4 = Checkbutton(main, variable = var2a)
self.Checkbox4.grid(column = 1, row = 2, sticky = W)
self.Checkbox5 = Checkbutton(main, text="Cocoa Content (%).", variable=var3)
self.Checkbox5.grid(column = 2, row = 3, sticky = W)
self.Checkbox6 = Checkbutton(main, variable = var3a)
self.Checkbox6.grid(column = 1, row = 3, sticky = W)
self.Checkbox7 = Checkbutton(main, text="Vegetable fat in addition to Cocoa butter", variable=var4)
self.Checkbox7.grid(column = 2, row = 4, sticky = W)
self.Checkbox8 = Checkbutton(main, variable = var4a)
self.Checkbox8.grid(column = 1, row = 4, sticky = W)
self.Checkbox9 = Checkbutton(main, text="Instructions for Use.", variable=var5)
self.Checkbox9.grid(column = 2, row = 5, sticky = W)
self.Checkbox10 = Checkbutton(main, variable = var5a)
self.Checkbox10.grid(column = 1, row = 5, sticky = W)
self.Checkbox11 = Checkbutton(main, text="Additional warning statements (pitt/stone, hyperactivity etc)", variable=var6)
self.Checkbox11.grid(column = 2, row = 6, sticky = W)
self.Checkbox12 = Checkbutton(main, variable = var6a)
self.Checkbox12.grid(column = 1, row = 6, sticky = W)
self.Checkbox13 = Checkbutton(main, text="Nutritional Information Visible", variable=var7)
self.Checkbox13.grid(column = 2, row = 7, sticky = W)
self.Checkbox14 = Checkbutton(main, variable = var7a)
self.Checkbox14.grid(column = 1, row = 7, sticky = W)
self.Checkbox15 = Checkbutton(main, text="Storage Conditions", variable=var8)
self.Checkbox15.grid(column = 2, row = 8, sticky = W)
self.Checkbox16 = Checkbutton(main, variable = var8a)
self.Checkbox16.grid(column = 1, row = 8, sticky = W)
self.Checkbox17 = Checkbutton(main, text="Best Before & Batch Information", variable=var9)
self.Checkbox17.grid(column = 2, row = 9, sticky = W)
self.Checkbox18 = Checkbutton(main, variable = var9a)
self.Checkbox18.grid(column = 1, row = 9, sticky = W)
self.Checkbox19 = Checkbutton(main, text="Net Weight & Correct Font Size.", variable=var10)
self.Checkbox19.grid(column = 2, row = 10, sticky = W)
self.Checkbox20 = Checkbutton(main, variable = var10a)
self.Checkbox20.grid(column = 1, row = 10, sticky = W)
self.Checkbox21 = Checkbutton(main, text="Barcode - Inner", variable=var11)
self.Checkbox21.grid(column = 2, row = 11, sticky = W)
self.Checkbox22 = Checkbutton(main, variable = var11a)
self.Checkbox22.grid(column = 1, row = 11, sticky = W)
self.Checkbox23 = Checkbutton(main, text="Address & contact details correct", variable=var12)
self.Checkbox23.grid(column = 2, row = 12, sticky = W)
self.Checkbox24 = Checkbutton(main, variable = var12a)
self.Checkbox24.grid(column = 1, row = 12, sticky = W)
##DISABLE ON CLICK##
def showstate(*args):
if var1.get() or var2.get() or var3.get() or var4.get() or var5.get() or var6.get() or var7.get() or var8.get() or var9.get() or var10.get() or var11.get() or var12.get():
self.Checkbox2.config(state = DISABLED)
self.Checkbox4.config(state = DISABLED)
self.Checkbox6.config(state = DISABLED)
self.Checkbox8.config(state = DISABLED)
self.Checkbox10.config(state = DISABLED)
self.Checkbox12.config(state = DISABLED)
self.Checkbox14.config(state = DISABLED)
self.Checkbox16.config(state = DISABLED)
self.Checkbox18.config(state = DISABLED)
self.Checkbox20.config(state = DISABLED)
self.Checkbox22.config(state = DISABLED)
self.Checkbox24.config(state = DISABLED)
if var1a.get() or var2a.get() or var3a.get() or var4a.get() or var5a.get() or var6a.get() or var7a.get() or var8a.get() or var9a.get() or var10a.get() or var11a.get() or var12a.get():
self.Checkbox1.config(state = DISABLED)
self.Checkbox3.config(state = DISABLED)
self.Checkbox5.config(state = DISABLED)
self.Checkbox7.config(state = DISABLED)
self.Checkbox9.config(state = DISABLED)
self.Checkbox11.config(state = DISABLED)
self.Checkbox13.config(state = DISABLED)
self.Checkbox15.config(state = DISABLED)
self.Checkbox17.config(state = DISABLED)
self.Checkbox19.config(state = DISABLED)
self.Checkbox21.config(state = DISABLED)
self.Checkbox23.config(state = DISABLED)
var1.trace_variable("w", showstate)
var1a.trace_variable("w", showstate)
var2.trace_variable("w", showstate)
var2a.trace_variable("w", showstate)
var3.trace_variable("w", showstate)
var3a.trace_variable("w", showstate)
var4.trace_variable("w", showstate)
var4a.trace_variable("w", showstate)
var5.trace_variable("w", showstate)
var5a.trace_variable("w", showstate)
var6.trace_variable("w", showstate)
var6a.trace_variable("w", showstate)
var7.trace_variable("w", showstate)
var7a.trace_variable("w", showstate)
var8.trace_variable("w", showstate)
var8a.trace_variable("w", showstate)
var9.trace_variable("w", showstate)
var9a.trace_variable("w", showstate)
var10.trace_variable("w", showstate)
var10a.trace_variable("w", showstate)
var11.trace_variable("w", showstate)
var11a.trace_variable("w", showstate)
var12.trace_variable("w", showstate)
var12a.trace_variable("w", showstate)
##DISABLE ON CLICK##
#Send data
def var_states():
text_file = open("logfile.txt", "a")
text_file.write("USER: %s, One %d\n" % (os.getlogin(), var1.get()))
text_file.close()
self.dataSend = Button(main, text = "Send", command = var_states).grid(column = 1, row = 13, sticky = W)
###################################################################################################################################
##Load Image##
###################################################################################################################################
# Create a Tkinter variable
tkvar = StringVar(root)
# Directory
directory = "//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project"
choices = glob.glob(os.path.join(directory, "*- to sign.jpg"))
tkvar.set('...To Sign Off...') # set the default option
# Images
def change_dropdown():
imgpath = tkvar.get()
img = Image.open(imgpath)
img = img.resize((529,361))
photo = ImageTk.PhotoImage(img)
label2.image = photo
label2.configure(image=photo)
#return path value
p = None
def func(value):
global p
p = Path(value)
print('req:', p)
#widgets
self.msg1 = Label(main, text = "Choose here")
self.msg1.grid(column = 0, row = 0)
self.popupMenu = OptionMenu(main, tkvar, *choices)
self.popupMenu.grid(row=1, column=0)
self.display_label = label2 = Label(main, image=None)
self.display_label.grid(row=2, column=0, rowspan = 500)
self.open_button = Button(main, text="Open", command=change_dropdown)
self.open_button.grid(row=502, column=0)
###################################################################################################################################
##Tab 2 - Manual##
###################################################################################################################################
def open_doc():
os.system("start C:/Users/Eduards/Desktop/Portfolio")
self.Manual_Button = Button(manual, text = "Open Manual", command = open_doc)
self.Manual_Button.pack()
root = Tk()
root.minsize(950, 450)
root.title("SIGN OFF LABELS")
app = App(root)
root.mainloop()
</code></pre>
<p>Have added another checkboxes, if one side is clicked, the other side is disabled.</p>
<p>Added tabs, need to work on manual, to open a docx file.</p>
<p>Next, I will concentrate on adding a log in window for users to log in. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T20:08:34.813",
"Id": "445848",
"Score": "3",
"body": "Welcome to Code Review! I've edited your question to more accurately describe your topic, and clarify some of your points. That being said, as currently written your question is off-topic. We require code to be completely implemented before being submitted for review. Are you able to restructure your code/question to be complete as-is, instead of including the elements that aren't doing what you want?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T20:26:17.670",
"Id": "445852",
"Score": "0",
"body": "Hi Dannnno, I give you final code by the end of the week hopefully, or start of next week (Monday Uk time)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T20:27:35.057",
"Id": "445854",
"Score": "0",
"body": "Also, thanks for the edit! I will keep that structure in mind and use it in later cases!"
}
] |
[
{
"body": "<h2>Fix your imports of tkinter</h2>\n\n<p>You are importing tkinter twice, once with a wildcard and once \"as tk\". You should not be using the global import at all (see <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP9</a>). Stick with a single import:</p>\n\n<pre><code>import tkinter as tk\n</code></pre>\n\n<p>There will be places in your code that need to be modified to account for this. For example, change all instance of <code>Checkbutton</code> to <code>tk.Checkbutton</code>.</p>\n\n<h2>Separate widget creation from widget layout</h2>\n\n<p>Don't write code like <code>tk.Label(...).grid(...)</code>. Separate your widget creation from widget layout. It makes your code easier to read, and makes the layout easier to visualize. Plus, when you need to keep a reference to a widget, you won't trip over the common problem of having variables set to <code>None</code> because <code>.grid(...)</code> and <code>.pack(...)</code> return None.</p>\n\n<p>For example:</p>\n\n<pre><code>choose_label = tk.Label(mainframe, text=\"Choose your sign off here:\")\npopupMenu = tk.OptionMenu(mainframe, tkvar, *choices)\nother_label = tk.Label(mainframe, image=None)\nopen_button = tk.Button(mainframe, text=\"Open\", command=change_dropdown)\n\nchoose_label.grid(row=1, column=1)\npopupMenu.grid(row=2, column=1)\nopen_button.grid(row=3, column=1)\nother_label.grid(row=4, column=1)\n</code></pre>\n\n<p>This makes it much easier to see which widgets are grouped together and how they are arranged on screen. </p>\n\n<p>As a rule of thumb, I always create all widgets that share the same parent as a group, and then lay them out as a group. That way I don't have to hunt through all of the code trying to find widgets that are arranged together. </p>\n\n<h2>Organize your widgets</h2>\n\n<p>You've put everything in <code>mainframe</code>. However, looking at your UI design you clearly have different sections to the UI. Have your code reflect those different sections.</p>\n\n<p>For example, you seem to have a left half and a right half to the GUI, and their layout needs are somewhat different. On the right is just a list of checkbuttons that are all aligned to the left. On the left is a more complex layout with different widgets where everything is centered. Also, the items on the left take up less space than the items on the right.</p>\n\n<p>I recommend that you start the GUI by creating two frames, one for the left and one for the right. </p>\n\n<pre><code>left_frame = tk.Frame(...)\nright_frame = tk.Frame(...)\n</code></pre>\n\n<p>You can then use <code>pack</code> to lay them out side-by-side, or use a paned window, or use <code>grid</code>. In this specific case I would choose <code>pack</code> simply because you don't have to worry about row and column weights.</p>\n\n<p>For example, this causes each to be given half of the available free space in the window:</p>\n\n<pre><code>left_frame.pack(side=\"left\", fill=\"both\", expand=True)\nright_frame.pac(side=\"right\", fill=\"both\", expand=True)\n</code></pre>\n\n<p>Next, focus on just one side of the UI. For example, all of the widgets on the left would be a child of <code>left_frame</code>:</p>\n\n<pre><code>choose_label = tk.Label(left_frame, text=\"Choose your sign off here:\")\npopupMenu = tk.OptionMenu(left_frame, tkvar, *choices)\nother_label = tk.Label(left_frame, image=None)\nopen_button = tk.Button(left_frame, text=\"Open\", command=change_dropdown)\nsave_button = tk.Button(left_frame, text = \"Save\", command = save)\n</code></pre>\n\n<p>Because these are all in a common frame, and separate from the widgets in the other frame, you are free to use <code>pack</code>, <code>grid</code>, or <code>place</code>. If you use <code>grid</code>, you don't have to worry about how the size of rows on the left affect the appearance of objects on the right.</p>\n\n<p>Next, focus on the widgets on the right, following the same pattern: create the widgets as children of the right frame, and then lay them out using whatever layout manager works best. </p>\n\n<h2>Organize your code</h2>\n\n<p>You have code that looks like this, which is very hard to read:</p>\n\n<pre><code>var1 = IntVar()\nCheckbutton(mainframe, text=\"Ingredients present in full (any allergens in bold with allergen warning if necessary)\", variable=var1).grid(column = 2, row=1, sticky=W)\nvar2 = IntVar()\nCheckbutton(mainframe, text=\"May Contain Statement.\", variable=var2).grid(column = 2, row=2, sticky=W)\n...\n</code></pre>\n\n<p>Instead, do one of two things. First, you can separate your data definitions (<code>var1 = IntVar()</code>) from your widget definition. For example:</p>\n\n<pre><code>var1 = IntVar()\nvar2 = IntVar()\n\nCheckbutton(mainframe, text=\"Ingredients present in full (any allergens in bold with allergen warning if necessary)\", variable=var1).grid(column = 2, row=1, sticky=W)\nCheckbutton(mainframe, text=\"May Contain Statement.\", variable=var2).grid(column = 2, row=2, sticky=W)\n</code></pre>\n\n<p>A better solution would be to use a data structure that lets you create these widgets and variables in a loop. By doing that, if you decide at a future date to change the look of a widget, you only have to change one or two lines of code rather than dozens.</p>\n\n<p>For example, assuming you've created a separate frame just for the checkbuttons (eg: <code>right_frame</code>), it might look like this:</p>\n\n<pre><code>required_info = [\n \"Ingredients present in full ...\",\n \"May Contain Statement\",\n \"Cocoa Content (%)\",\n \"...\",\n ]\n\n\nvars = []\nfor info in required_info:\n var = IntVar(value=0)\n vars.append(var)\n cb = tk.Checkbutton(right_frame, text=info, variable=var, onvalue=1, offvalue=0, justify=\"left\")\n cb.pack(side=\"top\", fill=\"x\")\n</code></pre>\n\n<p>With that, to add another required piece of info you only have to add a single line to the <code>required_info</code> array, rather than two or three lines of code. Plus, it makes it trivial to rearrange the order of the items since you only have to reorder the list rather than the code</p>\n\n<p>To get the values, you can then just iterate over the list of vars:</p>\n\n<pre><code>for var in vars:\n print(var.get())\n</code></pre>\n\n<p>You can even use the required information as the name of the widget:</p>\n\n<pre><code>for info in required_info:\n var = IntVar(value=0, name=info)\n ...\n\n...\nfor var in vars:\n print(\"{} = {}\".format(str(var), var.get()))\n</code></pre>\n\n<h2>Use classes</h2>\n\n<p>In my experience, tkinter is much easier to maintain if you use classes. At the very least, I recommend using a single class for the whole application, if for no other reason than it lets you specify widgets that use callbacks before having to define the callback, leaving your main logic near the top of the file. </p>\n\n<p>For example, instead of this:</p>\n\n<pre><code><define some widgets>\ndef change_dropdown(*args): ...\n<define more widgets>\ndef var_states(): ...\n<define more widgets>\ndef user(): ...\nuser()\ndef save(): ...\n<define more widgets>\nroot.mainloop()\n</code></pre>\n\n<p>... you could have this, which is considerably easier to read:</p>\n\n<pre><code>class App():\n def __init__(self):\n <define all widgets>\n def change_dropdown(self, *args): ...\n def var_states(self): ...\n def user(self): ...\n def save(self): ...\n\napp = App()\napp.root.mainloop()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T17:40:19.647",
"Id": "445973",
"Score": "0",
"body": "Awesome! I will update my code using this as my guide and learn from it! Will put my new code as answer and mention you in it. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T19:28:47.440",
"Id": "445997",
"Score": "0",
"body": "Love that loop idea for the checkboxes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T19:41:16.020",
"Id": "446002",
"Score": "0",
"body": "for this `for var in vars:\n print(\"{} = {}\".format(str(var), var.get()))` How can i get the required info text to appear instead of `PY_VAR1`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T19:42:13.257",
"Id": "446003",
"Score": "0",
"body": "@98Ed: `var = IntVar(value=0, name=info)`. Notice the `name=` parameter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T19:47:44.067",
"Id": "446005",
"Score": "0",
"body": "kinda confused, I am trying to re-code the var_states function, should I be using this at all?.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T19:55:50.297",
"Id": "446009",
"Score": "0",
"body": "becasue when I use ` for info in required_info:\n var = IntVar(value=0, name=info)\n\n for var in vars:\n print(\"{} = {}\".format(str(var), var.get()))` it still returns me `PY_VAR1`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T20:45:11.883",
"Id": "446017",
"Score": "0",
"body": "@98Ed: sorry, but I can't duplicate that. When I use `name=` both in python 2 and python 3, it works just like I described."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T06:41:42.970",
"Id": "446937",
"Score": "0",
"body": "Hi @BryanOakley have made an update, its a lot longer, but that's where I got to. Concentrated in making classes and functions. Added a another check box side by side for the second person to sign."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T17:08:13.453",
"Id": "229330",
"ParentId": "229264",
"Score": "5"
}
},
{
"body": "<ul>\n<li><p>The label images should be stored as .png files, not .jpeg. Use .png when you have non-photographic graphics, such as line drawings and text. Use .jpeg for photographic images.</p></li>\n<li><p>Taking the snapshot of the application can be done without using a screenshot. See <a href=\"https://stackoverflow.com/q/9886274/1329652\">this question</a> for details.</p></li>\n<li><p>You may wish to revisit the web-application concept: it is simple to forward a Windows Kerberos authentication to a website; all major browsers support it. If your organization has computers joined to Active Domain, the authentication is pretty much already done for you. See for example <a href=\"https://www.cloudera.com/documentation/enterprise/5-12-x/topics/cdh_sg_browser_access_kerberos_protected_url.html\" rel=\"nofollow noreferrer\">this page</a> for details of browser configuration. The web server can use e.g. <a href=\"https://github.com/modauthgssapi/mod_auth_gssapi\" rel=\"nofollow noreferrer\">mod_auth_gssapi</a> module to accept Kerberos authentication forwarded by the user's browser. It can also fall back to manual user + password authentication. The web server can <a href=\"https://wiki.samba.org/index.php/Authenticating_Apache_against_Active_Directory\" rel=\"nofollow noreferrer\">leverage an Active Domain for authentication</a>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T22:31:06.817",
"Id": "229348",
"ParentId": "229264",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T18:30:27.103",
"Id": "229264",
"Score": "2",
"Tags": [
"python",
"beginner",
"tkinter",
"automation"
],
"Title": "Digitizing paper label system with Python"
}
|
229264
|
<p>I have created an Encryption and Decryption Algorithm that encrypts plain text using a given cipher and also decrypts it back to the original notation. It works great.</p>
<p>This was my code for a coding test and the reviewer told me that the class structure is inverse of what is the right way of doing it and that it is sloppy at some places.</p>
<p>I want to know what is wrong with my structuring of classes, if anything. Does it look sloppy? Can someone please help me identify places where it is lacking Best Practices for Java?</p>
<p>I have a <code>MyBuilder</code> class which creates an instance of <code>MyAlgorithm</code>.
<code>MyAlgorithm</code> has the methods to encrypt and decrypt text, and it extends another class called <code>EncryptionAndDecryption</code> where the actual logic of the algorithm resides.</p>
<hr>
<pre class="lang-java prettyprint-override"><code>public class MyAlgorithm extends EncryptionAndDecryption {
public enum Action {
ENCRYPT,
DECRYPT
}
protected MyAlgorithm(final String cipherCharSet) {
super(cipherCharSet);
}
public String encryptText(final String cipher, final String plainText) {
return encryptOrDecryptText(cipher, plainText, Action.ENCRYPT);
}
public String decryptText(String cipher, String encryptedText) {
return encryptOrDecryptText(cipher, encryptedText, Action.DECRYPT);
}
public boolean encryptDirectory(String cipher, String baseDirectory) {
// for each files and sub files in each sub directories, call the following method;
// encryptOrDecryptFile(cipher, file, baseDirectory, Action.ENCRYPT));
}
public boolean decryptDirectory(String cipher, String baseDirectory) {
// for each files and sub files in each sub directories, call the following method;
// encryptOrDecryptFile(cipher, file, baseDirectory, Action.DECRYPT));
}
}
</code></pre>
<pre><code>public class EncryptionAndDecryption {
private final String CIPHER_CHAR_SET;
protected EncryptionAndDecryption(final String cipherCharSet) {
this.CIPHER_CHAR_SET = cipherCharSet;
}
protected final String encryptOrDecryptText(final String cipher, final String inputText, final MyAlgorithm.Action action) {
// method logic here
}
protected final void encryptOrDecryptFile(final String cipher, final Path filePath, final String baseDirectory, final MyAlgorithm.Action action) {
// method logic here
}
}
</code></pre>
<pre><code>public class MyBuilder {
private String CIPHER_CHAR_SET;
private MyBuilder() {}
public static MyBuilder builder() {
return new MyBuilder();
}
public MyBuilder withCipherSet(String cipherSet) {
this.CIPHER_CHAR_SET = cipherSet;
return this;
}
public MyAlgorithm build() {
return new MyAlgorithm(CIPHER_CHAR_SET);
}
}
</code></pre>
<pre><code>public class MyEncryptionApp {
public static final String CIPHER_CHAR_SET = "abcdefghijklmnopqrstuvwxyz";
public static void main(String args[]) {
if (args.length != 3) {
System.out.println("Exact 3 parameters required - [action] [key] [target]");
System.exit(1);
}
String action, key, target;
action = args[0];
key = args[1];
target = args[2];
MyAlgorithm myAlgorithm = MyBuilder.builder()
.withCipherSet(CIPHER_CHAR_SET)
.build();
if ("encrypt".equalsIgnoreCase(action)) {
System.out.println(myAlgorithm.encryptText(key, target));
} else if ("decrypt".equalsIgnoreCase(action)) {
System.out.println(myAlgorithm.decryptText(key, target));
} else if ("encryptDir".equalsIgnoreCase(action)) {
if(myAlgorithm.encryptDirectory(key, target)) {
System.out.println("Directory encryption Successful");
}
} else if ("decryptDir".equalsIgnoreCase(action)) {
if(myAlgorithm.decryptDirectory(key, target)) {
System.out.println("Directory decryption Successful");
}
} else {
System.out.println("action [" + action + "] not implemented");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T18:38:35.500",
"Id": "446191",
"Score": "1",
"body": "Welcome to Code Review! Please do not update the code in your question. 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)."
}
] |
[
{
"body": "<p>Hello and welcome to Code Review! I try to give a possible explanation of what the reviewer meant when he was talking about inverse class structure; in the <code>main</code> method this code is present:</p>\n\n<pre><code>MyAlgorithm myAlgorithm = MyBuilder.builder()\n .withCipherSet(CIPHER_CHAR_SET)\n .build();\n</code></pre>\n\n<p>But from your code <code>MyAlgorithm</code> is a subclass of <code>EncryptionAndDecryption</code> and this is the class where you defined the operations of encryption and decryption , so the method shoud have return an instance of class <code>EncryptionAndDecryption</code> instead of one subclass. \nOther problem: in the class <code>EncryptionAndDecryption</code> we have the below methods:</p>\n\n<pre><code>protected final String encryptOrDecryptText(final String cipher, final String inputText, final MyAlgorithm.Action action)\n\nprotected final void encryptOrDecryptFile(final String cipher, final Path filePath, final String baseDirectory, final MyAlgorithm.Action action)\n</code></pre>\n\n<p>With parameter <code>MyAlgorithm.Action action</code> the class <code>EncryptionAndDecryption</code> will be dependant from its subclass <code>MyAlgorithm</code> and without its subclass it cannot be even compiled.\nIn the class <code>EncryptionAndDecryption</code> I would make two distinct methods for encryption and decryption of strings, putting these related to files and directory in the subclass <code>MyAlgorithm</code>, deleting the enum value you are using to distinguish between the two operations.\nStyle problem : in the <code>main</code> method is present a list of <code>if</code> like this below:</p>\n\n<pre><code>if (\"encrypt\".equalsIgnoreCase(action)) {}\n</code></pre>\n\n<p>Normally it is the string compared to the string literal like:</p>\n\n<pre><code>if (action.equalsIgnoreCase(\"encrypt\")) {}\n</code></pre>\n\n<p>You can substitute the list of <code>if</code> with a <code>switch</code> like documented in <a href=\"https://docs.oracle.com/javase/8/docs/technotes/guides/language/strings-switch.html\" rel=\"nofollow noreferrer\">strings-switch</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:34:15.523",
"Id": "445984",
"Score": "0",
"body": "`MyAlgorithm myAlgorithm = MyBuilder.builder()\n .withCipherSet(CIPHER_CHAR_SET)\n .build();`\n\nThe reason it returns `MyAlgorithm` is because I have thought of it as a public facing class which has 4 separate methods to encrypt and String and Files. It doesn't know anything about the implementation. The super class `EncryptionAndDecryption` contains 2 methods that has actual logic needed for the 4 methods in sub class. These are marked protected and final so no one outside of the package can access them, nor can a child override them.\n\nIs this unconventional?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:34:35.983",
"Id": "445985",
"Score": "0",
"body": "I agree that the use of Enum in super class creates a dependency on the child class, instead I should have made a separate enum file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:34:44.997",
"Id": "445986",
"Score": "0",
"body": "`if (\"encrypt\".equalsIgnoreCase(action)) {}`\n\nAgreed, that normally people do it other way round, but I recently learned that doing this way helps prevent NullPointerException.\nAnd, ofcourse switch would have been much better choice here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T07:46:09.783",
"Id": "446075",
"Score": "1",
"body": "@winzhack999 I understand your point, maybe an alternative could be nesting class `EncryptionAndDecryption` inside class `MyAlgorithm` like in [Base64](https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html) and so your `builder` returns just a `MyAlgorithm` instance. This is one possible choice and the reviewer probably had in his mind his personal solution to solve the problem."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T16:43:32.087",
"Id": "229328",
"ParentId": "229268",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229328",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T20:09:57.480",
"Id": "229268",
"Score": "5",
"Tags": [
"java",
"object-oriented",
"file",
"file-system",
"caesar-cipher"
],
"Title": "Plain-text file encryption and decryption"
}
|
229268
|
<p>Can I get a review of my code for the the <a href="https://automatetheboringstuff.com/chapter3/#calibre_link-2229" rel="noreferrer">Collatz Sequence from Chapter three of <em>Automate the Boring Stuff with Python</em></a>?</p>
<blockquote>
<p><strong>The Collatz Sequence</strong></p>
<p>Write a function named collatz() that has one parameter named number.
If number is even, then collatz() should print number // 2 and return
this value. If number is odd, then collatz() should print and return 3
* number + 1.</p>
<p>Then write a program that lets the user type in an integer and that
keeps calling collatz() on that number until the function returns the
value 1. (Amazingly enough, this sequence actually works for any
integer—sooner or later, using this sequence, you’ll arrive at 1! Even
mathematicians aren’t sure why. Your program is exploring what’s
called the Collatz sequence, sometimes called “the simplest impossible
math problem.”)</p>
<p>Remember to convert the return value from input() to an integer with
the int() function; otherwise, it will be a string value.</p>
<p>Hint: An integer number is even if number % 2 == 0, and it’s odd if
number % 2 == 1.</p>
<p><strong>The output of this program could look something like this:</strong></p>
<pre class="lang-none prettyprint-override"><code>Enter number:
3
10
5
16
8
4
2
1
</code></pre>
<p><strong>Input Validation</strong></p>
<p>Add try and except statements to the previous project to detect
whether the user types in a noninteger string. Normally, the int()
function will raise a ValueError error if it is passed a noninteger
string, as in int('puppy'). In the except clause, print a message to
the user saying they must enter an integer.</p>
</blockquote>
<p>I am mainly wondering if there is a cleaner way to write my solution.</p>
<pre class="lang-py prettyprint-override"><code>def collatz(num):
while num > 1:
if num % 2 == 0:
print(num//2)
num = num //2
elif num % 2 ==1:
print(3*num+1)
num = 3*num+1
else:
print(num)
def getNum():
global num
num = (input("> "))
try:
num = int(num)
except ValueError:
print('plese enter a number')
getNum()
getNum()
collatz(num)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T20:49:27.913",
"Id": "445856",
"Score": "2",
"body": "Please add some description indicating what this chapter 3 thing is recommending with examples of input and output, nobody's going to guess what that is"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T21:07:43.437",
"Id": "445861",
"Score": "0",
"body": "@Edmad Broctor and @ Carcigenicate Thanks for your feedback. I went ahead and revised my post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T08:05:09.037",
"Id": "445901",
"Score": "6",
"body": "\"Amazingly enough, this sequence actually works for any integer—sooner or later, using this sequence, you’ll arrive at 1!\" Actually we don't know that it works for any integer, the idea that it will always reach 1 is a conjecture."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T17:11:00.223",
"Id": "445967",
"Score": "1",
"body": "@PierreCathé I have a truly marvelous demonstration of this proposition which this comment box is too small to contain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T06:45:13.393",
"Id": "446072",
"Score": "0",
"body": "@Acccumulation Wow ! That's impressive, in that case you should update the Wikipedia article, and contact the International Mathematical Union to collect your Fields Medal."
}
] |
[
{
"body": "<p>First, note how you're duplicating calculations:</p>\n\n<pre><code>print(num//2)\nnum = num //2\n</code></pre>\n\n<p>This may not cause issues with this specific code, but it isn't a good practice. You're doing twice as much work as you need to, which can cause performance issues once you start writing more complicated code. Do the calculation once, and save the result. In this case though, all you need to do is reverse those lines and use <code>num</code>:</p>\n\n<pre><code>num = num // 2\nprint(num)\n</code></pre>\n\n<p>Also, make sure you have proper spacing <a href=\"https://www.python.org/dev/peps/pep-0008/#other-recommendations\" rel=\"noreferrer\">around operators, and be consistent</a>.</p>\n\n<hr>\n\n<p>Your <code>if</code> and <code>elif</code> cases are exclusive of each other, and your <code>else</code> should never happen. If the first condition is true, then other must be false and vice-versa. There's no need for the second check. Once rewritten, you'll see that printing in every case isn't necessary. You can just print after:</p>\n\n<pre><code>while num > 1:\n if num % 2 == 0:\n num = num // 2\n\n else:\n num = 3 * num + 1\n\n print(num)\n</code></pre>\n\n<p>Since you're just reassinging <code>num</code> one of two options based on a condition, a conditional expression can be used here cleanly as well:</p>\n\n<pre><code>while num > 1:\n num = (num // 2) if num % 2 == 0 else (3 * num + 1)\n print(num)\n</code></pre>\n\n<p>The braces aren't necessary, but I think they're useful here due to the number of operators involved.</p>\n\n<hr>\n\n<hr>\n\n<p>Printing the numbers isn't ideal here. In most code, you need to be able to <em>use</em> the data that you produce. If you wanted to analyze the produced sequence, you would have to do something intercept the stdout, which is expensive and overly complicated. Make it a function that accumulates and returns a list. In the following examples, I also added some <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\">type hints</a> to make it clearer what the type of the data is:</p>\n\n<pre><code>from typing import List\n\ndef collatz(starting_num: int) -> List[int]:\n nums = [starting_num]\n\n num = starting_num\n while num > 1:\n num = (num // 2) if num % 2 == 0 else (3 * num + 1)\n nums.append(num)\n\n return nums\n</code></pre>\n\n<p>Or, a much cleaner approach is to make it a <a href=\"https://docs.python.org/3/tutorial/classes.html#generators\" rel=\"noreferrer\">generator that yields the numbers</a>:</p>\n\n<pre><code># Calling this function returns a generator that produces ints\n# Ignore the two Nones, as they aren't needed for this kind of generator\ndef collatz_gen(starting_num: int) -> Generator[int, None, None]:\n yield starting_num\n\n num = starting_num\n while num > 1:\n num = (num // 2) if num % 2 == 0 else (3 * num + 1)\n yield num\n\n>>> list(collatz_gen(5))\n[5, 16, 8, 4, 2, 1]\n</code></pre>\n\n<hr>\n\n<hr>\n\n<p>There's a few notable things about <code>getNum</code>:</p>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles\" rel=\"noreferrer\">Python uses \"snake_case\"</a>, not \"camelCase\".</p>\n\n<hr>\n\n<p>Your use of <code>global num</code> here is unnecessary and confusing. Just like before, explicitly <code>return</code> any data that the function produces:</p>\n\n<pre><code>def get_num() -> int:\n raw_num = input(\"> \")\n\n try:\n return int(raw_num)\n\n except ValueError:\n print('Please enter a number')\n return get_num()\n</code></pre>\n\n<p>Note how instead of reassigning a global <code>num</code>, we're just returning the number. I also spaced things out a bit, and used some more appropriate names. Conceptually, I'd say that <code>num = input(\"> \")</code> is wrong. At the time that that runs, <code>num</code> does <em>not</em> contain a number (it contains a string).</p>\n\n<hr>\n\n<p>This isn't a good use of recursion. It <em>likely</em> won't cause you any problems, but if your user is really dumb and enters wrong data ~1000 times, your program will crash. Just use a loop:</p>\n\n<pre><code>def get_num() -> int:\n while True:\n raw_num = input(\"> \")\n\n try:\n return int(raw_num)\n\n except ValueError:\n print('Please enter a number')\n</code></pre>\n\n<p>In languages like Python, be careful using recursion in cases where you have no guarantees about how many times the function will recurse.</p>\n\n<hr>\n\n<p>I'd also probably name this something closer to <code>ask_for_num</code>. \"get\" doesn't make it very clear about where the data is coming from.</p>\n\n<hr>\n\n<hr>\n\n<p>Taken altogether, you'll end up with:</p>\n\n<pre><code>from typing import Generator\n\ndef collatz_gen(starting_num: int) -> Generator[int, None, None]:\n yield starting_num\n\n num = starting_num\n while num > 1:\n num = (num // 2) if num % 2 == 0 else (3 * num + 1)\n yield num\n\ndef ask_for_num() -> int:\n while True:\n raw_num = input(\"> \")\n\n try:\n return int(raw_num)\n\n except ValueError:\n print('Please enter a number')\n</code></pre>\n\n<p>Which can be used like:</p>\n\n<pre><code>num = ask_for_num()\n\nfor n in collatz_gen(num):\n print(n)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T21:29:59.427",
"Id": "229275",
"ParentId": "229270",
"Score": "9"
}
},
{
"body": "<h2>Prompt</h2>\n\n<p>The most obvious bad practice here is the use of a global variable. Instead of setting <code>num</code> as a side-effect, your function should <code>return</code> the result.</p>\n\n<p><code>getNum()</code> is not such a good name for the function. <a href=\"https://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"noreferrer\">PEP 8</a>, the official style guide for Python, says that function names should be <code>lower_case_with_underscores</code>. Furthermore, \"get\" implies that the function is retrieving a piece of data that is already stored somewhere, which is not the case here. Finally, \"Num\" should be more specific.</p>\n\n<p>The use of recursion is not appropriate. If you want a loop, write a loop.</p>\n\n<pre><code>def ask_integer():\n \"\"\"\n Return an integer entered by the user (repeatedly prompting if\n the input is not a valid integer).\n \"\"\"\n while True:\n try:\n return int(input(\"> \"))\n except ValueError:\n print(\"Please enter an integer\")\n\nnum = ask_integer()\n</code></pre>\n\n<h2><code>collatz</code> function</h2>\n\n<p>Strictly speaking, you didn't follow the instructions. Your solution isn't wrong or bad — you just didn't implement the <code>collatz</code> function according to the specification that was given, which says that you should print and return one single number.</p>\n\n<pre><code>def collatz(num):\n \"\"\"\n Given a number, print and return its successor in the Collatz sequence.\n \"\"\"\n next = num // 2 if num % 2 == 0 else 3 * num + 1\n print(next)\n return next\n\nnum = ask_integer()\nwhile num > 1:\n num = collatz(num)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T23:04:03.127",
"Id": "445871",
"Score": "0",
"body": "Perhaps reverse the test and eliminate the comparison to 0: `next = 3 * num + 1 if num % 2 else num // 2`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T01:02:02.840",
"Id": "445876",
"Score": "4",
"body": "@RootTwo Honestly, I find that that muddies the intent. We're not checking if `num % 2` is falsey; it's not a predicate. We're checking if it's equal to 0. It just so happens that they're equivalent in Python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T08:16:25.053",
"Id": "445904",
"Score": "0",
"body": "`next = ...` overshadows the built-in `next`. In this context it's probably not hazardous, but just good to be aware of"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T09:01:40.930",
"Id": "445908",
"Score": "0",
"body": "While technically you could use `if num % 2 else`, I agree that showing the intent here is more important. and `if num % 2 == 0 else` communicates that intent better. I do agree you should rename your `next` variable, though. It's a bad habit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T18:25:38.137",
"Id": "446188",
"Score": "0",
"body": "@200_success Thanks for pointing out my failure to return the number not simply print it. That was very helpful."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T22:14:57.360",
"Id": "229278",
"ParentId": "229270",
"Score": "11"
}
},
{
"body": "<p>For sake of completeness, a recursive implementation for <code>collatz</code> (you already got enough good suggestions for inputting <code>num</code>):</p>\n\n<pre><code>def collatz(num):\n print(num)\n if num == 1:\n return num\n if num % 2 == 0:\n return collatz(num // 2)\n return collatz(3 * num + 1)\n\ncollatz(3)\n</code></pre>\n\n<p>Outputs</p>\n\n<pre><code>3\n10\n5\n16\n8\n4\n2\n1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T09:45:20.940",
"Id": "445911",
"Score": "1",
"body": "I don't think this answer helps OP. Although a recursive definition is certainly possible, it doesn't fit the specification they are trying to meet. Furthermore, this code has some redundancy: the function always returns 1 (when it returns at all), so why even have a return value?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T09:58:59.253",
"Id": "445912",
"Score": "0",
"body": "@MeesdeVries `the function always returns 1 (when it returns at all), so why even have a return value` I'm not sure I follow. The recursion must have a base case. It just so happens that the base case in this example is if `num == 1`. The example output shows that the function does **not** always returns 1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T10:04:16.310",
"Id": "445913",
"Score": "1",
"body": "The function *prints* other values, but it *returns* only the value 1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T10:10:58.063",
"Id": "445914",
"Score": "0",
"body": "@MeesdeVries Only the base case of the recursion (ie the last call) returns 1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T12:48:08.260",
"Id": "445937",
"Score": "0",
"body": "But this return value is then propagated upwards, so that the function returns the value that is returned in the base case. If you disagree: just pick an input `n` for which you believe the return value is not 1, and run `print(\"\\n\\n\" + str(collatz(n)))` and look at the *last* output to see what I mean."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T14:42:15.950",
"Id": "445956",
"Score": "0",
"body": "@MeesdeVries But that is how any recursion works. Only the last returned value (the base case) is what counts. I'm not saying this solution is the best, I solely suggested a different approach"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T14:46:33.530",
"Id": "445957",
"Score": "1",
"body": "I am not sure what your point is. My original comment noted that there is no need for the function you wrote to return anything, because it will always be the number 1, regardless of input. Therefore a better implementation would avoid returning any value at all, to avoid the suggestion that it is meaningful. E.g., I would say a better implementation (of the recursion part) is `if num % 2 == 0: collatz(num//2); elif num > 1: collatz(3 * num + 1)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T14:53:34.010",
"Id": "445958",
"Score": "0",
"body": "@MeesdeVries That would cause an infinite recursion"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T15:09:22.400",
"Id": "445960",
"Score": "1",
"body": "I invite you to try the code I wrote out for yourself to see that it does not (at least, for positive integer input). If you wish to discuss this any further I suggest we take it to chat."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T08:22:01.577",
"Id": "229296",
"ParentId": "229270",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229275",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T20:38:03.013",
"Id": "229270",
"Score": "8",
"Tags": [
"python",
"collatz-sequence"
],
"Title": "Python - The Collatz Sequence"
}
|
229270
|
<p>In short, I need help simplifying and optimizing this code because now that I have switched to a tree widget from 2 list widgets, loading the tables has increased by roughly 3-4 seconds (used to be almost instant). I would also like to shorten this function if possible.</p>
<pre><code>--- Background Info ---
self.tableData -- The table that the information is being displayed to
getItem() -- a function that when a table of a database is selected, returns the database name (var[0]) and the table name (var[1])
columnNames -- Returns the column names for the table
rows -- returns the total number of rows in the table
g -- index value for the row
h -- index value for the column the data will go in
-- forgot what i, j, k do because i was working on other parts of the program, but they are needed (been some time now)
</code></pre>
<p>Note: This code belongs to a class which I have not included</p>
<pre><code>def LoadTable():
self.tableData.clear()
if getItem() != None:
var = getItem()
try:
ccnnxx = mysql.connector.connect(user=self.uname.text(), password=self.upass.text(), host=self.uhost.text(), port=self.uport.text(), database = var[0])
cursor = ccnnxx.cursor()
self.tableData.setRowCount(0)
self.tableData.setColumnCount(0)
header = self.tableData.horizontalHeader()
item = getItem()
cursor.execute("SELECT * FROM " + var[1])
rows = cursor.fetchall()
self.tableData.setRowCount(cursor.rowcount)
ccnnxx.close()
self.tableData.setColumnCount(len(rows[0]))
columnNames = [a[0] for a in cursor.description]
g = 0
h = 0
i = 0
j = 0
k = 0
counter = 0
for items in columnNames:
item = QtWidgets.QTableWidgetItem()
self.tableData.setHorizontalHeaderItem(g, item)
self.tableData.horizontalHeaderItem(g).setText(QtWidgets.QApplication.translate("MainWindow", columnNames[h], None, -1))
header.setSectionResizeMode(g, QtWidgets.QHeaderView.ResizeToContents)
g += 1
h += 1
for row in rows:
counter += 1
if i < counter:
while j != len(rows[0]):
item = QtWidgets.QTableWidgetItem()
self.tableData.setItem(i, k, item)
self.tableData.item(i, k).setText(QtWidgets.QApplication.translate("MainWindow", str(row[j]), None, -1))
k +=1
j +=1
else:
i +=1
k = 0
j = 0
else:
k = 0
j = 0
except IndexError:
#print('This table has no information!')
pass
except TypeError:
#double right-click protection
pass
else:
pass
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T20:57:26.777",
"Id": "229272",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"mysql",
"pyside"
],
"Title": "PySide2 Row and Column Creator"
}
|
229272
|
<p>There will be a huge object mapping (transforming) with a lot of calculations and logic for some fields.</p>
<p>I would like to refactor this to classes or some kind of separation so it will be easily testable (jest) for each field. How would you abstract these to a few classes or which design pattern that is best suited for this?</p>
<p>For example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> const data = {
id: 111,
items: [
{
title: "Title One",
qty: "2",
price: "1.00",
vat: 20,
},
{
title: "Title Two",
qty: "3",
price: "5.00",
vat: 20,
}
],
address: {
price: 5,
name: "Tommy",
line_1: "Line 1",
line_2: "Line 2",
line_3: "Line 3",
}
}
function mapData(data) {
const orderItems = data.items.map(item => {
return {
Name: item.title,
Qty: parseInt(item.qty),
Price: item.price,
Total: getOrderItemTotal(item),
TotalIncVat: getOrderItemTotalIncVat(item),
// and many more fields
}
});
return {
Id: data.id,
Total: getOrderTotal(data, orderItems),
Items: orderItems,
DeliveryAddress: {
ShippingCost: data.address.price,
Name: data.address.name,
Address1: data.address.line_1,
Address2: data.address.line_2,
Address3: data.address.line_3,
},
// and many more fields
}
}
function getOrderTotal(data, orderItems) {
const totalCostItems = orderItems.reduce((acc, item) => {
return acc + parseFloat(item.TotalIncVat);
}, 0);
return (totalCostItems + data.address.price).toFixed(2);
}
function getOrderItemTotal(item) {
const totalPrice = parseFloat(item.price) * parseInt(item.qty);
return totalPrice.toFixed(2);
}
function getOrderItemTotalIncVat(item) {
const totalPrice = parseFloat(getOrderItemTotal(item));
const vat = (item.vat / 100) * totalPrice;
return (totalPrice + vat).toFixed(2);
}
console.log(mapData(data));</code></pre>
</div>
</div>
</p>
<p>Edit: I would like to know what the best way to refactor this mapping to multiple files (or Classes?) and calculation logic as in clean code and follow SOLID principles. To follow SOLID principles, I am thinking to create <code>Order</code> class, <code>OrderItem</code> class and <code>DeliveryAddress</code> class? </p>
<p>Each class would have some calculations method. </p>
<p>If class is not necessary, what are alternative options? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T20:30:54.413",
"Id": "446015",
"Score": "1",
"body": "@dfhwze Updated: added an example of calculate methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T08:09:53.230",
"Id": "446077",
"Score": "0",
"body": "Could you edit to clarify the purpose (in body and title)? At the moment, we have \"*transforming ... calculations and logic*\", which describes most code we see here. Can you be more specific? Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T18:41:17.420",
"Id": "446193",
"Score": "0",
"body": "@TobySpeight I have edited my topic and I have tried my best to be more specific"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T21:00:45.687",
"Id": "229273",
"Score": "5",
"Tags": [
"javascript",
"design-patterns",
"node.js"
],
"Title": "Mapping abstraction? (Node JS)"
}
|
229273
|
<p>I'm having a problem modifying the code so function <em>solve_quadratic</em>, that returns both solutions of a generic quadratic as a pair (2-tuple) when the coefficients are given as parameters. It should work like this:</p>
<p><a href="https://i.stack.imgur.com/d0sJr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d0sJr.jpg" alt="enter image description here"></a></p>
<p>This is my code</p>
<pre><code>import math
def solve_quadratic(a, b, c):
d = int(b*b) - int(4*a*c)
sol1 = (-b-math.sqrt(d))/(2*a)
sol2 = (-b+math.sqrt(d))/(2*a)
print('({} {})'.format(sol2, sol1))
return solve_quadratic
def main():
solve_quadratic(1, -3, 2)
solve_quadratic(1, 2, 1)
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T21:39:03.300",
"Id": "445863",
"Score": "0",
"body": "Welcome to code-review. Your questions currently reads as though the code isn't working. If this is the case, then this question is off-topic, as we can only review complete and working code here. If I have mis-understood, than you might consider rephrasing the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T21:45:26.200",
"Id": "445865",
"Score": "0",
"body": "@VisualMelon the code works just fine, it basically serves the purpose of the quadratic formula . I want to modify it as mentioned above so that the function solve_quadratic returns the two solutions into the main function . by two solutions I mean the (2,0, 1,0) and (-1,0,-1,0)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T21:59:06.007",
"Id": "445867",
"Score": "0",
"body": "If your code isn't producing the expected output, then it isn't working fine: requests to change or fix basic functionality are not on-topic on code-review. It might have been better to ask this question on stack overflow, but you'd have to check their [Help Center](https://stackoverflow.com/help)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T01:22:18.467",
"Id": "445877",
"Score": "0",
"body": "@VisualMelon: let's not get pedantic here: the code merely needs to swap the `print()` for a `return` statement. Also, strip the unnecessary `int()` calls. Essentially the code nearly works (new users often confuse printing a result with returning it), and can be fixed in 30 seconds flat, far less than time arguing about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T11:15:21.633",
"Id": "445922",
"Score": "0",
"body": "@smci while I agree the fixes are minor, our basic standards require the OP understand the code and that the code works correctly. While beginner questions are welcome here, and stuff like the `int` might be considered an 'edge case' they missed, the fact that they are explicitly asking for help with changing the basic functionality means it must be off-topic (in my opinion). Remember that putting a question on hold is an opportunity for the OP to discuss with us why it is on hold and resolve it: we want to ensure that every question is high quality."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T16:21:55.303",
"Id": "446462",
"Score": "0",
"body": "Ed1995: all you need to do to get this reopened is edit the code to work correctly."
}
] |
[
{
"body": "<ol>\n<li><p><strong>Obvious bug: confusing <code>print</code> with <code>return</code> in a function</strong></p>\n\n<ul>\n<li>your spec says modify the code so your function <strong>returns</strong> both solutions as a tuple. Not <strong>print</strong> them, which is what it currently does.</li>\n<li>remove the <code>print(...)</code> line inside the function</li>\n<li>the line <code>return solve_quadratic</code> should now be <code>return sol1, sol2</code></li>\n<li>in general get out of the bad habit of having functions print their result instead of returning it (strictly that makes it only a subroutine, not a function). Returning the result is much more flexible, we can use it in unit-test, send it into another function or iterator, etc. If you only want to print the function's output, have your calling code do that: <code>print(solve_quadratic(...))</code>. So you lose nothing and gain a huge amount by having functions always return their result.</li>\n</ul></li>\n<li><p>Nastier bug: Your code is <strong>arbitrarily rounding subvalues to integers for no good reason, and hence returns the wrong answer for many non-integer inputs</strong>:</p>\n\n<ul>\n<li>Why does it do <code>d = int(b*b) - int(4*a*c)</code>, that's weird and outright wrong. Why not simply <code>d = b*b - 4*a*c</code>? Why are you rounding anything before the division? (If your intent is merely to get rounded solutions, then do say <code>round(sol, 1)</code> at the end)</li>\n<li>Example: calling your function on <code>a=1, b=4, c=4.1</code> will wrongly round the slightly negative discriminant up to 0 and wrongly return a real result, where it should throw a ValueError</li>\n<li>the code is not quite requiring all of <code>a,b,c</code> to be integers, but nearly: it (totally arbitrarily) requires b to at least be the sqrt of an integer, and <code>4*a*c</code> to be an integer.</li>\n<li>as an aside we've uncovered that your spec/teacher didn't seem to care about testing with non-integer inputs.</li>\n<li>(at least in Python 3 you no longer have to care about integer division and unwanted rounding when dividing an integer numerator by an integer denominator, which would have given a second unwanted source of rounding on the line <code>(-b + math.sqrt(d))/(2*a)</code>)</li>\n</ul></li>\n<li><p><strong>Exception for negative discriminant case, do you need to handle it</strong></p>\n\n<ul>\n<li>You don't handle the case where the discriminant is negative <code>d = int(b*b) - int(4*a*c)</code> hence taking <code>sqrt(d)</code> will blow up (if you're looking for real roots only). If you want to handle that, you could <code>try...catch</code> the <code>ValueError: math domain error</code> and return the tuple <code>None, None</code>. Probably this doesn't matter in your exercise, but it's good practice not to write exception-happy code that generally behaves well (unless you explicitly want the <code>ValueError</code> on negative discriminant). It all depends on what behavior your client code expects.</li>\n</ul></li>\n<li><p><strong>You can do <code>from math import sqrt</code> for common everyday identifiers</strong></p>\n\n<ul>\n<li>Now you can write <code>sqrt</code> rather than <code>math.sqrt</code> and your code is shorter and clearer. Python ain't Java :) We don't want to see fully qualified package names for simple everyday stuff like <code>sqrt</code>, <code>abs</code>, <code>ceil</code>, <code>random</code> etc. Well maybe some teachers do, but they were probably indoctrinated in Java-land, with abominations like <code>System.out.println()</code> and <code>.toString()</code>, and simple lines exceed 80 chars and thus are unreadable (and in fact defeat some diff'ing tools). Those teachers are made of wood, therefore weigh the same as a duck, therefore...</li>\n<li>Just don't abuse with huge import lines: <code>from package import thing1, thing2, thing3, thing4, thing5...</code>. Do <code>import sqrt</code> if you want to use lots of its functions. You can still also do <code>from math import sqrt, abs</code> for the subset of functions you use a lot. Yes, this is strictly frowned upon, but it makes for shorter clearer code.</li>\n<li>Or if you ever started using numpy, which also has a (different) <code>numpy.sqrt</code> function, then you don't want your code to be at the mercy of whichever imports got run, and which order. So then you'd write an explicit <code>math.sqrt</code> or <code>np.sqrt</code>. (Probably you'd never use <code>math.sqrt</code> again, but you get the wider point about avoiding name collisions.)</li>\n</ul></li>\n<li><p>Give the function a <strong>docstring</strong></p>\n\n<ul>\n<li>it's good practice, it tell us the input args and types, and return type(s)</li>\n<li>you can also mention the input domain is restricted, what assumptions you make, whether you handle corner cases. e.g. <em>\"real coefficients a,b,c, returns real roots only (, errors on negative discriminants)\"</em></li>\n<li>particularly important when your code might get thrown over the wall to someone else to use and/or test, i.e. any non-trivial real-world codebase</li>\n</ul></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T21:41:58.820",
"Id": "229277",
"ParentId": "229274",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T21:14:41.437",
"Id": "229274",
"Score": "-1",
"Tags": [
"python"
],
"Title": "Solving quadratic functions in Python"
}
|
229274
|
<p>From "Cracking the Coding Interview":</p>
<blockquote>
<p>Write a program to sort a stack in ascending order (with biggest items on top). You may use at most one additional stack to hold items, but you may not copy the elements into any other data structure (such as an array). The stack supports <code>push</code>, <code>pop</code>, <code>is_empty</code>, and <code>peek</code></p>
</blockquote>
<p>The classic solution I found online to this (and the one in the book) is something like this:</p>
<h2>Algo #1 (Classic)</h2>
<blockquote>
<pre class="lang-py prettyprint-override"><code>
def sort_stack(primary):
secondary = []
while primary:
tmp = primary.pop()
while (secondary and secondary[-1] > tmp):
primary.append(secondary.pop())
secondary.append(tmp)
return secondary
</code></pre>
</blockquote>
<p>The gist of this being that we will return our secondary/auxiliary stack after sorting via <span class="math-container">\$O(n^2)\$</span> time.</p>
<p>This is not what my initial approach was, however, and I do think my approach has some interesting qualities:</p>
<h2>Algo #2 (Mine)</h2>
<pre class="lang-py prettyprint-override"><code>def sort_stack(primary):
did_sort = False
secondary = []
while not did_sort:
# move from primary to secondary, pushing larger elements first when possible
desc_swap(primary, secondary)
# move from secondary back to primary, pushing smaller elements first when possible. Set did_sort = True if we're done and can exit.
did_sort = asc_swap(secondary, primary)
return primary
def asc_swap(full, empty):
temp = None
did_sort = True
yet_max = None
while full:
if not temp:
temp = full.pop()
if full:
if full[-1] < temp:
insert = full.pop()
if insert < yet_max:
did_sort = False
yet_max = insert
empty.append(insert)
else:
empty.append(temp)
temp = None
if temp:
empty.append(temp)
return did_sort
def desc_swap(full, empty):
temp = None
while full:
if not temp:
temp = full.pop()
if full:
if full[-1] > temp:
empty.append(full.pop())
else:
empty.append(temp)
temp = None
if temp:
empty.append(temp)
</code></pre>
<p>Now obviously it is not nearly as clean or elegant, but it could be with some helper functions that dynamically choose our comparator and choose which element to push, etc.</p>
<p>Basically what it is doing is this:</p>
<pre><code># Start with stack in wrong order (worst case)
primary: 4 3 2 1
secondary:
# Swap to secondary, pushing larger elements first (1 is held in temp until the end because it is smaller than the following elements)
primary:
secondary: 2 3 4 1
# Swap back to primary, pushing smaller elements first
primary: 1 3 2 4
secondary:
# back to secondary
primary:
secondary: 4 3 2 1
# Back to primary, finished
primary: 1 2 3 4
secondary:
</code></pre>
<p>This strategy has a best-case/worst-case tradeoff.
Algo #1 actually performs <em>worst</em> when the stack is already sorted and best when the stack is sorted in the wrong order, and algo #2 does the opposite.</p>
<h2>Questions</h2>
<ul>
<li>What are your thoughts? I think it is just an interesting way to sort that I haven't seen before. </li>
<li>Is there a name for this kind of sorting? I couldn't find similar algos but I'm sure theyre out there and would love to be able to describe it/recognize it better.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T11:30:36.720",
"Id": "445926",
"Score": "0",
"body": "Honestly the question isn't solvable if read in it's most strict form. A single temp variable is technically a data structure so you unless you are allowed to swap the top elements you can only scan along them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T10:09:11.053",
"Id": "447220",
"Score": "1",
"body": "`couldn't find similar [algorithms]` alternating sort order has been used in \"read backwards tape sort\" for a long time."
}
] |
[
{
"body": "<p>I really don't recommend trying to write anything that is more complicated than necessary during an interview, especially if it's on a whiteboard. Interviews are stressful enough for you; introducing more opportunities for errors is not a good idea. As for the interviewer, their likely thoughts are that your code lacks elegance and is hard to verify.</p>\n\n<p>In this case, your code is buggy and crashes for <code>sort_stack([3, 1, 4, 1])</code> on line 22, in <code>asc_swap</code>:</p>\n\n<pre><code> if insert < yet_max:\nTypeError: '<' not supported between instances of 'int' and 'NoneType' <span class=\"math-container\">`</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T17:55:24.140",
"Id": "447161",
"Score": "0",
"body": "I totally agree that this is a less good approach for interviewing, but I'm trying to answer the question of whether or not this is a well-known type of sorting or if it has a name?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T05:21:08.493",
"Id": "229288",
"ParentId": "229276",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T21:33:24.410",
"Id": "229276",
"Score": "5",
"Tags": [
"python",
"algorithm",
"sorting",
"interview-questions",
"stack"
],
"Title": "An alternative algorithm for sorting a stack using only one additional stack"
}
|
229276
|
<p>I'm writing a URL validator. Firstly, it checks for special characters in the input. Secondly, it adds 'http://' and checks for validity.</p>
<pre class="lang-java prettyprint-override"><code> /* Returns true if url is valid */
private static boolean isValidURL(String url) {
boolean containsSpecialCharacters = specialCharactersExists(url);
if ( !containsSpecialCharacters ) {
/* Try creating a valid URL */
try {
new URL(String.format("%s%s", "http://", url)).toURI();
return true;
} catch (Exception e) {
/* Not a valid URL */
}
}
return false;
}
/* Returns true if url contains special characters */
private static boolean specialCharactersExists(String input) {
Pattern regex = Pattern.compile("[^A-Za-z0-9.-]");
Matcher matcher = regex.matcher(input);
return matcher.find();
}
</code></pre>
<p>This serves my purpose. I'm seeking advice on how to improve the code (especially the Regex part)</p>
|
[] |
[
{
"body": "<p>Welcome to Code Review!</p>\n\n<p><strong>Bad naming</strong></p>\n\n<p>The method doesn't actually check that a URL is valid, as it allows values that are not URLs. Thus it should not be named as \"isValidURL\". It should be <code>isValidAddress</code> or similar, but not URL. URLs have a <a href=\"https://en.wikipedia.org/wiki/URL#Syntax\" rel=\"nofollow noreferrer\">very well defined syntax</a>.</p>\n\n<p><strong>Unnecessary variables</strong></p>\n\n<p>There is no need to store the return value of <code>specialCharactersExists(url)</code> to a variable. It only adds an unnecessary large if-statement. Instead, check the value and exit early. Also, the characters you check are not special, they're \"illegal\" or \"invalid\" in your implementation so change name to reflect that:</p>\n\n<pre><code> if (illegalCharactersExist(url)) {\n return false;\n }\n</code></pre>\n\n<p><strong>Missing final</strong></p>\n\n<p>Variables that are not supposed to change should be marked as <code>final</code>. If you decide to keep the containsSpecialCharacters variable, it should be marked as final (and named as decribed above).</p>\n\n<pre><code>final boolean containsIllegalCharacters = illegalCharactersExist(url);\n</code></pre>\n\n<p><strong>Reuse Pattern</strong></p>\n\n<p>The Pattern class is <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\" rel=\"nofollow noreferrer\">thread safe</a>. You should compile the pattern once into a static variable and reuse it in the matcher. Also, regex is not a good name. It tells what the variable is, not what it's purpose is. Naming should always reflect purpose.</p>\n\n<pre><code> private static final Pattern ILLEGAL_CHAR_PATTERN = Pattern.compile(\"[^A-Za-z0-9.-]\");\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T06:51:18.580",
"Id": "229290",
"ParentId": "229280",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229290",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T23:36:55.363",
"Id": "229280",
"Score": "3",
"Tags": [
"java",
"strings",
"regex",
"validation",
"url"
],
"Title": "Validate URL with Regex and java.net.URL"
}
|
229280
|
<p>I recently posted <a href="https://codereview.stackexchange.com/questions/228864/adodb-wrapper-class">this</a> question on my implementation of an ADODB Wrapper Class. I realized in my own <a href="https://codereview.stackexchange.com/questions/228864/adodb-wrapper-class/229193#229193">review</a> that I was missing some very important things, so much so, that I decided it would be worth it to re-write the entire class. Saying that I have done quite a bit of restructuring so I am going to provide an outline of what I have done and why. </p>
<p><strong>Numeric Parameters:</strong> </p>
<p>I removed the public properties <code>ParameterNumericScale</code> and <code>ParameterPrecision</code> as I was not considering the possibility of a parameters with varying <em>precision</em> and <em>numericscale</em>. To address this, I created 2 functions that automatically calculate the <em>precision</em> and <em>numericscale</em> for each parameter passed in: </p>
<pre class="lang-vb prettyprint-override"><code>Private Function CalculatePrecision(ByVal Value As Variant) As Byte
CalculatePrecision = CByte(Len(Replace(CStr(Value), ".", vbNullString)))
End Function
Private Function CalculateNumericScale(ByVal Value As Variant) As Byte
CalculateNumericScale = CByte(Len(Split(CStr(Value), ".")(1)))
End Function
</code></pre>
<p><strong>ADO Connection Error's Collection:</strong></p>
<p>I opted to pass the <code>Connection.Errors</code> collection alone, instead of the entire Connection Object to each of the sub procedures <code>ValidateConnection</code> and <code>PopulateADOErrorObject</code>:</p>
<pre class="lang-vb prettyprint-override"><code>Private Sub ValidateConnection(ByVal ConnectionErrors As ADODB.Errors)
If ConnectionErrors.Count > 0 Then
If Not this.HasADOError Then PopulateADOErrorObject ConnectionErrors
Dim ADOError As ADODB.Error
Set ADOError = GetError(ConnectionErrors, ConnectionErrors.Count - 1) 'Note: 0 based collection
Err.Raise ADOError.Number, ADOError.Source, ADOError.Description, ADOError.HelpFile, ADOError.HelpContext
End If
End Sub
</code></pre>
<p><strong>Bi-Directional Parameters:</strong></p>
<p>Previously, I was only considering the use of Input Parameters for a given command, because there is no way to know what Direction a parameter should be mapped. However, I was able to come up with something close to this, by implicitly calling the <code>Parameters.Refresh</code> method of the <code>Parameters</code> collection object. Note that Parameters STILL have to be passed in the correct order or ADO will populate the <code>Connection.Errors</code> collection. It is also worth mentioning that this has a very small (virtually unnoticeable) performance hit, but even still, I chose to leave it up to the client to choose which method that they want use. I did so by adding a boolean property called <code>DeriveParameterDirection</code>, which If set to true, then the <code>DerivedDirectionParameters</code> implementation of the <code>IADODBParametersWrapper</code> will be used, in the private <code>CreateCommand</code> procedure. If false, then the <code>AssumeParameterDirection</code> of <code>IADODBParametersWrapper</code> will be used. </p>
<p>Also, If output parameters are used, you need a way to return them, so I use the following in <code>ADODBWrapper</code> to do so: </p>
<pre class="lang-vb prettyprint-override"><code>'note: this.OuputParameters is a read only property at the class level
Private Sub PopulateOutPutParameters(ByRef Parameters As ADODB.Parameters)
Dim Param As ADODB.Parameter
Set this.OuputParameters = New Collection
For Each Param In Parameters
Select Case Param.Direction
Case adParamInputOutput
this.OuputParameters.Add Param
Case adParamOutput
this.OuputParameters.Add Param
Case adParamReturnValue
this.OuputParameters.Add Param
End Select
Next
End Sub
</code></pre>
<p><strong>IADODBParametersWrapper (Interface):</strong></p>
<pre class="lang-vb prettyprint-override"><code>Option Explicit
Public Sub SetParameters(ByRef Command As ADODB.Command, ByRef ParameterValues As Variant)
End Sub
Private Sub Class_Initialize()
Err.Raise vbObjectError + 1024, TypeName(Me), "An Interface class must not be instantiated."
End Sub
</code></pre>
<p><strong>AssumedDirectionParameters (Class):</strong></p>
<pre class="lang-vb prettyprint-override"><code>Option Explicit
Implements IADODBParametersWrapper
Private Sub IADODBParametersWrapper_SetParameters(ByRef Command As ADODB.Command, ByRef ParameterValues As Variant)
Dim i As Long
Dim ParamVal As Variant
If UBound(ParameterValues) = -1 Then Exit Sub 'not allocated
For i = LBound(ParameterValues) To UBound(ParameterValues)
ParamVal = ParameterValues(i)
Command.Parameters.Append ToADOInputParameter(ParamVal)
Next i
End Sub
Private Function ToADOInputParameter(ByVal ParameterValue As Variant) As ADODB.Parameter
Dim ResultParameter As New ADODB.Parameter
With ResultParameter
Select Case VarType(ParameterValue)
Case vbInteger
.Type = adInteger
Case vbLong
.Type = adInteger
Case vbSingle
.Type = adSingle
.Precision = CalculatePrecision(ParameterValue)
.NumericScale = CalculateNumericScale(ParameterValue)
Case vbDouble
.Type = adDouble
.Precision = CalculatePrecision(ParameterValue)
.NumericScale = CalculateNumericScale(ParameterValue)
Case vbDate
.Type = adDate
Case vbCurrency
.Type = adCurrency
.Precision = CalculatePrecision(ParameterValue)
.NumericScale = CalculateNumericScale(ParameterValue)
Case vbString
.Type = adVarChar
.Size = Len(ParameterValue)
Case vbBoolean
.Type = adBoolean
End Select
.Direction = ADODB.ParameterDirectionEnum.adParamInput
.value = ParameterValue
End With
Set ToADOInputParameter = ResultParameter
End Function
Private Function CalculatePrecision(ByVal value As Variant) As Byte
CalculatePrecision = CByte(Len(Replace(CStr(value), ".", vbNullString)))
End Function
Private Function CalculateNumericScale(ByVal value As Variant) As Byte
CalculateNumericScale = CByte(Len(Split(CStr(value), ".")(1)))
End Function
</code></pre>
<p><strong>DerivedDirectionParameters (Class):</strong></p>
<pre class="lang-vb prettyprint-override"><code>Option Explicit
Implements IADODBParametersWrapper
Private Sub IADODBParametersWrapper_SetParameters(ByRef Command As ADODB.Command, ByRef ParameterValues As Variant)
Dim i As Long
Dim ParamVal As Variant
If UBound(ParameterValues) = -1 Then Exit Sub 'not allocated
With Command
If .Parameters.Count = 0 Then
Err.Raise vbObjectError + 1024, TypeName(Me), "This Provider does " & _
"not support parameter retrieval."
End If
Select Case .CommandType
Case adCmdStoredProc
If .Parameters.Count > 1 Then 'Debug.Print Cmnd.Parameters.Count prints 1 b/c it includes '@RETURN_VALUE'
'which is a default value
For i = LBound(ParameterValues) To UBound(ParameterValues)
ParamVal = ParameterValues(i)
'Explicitly set size to prevent error
'as per the Note at: https://docs.microsoft.com/en-us/sql/ado/reference/ado-api/refresh-method-ado?view=sql-server-2017
SetVariableLengthProperties .Parameters(i + 1), ParamVal
.Parameters(i + 1).Value = ParamVal '.Parameters(i + 1) b/c of @RETURN_VALUE
'mentioned above
Next i
End If
Case adCmdText
For i = LBound(ParameterValues) To UBound(ParameterValues)
ParamVal = ParameterValues(i)
'Explicitly set size to prevent error
SetVariableLengthProperties .Parameters(i), ParamVal
.Parameters(i).Value = ParamVal
Next i
End Select
End With
End Sub
Private Sub SetVariableLengthProperties(ByRef Parameter As ADODB.Parameter, ByRef ParameterValue As Variant)
With Parameter
Select Case VarType(ParameterValue)
Case vbSingle
.Precision = CalculatePrecision(ParameterValue)
.NumericScale = CalculateNumericScale(ParameterValue)
Case vbDouble
.Precision = CalculatePrecision(ParameterValue)
.NumericScale = CalculateNumericScale(ParameterValue)
Case vbCurrency
.Precision = CalculatePrecision(ParameterValue)
.NumericScale = CalculateNumericScale(ParameterValue)
Case vbString
.Size = Len(ParameterValue)
End Select
End With
End Sub
Private Function CalculatePrecision(ByVal value As Variant) As Byte
CalculatePrecision = CByte(Len(Replace(CStr(value), ".", vbNullString)))
End Function
Private Function CalculateNumericScale(ByVal value As Variant) As Byte
CalculateNumericScale = CByte(Len(Split(CStr(value), ".")(1)))
End Function
</code></pre>
<p><strong>ADODBWrapper (Class):</strong></p>
<pre class="lang-vb prettyprint-override"><code>Option Explicit
Private Type TADODBWrapper
DeriveParameterDirection As Boolean
CommandTimeout As Long
OuputParameters As Collection
ADOErrors As ADODB.Errors
HasADOError As Boolean
End Type
Private this As TADODBWrapper
Public Property Get DeriveParameterDirection() As Boolean
DeriveParameterDirection = this.DeriveParameterDirection
End Property
Public Property Let DeriveParameterDirection(ByVal value As Boolean)
this.DeriveParameterDirection = value
End Property
Public Property Get CommandTimeout() As Long
CommandTimeout = this.CommandTimeout
End Property
Public Property Let CommandTimeout(ByVal value As Long)
this.CommandTimeout = value
End Property
Public Property Get OuputParameters() As Collection
Set OuputParameters = this.OuputParameters
End Property
Public Property Get Errors() As ADODB.Errors
Set Errors = this.ADOErrors
End Property
Public Property Get HasADOError() As Boolean
HasADOError = this.HasADOError
End Property
Private Sub Class_Terminate()
With this
.CommandTimeout = Empty
.DeriveParameterDirection = Empty
Set .OuputParameters = Nothing
Set .ADOErrors = Nothing
.HasADOError = Empty
End With
End Sub
Public Function GetRecordSet(ByRef Connection As ADODB.Connection, _
ByVal CommandText As String, _
ByVal CommandType As ADODB.CommandTypeEnum, _
ByVal CursorType As ADODB.CursorTypeEnum, _
ByVal LockType As ADODB.LockTypeEnum, _
ParamArray ParameterValues() As Variant) As ADODB.Recordset
Dim Cmnd As ADODB.Command
ValidateConnection Connection.Errors
On Error GoTo CleanFail
Set Cmnd = CreateCommand(Connection, CommandText, CommandType, CVar(ParameterValues)) 'must convert paramarray to
'a variant in order to pass
'to another function
'Note: When used on a client-side Recordset object,
' the CursorType property can be set only to adOpenStatic.
Set GetRecordSet = New ADODB.Recordset
GetRecordSet.CursorType = CursorType
GetRecordSet.LockType = LockType
Set GetRecordSet = Cmnd.Execute(Options:=ExecuteOptionEnum.adAsyncFetch)
'if successful
If Not this.ADOErrors Is Nothing Then this.ADOErrors.Clear
CleanExit:
Set Cmnd = Nothing
Exit Function
CleanFail:
PopulateADOErrorObject Connection.Errors
Resume CleanExit
End Function
Public Function GetDisconnectedRecordSet(ByRef ConnectionString As String, _
ByVal CursorLocation As ADODB.CursorLocationEnum, _
ByVal CommandText As String, _
ByVal CommandType As ADODB.CommandTypeEnum, _
ParamArray ParameterValues() As Variant) As ADODB.Recordset
Dim Cmnd As ADODB.Command
Dim CurrentConnection As ADODB.Connection
On Error GoTo CleanFail
Set CurrentConnection = CreateConnection(ConnectionString, CursorLocation)
Set Cmnd = CreateCommand(CurrentConnection, CommandText, CommandType, CVar(ParameterValues)) 'must convert paramarray to
'a variant in order to pass
'to another function
Set GetDisconnectedRecordSet = New ADODB.Recordset
With GetDisconnectedRecordSet
.CursorType = adOpenStatic 'Must use this cursortype and this locktype to work with a disconnected recordset
.LockType = adLockBatchOptimistic
.Open Cmnd, , , , Options:=ExecuteOptionEnum.adAsyncFetch
'disconnect the recordset
Set .ActiveConnection = Nothing
End With
'if successful
If Not this.ADOErrors Is Nothing Then this.ADOErrors.Clear
CleanExit:
Set Cmnd = Nothing
If Not CurrentConnection Is Nothing Then: If (CurrentConnection.State And adStateOpen) = adStateOpen Then CurrentConnection.Close
Set CurrentConnection = Nothing
Exit Function
CleanFail:
PopulateADOErrorObject CurrentConnection.Errors
Resume CleanExit
End Function
Public Function QuickExecuteNonQuery(ByVal ConnectionString As String, _
ByVal CommandText As String, _
ByVal CommandType As ADODB.CommandTypeEnum, _
ByRef RecordsAffectedReturnVal As Long, _
ParamArray ParameterValues() As Variant) As Boolean
Dim Cmnd As ADODB.Command
Dim CurrentConnection As ADODB.Connection
On Error GoTo CleanFail
Set CurrentConnection = CreateConnection(ConnectionString, adUseServer)
Set Cmnd = CreateCommand(CurrentConnection, CommandText, CommandType, CVar(ParameterValues)) 'must convert paramarray to
'a variant in order to pass
'to another function
Cmnd.Execute RecordsAffected:=RecordsAffectedReturnVal, Options:=ExecuteOptionEnum.adExecuteNoRecords
QuickExecuteNonQuery = True
'if successful
If Not this.ADOErrors Is Nothing Then this.ADOErrors.Clear
CleanExit:
Set Cmnd = Nothing
If Not CurrentConnection Is Nothing Then: If (CurrentConnection.State And adStateOpen) = adStateOpen Then CurrentConnection.Close
Set CurrentConnection = Nothing
Exit Function
CleanFail:
PopulateADOErrorObject CurrentConnection.Errors
Resume CleanExit
End Function
Public Function ExecuteNonQuery(ByRef Connection As ADODB.Connection, _
ByVal CommandText As String, _
ByVal CommandType As ADODB.CommandTypeEnum, _
ByRef RecordsAffectedReturnVal As Long, _
ParamArray ParameterValues() As Variant) As Boolean
Dim Cmnd As ADODB.Command
ValidateConnection Connection.Errors
On Error GoTo CleanFail
Set Cmnd = CreateCommand(Connection, CommandText, CommandType, CVar(ParameterValues)) 'must convert paramarray to
'a variant in order to pass
'to another function
Cmnd.Execute RecordsAffected:=RecordsAffectedReturnVal, Options:=ExecuteOptionEnum.adExecuteNoRecords
ExecuteNonQuery = True
'if successful
If Not this.ADOErrors Is Nothing Then this.ADOErrors.Clear
CleanExit:
Set Cmnd = Nothing
Exit Function
CleanFail:
PopulateADOErrorObject Connection.Errors
Resume CleanExit
End Function
Public Function CreateConnection(ByRef ConnectionString As String, ByVal CursorLocation As ADODB.CursorLocationEnum) As ADODB.Connection
On Error GoTo CleanFail
Set CreateConnection = New ADODB.Connection
CreateConnection.CursorLocation = CursorLocation
CreateConnection.Open ConnectionString
CleanExit:
Exit Function
CleanFail:
PopulateADOErrorObject CreateConnection.Errors
Resume CleanExit
End Function
Private Function CreateCommand(ByRef Connection As ADODB.Connection, _
ByVal CommandText As String, _
ByVal CommandType As ADODB.CommandTypeEnum, _
ByRef ParameterValues As Variant) As ADODB.Command
Dim ParameterGenerator As IADODBParametersWrapper
Set CreateCommand = New ADODB.Command
With CreateCommand
.ActiveConnection = Connection
.CommandText = CommandText
.CommandTimeout = Me.CommandTimeout '0
End With
If Me.DeriveParameterDirection Then
Set ParameterGenerator = New DerivedDirectionParameters
CreateCommand.CommandType = CommandType 'When set before accessing the Parameters Collection,
'Parameters.Refresh is impilicitly called
ParameterGenerator.SetParameters CreateCommand, ParameterValues
PopulateOutPutParameters CreateCommand.Parameters
Else
Set ParameterGenerator = New AssumedDirectionParameters
ParameterGenerator.SetParameters CreateCommand, ParameterValues
CreateCommand.CommandType = CommandType
End If
End Function
Private Sub ValidateConnection(ByRef ConnectionErrors As ADODB.Errors)
If ConnectionErrors.Count > 0 Then
If Not this.HasADOError Then PopulateADOErrorObject ConnectionErrors
Dim ADOError As ADODB.Error
Set ADOError = GetError(ConnectionErrors, ConnectionErrors.Count - 1) 'Note: 0 based collection
Err.Raise ADOError.Number, ADOError.Source, ADOError.Description, ADOError.HelpFile, ADOError.HelpContext
End If
End Sub
Private Sub PopulateADOErrorObject(ByVal ConnectionErrors As ADODB.Errors)
If ConnectionErrors.Count = 0 Then Exit Sub
this.HasADOError = True
Set this.ADOErrors = ConnectionErrors
End Sub
Public Function ErrorsToString() As String
Dim ADOError As ADODB.Error
Dim i As Long
Dim ErrorMsg As String
For Each ADOError In this.ADOErrors
i = i + 1
With ADOError
ErrorMsg = ErrorMsg & "Count: " & vbTab & i & vbNewLine
ErrorMsg = ErrorMsg & "ADO Error Number: " & vbTab & CStr(.Number) & vbNewLine
ErrorMsg = ErrorMsg & "Description: " & vbTab & .Description & vbNewLine
ErrorMsg = ErrorMsg & "Source: " & vbTab & .Source & vbNewLine
ErrorMsg = ErrorMsg & "NativeError: " & vbTab & CStr(.NativeError) & vbNewLine
ErrorMsg = ErrorMsg & "HelpFile: " & vbTab & .HelpFile & vbNewLine
ErrorMsg = ErrorMsg & "HelpContext: " & vbTab & CStr(.HelpContext) & vbNewLine
ErrorMsg = ErrorMsg & "SQLState: " & vbTab & .SqlState & vbNewLine
End With
Next
ErrorsToString = ErrorMsg & vbNewLine
End Function
Public Function GetError(ByRef ADOErrors As ADODB.Errors, ByVal Index As Variant) As ADODB.Error
Set GetError = ADOErrors.item(Index)
End Function
Private Sub PopulateOutPutParameters(ByRef Parameters As ADODB.Parameters)
Dim Param As ADODB.Parameter
Set this.OuputParameters = New Collection
For Each Param In Parameters
Select Case Param.Direction
Case adParamInputOutput
this.OuputParameters.Add Param
Case adParamOutput
this.OuputParameters.Add Param
Case adParamReturnValue
this.OuputParameters.Add Param
End Select
Next
End Sub
</code></pre>
|
[] |
[
{
"body": "<p><strong>CommandTimeout:</strong></p>\n\n<p>Allowing the client to specify a given command's execution time threshold by making it a read/write property is good improvement from the first post of this class, that you did not mention in your <em>\"outline of what I have done and why\"</em>, so I am mentioning it here. </p>\n\n\n\n<pre class=\"lang-vb prettyprint-override\"><code>Public Property Get CommandTimeout() As Long\n CommandTimeout = this.CommandTimeout\nEnd Property\n\nPublic Property Let CommandTimeout(ByVal value As Long)\n this.CommandTimeout = value\nEnd Property\n</code></pre>\n\n<p><strong>Managing The Connection Object:</strong></p>\n\n<p>Since I am on the topic of things you forgot to mention, In both of <code>GetDisconnectedRecordset</code> and <code>QuickExecuteNonQuery</code>, you wrote this: </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>If Not CurrentConnection Is Nothing Then: If (CurrentConnection.State And adStateOpen) = adStateOpen Then CurrentConnection.Close\nSet CurrentConnection = Nothing\n</code></pre>\n\n<p>Bit-wise comparisons, specifically with respect to the <code>Connection</code> object's state, is good, but you could probably make the code look more friendly: </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>If Not CurrentConnection Is Nothing Then\n If (CurrentConnection.State And adStateOpen) = adStateOpen Then\n CurrentConnection.Close\n End If\nEnd If\nSet CurrentConnection = Nothing \n</code></pre>\n\n<p><strong>OutPut Parameters:</strong></p>\n\n<blockquote>\n <p>\"Also, If output parameters are used, you need a way to return them, so I use the following in ADODBWrapper to do so\"</p>\n</blockquote>\n\n<p>You are indeed able to return parameters, from your <code>OuputParameters</code> property, in the sense that you are returning the ACTual <code>Parameter</code> object, but why do that if you only want to access a parameter's value? As you have it now, one would have to write code like the following, just to get a value: </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub GetOutputParams()\n\n Dim SQLDataAdapter As ADODBWrapper\n Dim rsDisConnected As ADODB.Recordset\n Dim InputParam As String\n Dim OutPutParam As Integer\n\n Set SQLDataAdapter = New ADODBWrapper\n\n SQLDataAdapter.DeriveParameterDirection = True\n\n On Error GoTo CleanFail\n InputParam = \"Val1,Val2,Val3\"\n Set rsDisConnected = SQLDataAdapter.GetDisconnectedRecordSet(CONN_STRING, adUseClient, _\n \"SCHEMA.SOME_STORED_PROC_NAME\", _\n adCmdStoredProc, InputParam, OutPutParam)\n\n\n Sheet1.Range(\"A2\").CopyFromRecordset rsDisConnected\n\n '***************************************************\n 'set the parameter object only to return the value? \n Dim Param As ADODB.Parameter \n If SQLDataAdapter.OuputParameters.Count > 0 Then \n Set Param = SQLDataAdapter.OuputParameters(1)\n Debug.Print Param.Value\n End If\n '***************************************************\n\nCleanExit:\n Exit Sub\n\nCleanFail:\n If SQLDataAdapter.HasADOError Then Debug.Print SQLDataAdapter.ErrorsToString()\n Resume CleanExit\n\nEnd Sub\n</code></pre>\n\n<p>If you change the private <code>PopulateOutPutParameters</code> procedure In <code>ADODBWrapper</code> to add only the <code>Parameter.Value</code> to <code>OutPutParameters</code> collection like this: </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub PopulateOutPutParameters(ByRef Parameters As ADODB.Parameters)\n\n Dim Param As ADODB.Parameter\n\n Set this.OuputParameters = New Collection\n\n For Each Param In Parameters\n Select Case Param.Direction\n Case adParamInputOutput\n\n this.OuputParameters.Add Param.value\n\n Case adParamOutput\n\n this.OuputParameters.Add Param.value\n\n Case adParamReturnValue\n\n this.OuputParameters.Add Param.value\n\n End Select\n Next\n\nEnd Sub\n</code></pre>\n\n<p>Then you could do this in the client code: </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>If SQLDataAdapter.OuputParameters.Count > 0 Then\n Debug.Print SQLDataAdapter.OuputParameters(1)\nEnd If\n</code></pre>\n\n<p>Saying all of that, it would still be nice to have a way to map parameters without the client having to know their ordinal position as determined by the way a stored procedure was written, but this is much easier said than done. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T12:44:35.633",
"Id": "229374",
"ParentId": "229281",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229374",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T23:43:59.177",
"Id": "229281",
"Score": "6",
"Tags": [
"sql",
"vba",
"vb6",
"adodb"
],
"Title": "ADODB Wrapper Class (Revisited)"
}
|
229281
|
<p>I'm rewriting a full color Mandelbrot Set explorer in Python using tkinter. For it, I need to be able to convert a <code>Tuple[int, int, int]</code> into a hex string in the form <code>#123456</code>. Here are example uses of the two variants that I came up with:</p>
<pre><code>>>>rgb_to_hex(123, 45, 6)
'#7b2d06'
>>>rgb_to_hex(99, 88, 77)
'#63584d'
>>>tup_rgb_to_hex((123, 45, 6))
'#7b2d06'
>>>tup_rgb_to_hex((99, 88, 77))
'#63584d'
>>>rgb_to_hex(*(123, 45, 6))
'#7b2d06'
>>>rgb_to_hex(*(99, 88, 77))
'#63584d'
</code></pre>
<p>The functions I've come up with are very simple, but intolerably slow. This code is a rare case where performance is a real concern. It will need to be called once per pixel, and my goal is to support the creation of images up to 50,000x30,000 pixels (1500000000 in total). 100 million executions take ~300 seconds: </p>
<pre><code>>>>timeit.timeit(lambda: rgb_to_hex(255, 254, 253), number=int(1e8))
304.3993674000001
</code></pre>
<p>Which, unless my math is fubared, means this function <em>alone</em> will take <em>75 minutes</em> in total for my extreme case.</p>
<p>I wrote two versions. The latter was to reduce redundancy (and since I'll be handling tuples anyways), but it was even slower, so I ended up just using unpacking on the first version:</p>
<pre><code># Takes a tuple instead
>>>timeit.timeit(lambda: tup_rgb_to_hex((255, 254, 253)), number=int(1e8))
342.8174099
# Unpacks arguments
>>>timeit.timeit(lambda: rgb_to_hex(*(255, 254, 253)), number=int(1e8))
308.64342439999973
</code></pre>
<p>The code:</p>
<pre><code>from typing import Tuple
def _channel_to_hex(color_val: int) -> str:
raw: str = hex(color_val)[2:]
return raw.zfill(2)
def rgb_to_hex(red: int, green: int, blue: int) -> str:
return "#" + _channel_to_hex(red) + _channel_to_hex(green) + _channel_to_hex(blue)
def tup_rgb_to_hex(rgb: Tuple[int, int, int]) -> str:
return "#" + "".join([_channel_to_hex(c) for c in rgb])
</code></pre>
<p>I'd prefer to be able to use the <code>tup_</code> variant for cleanliness, but there may not be a good way to automate the iteration with acceptable amounts of overhead.</p>
<p>Any performance-related tips (or anything else if you see something) are welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T01:32:59.627",
"Id": "445878",
"Score": "19",
"body": "`It will need to be called once per pixel` - this is suspicious. What code is accepting a hex string? High-performance graphics code should be dealing in RGB byte triples packed into an int32."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T01:38:50.980",
"Id": "445879",
"Score": "1",
"body": "Put another way: I think you need to approach this from another angle. Make a framebuffer using a lower-level technology and pull that into tkinter wholesale."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T02:00:14.550",
"Id": "445881",
"Score": "3",
"body": "@Reinderien Canvas pixel coloring seems to be done exclusively using hex strings in tkinter unfortunately. Unless I can have it accept a buffer of existing data. I'll look into that tomorrow. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T02:02:21.637",
"Id": "445882",
"Score": "3",
"body": "And I'm going to remove the `number-guessing-game` tag. I'm not sure why that was added."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T08:25:24.480",
"Id": "445906",
"Score": "1",
"body": "Where are you getting those tuples? Perhaps there's an easy way to stay out of python for longer and therefore optimize better. Just calling any function 1.5e9 times is going to be slower than you want. For example, if you get them from a long continues array of some kind, numpy makes this trivial, especially since you can probably just shove numpy's own byte buffer into tkinter. I've had an issue like this myself once for displaying an image, and the solution was \"let numpy handle it.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T13:49:01.080",
"Id": "445945",
"Score": "0",
"body": "@Gloweye They're produced by \"color scheme\" functions. The functions take the (real, imaginary) coordinates of the pixel and how many iterations it took that pixel to fail, and return a three-tuple. They could return anything to indicate the color (that code is completely in my control), I just thought a three-tuple would by simplest. In theory, I could expect the functions to directly return a hex string, but that's just kicking the can down the road a bit since they need to be able to generate the string somehow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T13:49:33.720",
"Id": "445946",
"Score": "0",
"body": "And unfortunately I got called in to work for the next couple days. I'll need to wait until the weekend now to llaybaround with this more. Thanks for the thoughts guys."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T23:41:13.210",
"Id": "446045",
"Score": "0",
"body": "@Carcigenicate I doubt the performance of your application should be improved by twiddling with the performance of your RGB to Hex conversion functions. You should be working with `array`s from the array module. You should be loading the pixel values in directly into your program, \"RGB\" and \"Hex\" are human representations of a numerical value. You want to work directly with the numerical value for performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T00:27:31.590",
"Id": "446049",
"Score": "0",
"body": "@noɥʇʎԀʎzɐɹƆ I guess my misunderstanding was that it seemed to me that the only way to color a canvas pixel by pixel was to supply a hex string in a drawing call like `canvas.create_oval(x, y, x, y, fill=color)`. I didn't offhand see any way to load the values in bulk."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T00:30:51.607",
"Id": "446050",
"Score": "1",
"body": "I can see now looking at the docs though, you can load images straight to the canvas. I'll probably just draw it onto an image in memory then load that. I think that's what a couple people here are suggesting using PIL."
}
] |
[
{
"body": "<p>You seem to be jumping through some unnecessary hoops. Just format a string directly:</p>\n\n<pre><code>from timeit import timeit\n\n\ndef _channel_to_hex(color_val: int) -> str:\n raw: str = hex(color_val)[2:]\n return raw.zfill(2)\n\n\ndef rgb_to_hex(red: int, green: int, blue: int) -> str:\n return \"#\" + _channel_to_hex(red) + _channel_to_hex(green) + _channel_to_hex(blue)\n\n\ndef direct_format(r, g, b):\n return f'#{r:02x}{g:02x}{b:02x}'\n\n\ndef one_word(r, g, b):\n rgb = r<<16 | g<<8 | b\n return f'#{rgb:06x}'\n\n\n\ndef main():\n N = 100000\n methods = (\n rgb_to_hex,\n direct_format,\n one_word,\n )\n for method in methods:\n hex = method(1, 2, 255)\n assert '#0102ff' == hex\n\n def run():\n return method(1, 2, 255)\n\n dur = timeit(run, number=N)\n print(f'{method.__name__:15} {1e6*dur/N:.2f} us')\n\n\nmain()\n</code></pre>\n\n<p>produces:</p>\n\n<pre><code>rgb_to_hex 6.75 us\ndirect_format 3.14 us\none_word 2.74 us\n</code></pre>\n\n<p>That said, the faster thing to do is almost certainly to generate an image in-memory with a different framework and then send it to tkinter.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T15:38:33.050",
"Id": "446585",
"Score": "1",
"body": "Good suggestions, but I ended up just learning how to use Pillow (basically your suggestion at the bottom). You can import Pillow image objects directly into tkinter. It ended up being much cleaner. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T02:14:04.953",
"Id": "229285",
"ParentId": "229282",
"Score": "20"
}
},
{
"body": "<p>Another approach to generate the hex string is to directly reuse methods of format strings rather than writing your own function.</p>\n\n<pre><code>rgb_to_hex = \"#{:02x}{:02x}{:02x}\".format # rgb_to_hex(r, g, b) expands to \"...\".format(r, g, b)\n\nrgb_tup_to_hex = \"#%02x%02x%02x\".__mod__ # rgb_tup_to_hex((r, g, b)) expands to \"...\" % (r, g, b)\n</code></pre>\n\n<p>These are faster (<code>rgb_to_hex_orig</code> is renamed from the <code>rgb_to_hex</code> function in the question):</p>\n\n<pre><code>rgb_tup = (0x20, 0xFB, 0xC2)\n\n%timeit rgb_to_hex_orig(*rgb_tup)\n%timeit direct_format(*rgb_tup)\n%timeit one_word(*rgb_tup)\n%timeit rgb_to_hex(*rgb_tup)\n%timeit rgb_tup_to_hex(rgb_tup)\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>1.57 µs ± 5.14 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n1.18 µs ± 5.34 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n704 ns ± 3.35 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n672 ns ± 4.54 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n502 ns ± 7.23 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n</code></pre>\n\n<p><code>rgb_tup_to_hex</code> is the fastest partially due to it takes a tuple directly as its argument and avoids the small overhead of unpacking arguments.</p>\n\n<p>However, I doubt these improvements would help solve your problem given its magnitude.</p>\n\n<p>Using the <a href=\"https://pillow.readthedocs.io\" rel=\"noreferrer\">Pillow / PIL</a> library, pixel values can be <a href=\"https://en.wikibooks.org/wiki/Python_Imaging_Library/Editing_Pixels\" rel=\"noreferrer\">directly set based on indices using tuples</a>. Therefore converting tuples to strings are not really necessary. <a href=\"https://www.c-sharpcorner.com/blogs/basics-for-displaying-image-in-tkinter-python\" rel=\"noreferrer\">Here</a> are examples showing basics of displaying <code>PIL</code> images in <code>tkinter</code>. This is likely still slow if the changes are done pixel by pixel. For extensive changes, the <a href=\"https://pillow.readthedocs.io/en/4.0.x/reference/ImageDraw.html\" rel=\"noreferrer\">ImageDraw</a> module or <a href=\"https://pillow.readthedocs.io/en/4.0.x/reference/Image.html#PIL.Image.Image.putdata\" rel=\"noreferrer\">Image.putdata</a> could be used.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T12:11:25.913",
"Id": "229307",
"ParentId": "229282",
"Score": "11"
}
},
{
"body": "<h1>memoization</h1>\n\n<p>The <code>_channel_to_hex</code> is called 3 times per pixel. It only takes 256 different inputs, so a logical first step would be to memoize the results. This can be done with either <code>functools.lru_cache</code></p>\n\n<pre><code>from functools import lru_cache\n@lru_cache(None)\ndef _channel_to_hex(color_val: int) -> str:\n raw: str = hex(color_val)[2:]\n return raw.zfill(2)\n</code></pre>\n\n<p>This already reduces the time needed with about a 3rd</p>\n\n<p>An alternative is using a dict:</p>\n\n<pre><code>color_hexes ={\n color_val: hex(color_val)[2:].zfill(2)\n for color_val in range(256)\n}\n\ndef rgb_to_hex_dict(red: int, green: int, blue: int) -> str:\n return \"#\" + color_hexes[red] + color_hexes[green] + color_hexes[blue]\n</code></pre>\n\n<p>If the color-tuples are also limited (256**3 in worst case), so these can also be memoized</p>\n\n<pre><code>color_tuple_hexes = {\n rgb_to_hex_dict(*color_tuple)\n for color_tuple in itertools.product(range(256), repeat=3)\n}\n</code></pre>\n\n<p>This takes about 15 seconds on my machine, but only needs to be done once.</p>\n\n<p>If only a limited set of tuples is used, you can also use <code>lru_cache</code></p>\n\n<pre><code>@lru_cache(None)\ndef rgb_to_hex_dict(red: int, green: int, blue: int) -> str:\n return \"#\" + color_hexes[red] + color_hexes[green] + color_hexes[blue]\n</code></pre>\n\n<h1>numpy</h1>\n\n<p>if you have your data in a 3-dimensional numpy array, for example:</p>\n\n<pre><code>color_data = np.random.randint(256, size=(10,10,3))\n</code></pre>\n\n<p>You could do something like this:</p>\n\n<pre><code>coeffs = np.array([256**i for i in range(3)])\nnp_hex = (color_data * coeffs[np.newaxis, np.newaxis, :]).sum(axis=2)\nnp.vectorize(lambda x: \"#\" + hex(x)[2:].zfill(6))(np_hex)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T12:57:12.090",
"Id": "229311",
"ParentId": "229282",
"Score": "7"
}
},
{
"body": "<h1>Numpy is your best friend.</h1>\n\n<p>Given your comment:</p>\n\n<blockquote>\n <p>The tuples are produced by \"color scheme\" functions. The functions take the (real, imaginary) coordinates of the pixel and how many iterations it took that pixel to fail, and return a three-tuple. They could return anything to indicate the color (that code is completely in my control), I just thought a three-tuple would by simplest. In theory, I could expect the functions to directly return a hex string, but that's just kicking the can down the road a bit since they need to be able to generate the string somehow.</p>\n</blockquote>\n\n<p>Create a <a href=\"https://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html\" rel=\"nofollow noreferrer\">numpy</a> array for the image you're going to create, then just assign your values into the array directly. Something like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\n\nimage = np.empty(shape=(final_image.ysize, final_image.xsize, 3), dtype=np.uint8)\n\n# And instead of calling a function, assign to the array simply like:\nimage[x_coor, y_coor] = color_tuple\n\n# Or if you really need a function:\nimage.__setitem__((x_coor, y_coor), color_tuple) # I haven't tested this with numpy, but something like it should work.\n</code></pre>\n\n<p>You do need to make sure that your arrays are in the same shape as tkinter expects it's images, though. And if you can make another shortcut to put the data into the array sooner, take it.</p>\n\n<p>If you're doing an action this often, then you need to cut out function calls and such as often as you can. If possible, make the slice assignments bigger to set area's at the same time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T14:31:18.573",
"Id": "445953",
"Score": "0",
"body": "`np.ndarray(...)` is rarely used directly. From [doc](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html): *Arrays should be constructed using `array`, `zeros` or `empty`*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T14:32:36.173",
"Id": "445954",
"Score": "0",
"body": "Yes, you'll get a buffer filled with bogus data. But if you fill it yourself anyway, then it doesn't really matter what you use. I just grabbed the first thing that came to mind. Do you think it's bad practice if you fill your array entirely anyway ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T14:41:30.403",
"Id": "445955",
"Score": "0",
"body": "In this case I do not think there is much difference in terms of the functionality or performance. As the doc suggests, `np.ndarray` is a low-level method and it is recommended to use those high-level APIs instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T15:04:28.113",
"Id": "445959",
"Score": "0",
"body": "[`np.empty(...)`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html) is good candidate to express what you are doing in case you want to follow @Gloweye's comment and get rid of `np.ndarray(...)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T01:32:46.917",
"Id": "446052",
"Score": "0",
"body": "I think you need parentheses around `x_coor, y_coor` to make it a tuple."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T05:04:59.803",
"Id": "446066",
"Score": "0",
"body": "Uhm... yeah, in case of the ```__setitem__``` you do. Not for the straight assignment, though. I'll fix the setitem one."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T14:15:24.707",
"Id": "229319",
"ParentId": "229282",
"Score": "7"
}
},
{
"body": "<h1>Python compilers for performance</h1>\n\n<h2>Nuitka</h2>\n\n<p><a href=\"https://nuitka.net\" rel=\"nofollow noreferrer\">Nuitka</a> compiles any and all Python code into faster architecture-specific C++ code. Nuitka's generated code is faster.</p>\n\n<h2>Cython</h2>\n\n<p>Cython can compiles any and all Python code into platform-indepndent C code. However, where it really shines is because you can annotate your Cython functions with C types and get a performance boost out of that.</p>\n\n<h2>PyPy</h2>\n\n<p>PyPy is a JIT that compiles pure Python code. Sometimes it can produce good code, but it has a slow startup time. Although PyPy probably won't give you C-like or FORTRAN-like speeds, it can sometimes double or triple the execution speed of performance-critical sections.</p>\n\n<p>However, PyPy is low on developers, and as such, it does not yet support Python versions 3.7 or 3.8. Most libraries are still written with 3.6 compatibility.</p>\n\n<h2>Numba</h2>\n\n<p>Numba compiles a small subset of Python. It can achieve C-like or FORTRAN-like speeds with this subset-- when tuned properly, it can automatically parallelize and automatically use the GPU. However, you won't really be writing your code in Python, but in Numba.</p>\n\n<h1>Alternatives</h1>\n\n<p>You can write performance-critical code in another programming language. \nOne to consider would be D, a modern programming language with excellent C compatibility.</p>\n\n<p>Python integrates easily with languages C. In fact, you can load dynamic libraries written in C* into Python with no glue code.</p>\n\n<p>*D should be able to do this with <code>extern(C):</code> and <code>-betterC</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T23:28:52.233",
"Id": "229350",
"ParentId": "229282",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229285",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T00:16:57.387",
"Id": "229282",
"Score": "15",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Performance for simple code that converts a RGB tuple to hex string"
}
|
229282
|
<p>I'm a beginner learning ROS. I'm developing an android application that will control my robot and that includes getting the list of waypoints to display it to my spinner. How do you get the list of waypoints to my topic /waypoints assuming that there is a map?</p>
<p>I've already done the code for subscribing to the topic /waypoints and serializing its msg type</p>
<p>This is my code for serializing the msg-type of the topic /waypoints:</p>
<pre><code>public class WaypointList {
@SerializedName("header")
@Expose
public Header header;
@SerializedName("pose")
@Expose
public Pose pose;
@SerializedName("name")
@Expose
public String name;
@SerializedName("secs")
@Expose
public int secs;
@SerializedName("nsecs")
@Expose
public int nsecs;
@SerializedName("position")
@Expose
public Position position;
@SerializedName("orientation")
@Expose
public Orientation orientation;
@SerializedName("y")
@Expose
public float y;
@SerializedName("x")
@Expose
public float x;
@SerializedName("z")
@Expose
public float z;
@SerializedName("w")
@Expose
public float w;
@SerializedName("stamp")
@Expose
public Stamp stamp;
@SerializedName("frame_id")
@Expose
public String frameId;
@SerializedName("seq")
@Expose
public int seq;
@SerializedName("waypoints")
@Expose
public List<WaypointList> waypoints = null;
/**
* No args constructor for use in serialization
*
*/
public WaypointList() {
}
/**
*
* @param waypoints
*/
public WaypointList(List<WaypointList> waypoints, Stamp stamp, String frameId, int seq, float y, float x, float z, float w, Position position, Orientation orientation, int secs, int nsecs, Header header, Pose pose, String name) {
super();
this.header = header;
this.pose = pose;
this.name = name;
this.secs = secs;
this.nsecs = nsecs;
this.position = position;
this.orientation = orientation;
this.y = y;
this.x = x;
this.z = z;
this.w = w;
this.stamp = stamp;
this.frameId = frameId;
this.seq = seq;
this.waypoints = waypoints;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T04:50:45.077",
"Id": "445892",
"Score": "2",
"body": "It's not exactly clear what you're looking for and likely that this is in the wrong subsection of stackexchange. At the moment you have a class which contains a list of your class and nothing more. With nothing else to actually review in your code, I would recommend `public class WaypointList extends List`. Improvements can be what exactly you want your robot to do with the waypoints -- for instance nearest neighbor (and if that's the case, this is definitely in the wrong location)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T05:30:58.467",
"Id": "445893",
"Score": "1",
"body": "@DavidFisher apologies. I've edited my codes regarding my question. basically i want my robot to go from point a to point b from the listed waypoints in my topic (/waypoints). i needed a variable that will hold all the data to be able to display it to my spinner."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T02:33:55.500",
"Id": "229286",
"Score": "3",
"Tags": [
"java",
"beginner",
"android",
"serialization"
],
"Title": "Getting a list of waypoints assuming that there is a map"
}
|
229286
|
<p>I have written a python script that has tallies representing digits 1-9 (0 is just ":" ) Unlike true Unary languages that are in the form <strong>1^k</strong>. I represent values for <strong>n</strong> as per their <em>decimal digits</em>. The integer <em>121</em> is <strong>1_11_1</strong> Overall every <strong>k</strong> digit out of <strong>n</strong> <em>"integer"</em> is in Tally notation, and the amount of tallies is the sum of all the digits in a given <strong>n</strong> "integer" such as <strong>121 = 4, 1_11_1 = 4</strong>.</p>
<p>Its called a <a href="https://en.wikipedia.org/wiki/Many-one_reduction" rel="nofollow noreferrer">many-one reduction</a>. If you can transform Instance A(9,33,4) into Instance B(1111_1111 1, 111----111, 1111) in poly-time, then its NP-complete</p>
<p>Transformation rules is to just to enter each integer <strong>sequentially</strong> when asked in the while loop. Also, when your integer is a negative you do not give a "-" symbol for input. It will ask for input if its a negative integer.</p>
<pre><code>Input
(9,33,4) "9, and then 33 and then 4. One at a time for each input."
Output
'111_1111 1' = 9
111
33>>
111
11 11 =4
</code></pre>
<p><strong>Algorithm for the Reduction</strong></p>
<pre><code># This algorithm is very simple and inconsequential.
# It converts integers into a unary like language
# in poly time. All tallies are represented vertically.
print('If your integer is a negative, the script will ask.')
print("DO NOT GIVE -X integers for input!!!")
print('Script will output multiple - symbols for a negative integer transformation')
while 0 == 0:
ask = input('Enter an integer from a subset-sum instance sequentially.')
askStr = str(ask)
res = list(map(int, str(askStr)))
x = (res)
asktwo = input('Is your integer a negative integer? y or n: ')
if asktwo == str("y"):
twinkle = str('-')
else:
twinkle = str(" ")
for n in x:
if n == 0:
tallyone = ":"
print(twinkle, tallyone)
if n == 1:
print(twinkle, "1")
if n == 2:
print(twinkle, "11")
if n == 3:
print(twinkle, "111")
if n == 4:
print(twinkle, "11 11")
if n == 5:
print(twinkle, "111 11")
if n == 6:
print(twinkle, "111 111")
if n == 7:
print(twinkle, "111_111 1")
if n == 8:
print(twinkle, "1111 1111")
if n == 9:
print(twinkle, "1111_1111 1")
</code></pre>
<h2> Question</h2>
<p>In what way, is this code sloppy? Am I using while loops and variable names in an ugly way? Is my tallies in the print statements hard to read? What is the ugliest parts of my code and how would I improve them?</p>
<p><em>The code works. But, I don't know enough about python so what mistakes are you seeing in my code?</em></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T04:50:42.263",
"Id": "445891",
"Score": "7",
"body": "I must admit that I don't yet see the logic of the transformation. As an example, why is 5 transformed to \"111 11\" and not \"11111\", \"1111 1\", or \"111_11\"? And how is this related to a “subset sum instance”?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T13:57:28.613",
"Id": "445947",
"Score": "0",
"body": "@MartinR At the very least, the code does nothing like the 121 = 1_11_1 example"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T14:06:46.300",
"Id": "445948",
"Score": "0",
"body": "Could you try explaining a little bit more what the code is supposed to do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T21:53:56.680",
"Id": "446034",
"Score": "0",
"body": "@ Martin R Its called a many one reduction. If you can transform Instance A(9,33,4) into Instance B(1111_1111 1, 111----111, 1111) in poly-time. Then its NP-complete https://en.wikipedia.org/wiki/Many-one_reduction"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T05:43:50.820",
"Id": "446069",
"Score": "2",
"body": "@TravisWells: It may be my lacking knowledge of computability theory, but it still isn't clear to me. What exactly are the problems A and B in your reduction? How is this related to a subset-sum? And what exactly are the transformation rules?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T17:02:03.673",
"Id": "446167",
"Score": "0",
"body": "Problem A- Given a random subset sum instance of (9, 33, 4). Is there a subset sum of 37? Yes. Problem B- (1111_1111 1, 111----111, 1111). Is there a subset-sum of 37? Yes. The transformation rules require it to be polynomial time. Since, all tallies are fixed constants it will always take a fixed amount of time for individuals digits. For integers this grows \"linearly.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T21:07:24.183",
"Id": "446208",
"Score": "0",
"body": "Would be better if you can provide some input and output samples as you expect / actual"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T04:12:04.670",
"Id": "446239",
"Score": "0",
"body": "@bhathiya-perera I took your suggestion so take a look and tell me what you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T13:29:26.750",
"Id": "446328",
"Score": "0",
"body": "@TravisWells: All this is still very unclear to me. You say that “The integer 121 is 1_11_1” but your code does not print “1_11_1” when I enter the input number 121. Then you give an input/output example, but your code does not accept (9,33,4) as input, nor does it produce the example output. – It would *really* help if you tell us the exact transformation rules."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T15:51:18.637",
"Id": "446352",
"Score": "0",
"body": "@MartinR Enter an integer from a subset-sum instance **sequentially**. (not 9, 33, 4) at once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T15:52:51.940",
"Id": "446353",
"Score": "0",
"body": "@TravisWells: (Repeating myself:) Why is 5 transformed to \"111 11\" and not \"11111\", \"1111 1\", or \"111_11\"? What are the transformation rules?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T15:54:38.023",
"Id": "446354",
"Score": "0",
"body": "@MartinR Its easier to read 3 and 2 tallies that equals 5. It never bothered me. Except \"11111\". That's harder to read than just 111 11 or 111_11."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T15:56:23.643",
"Id": "446355",
"Score": "0",
"body": "@MartinR Transformation rules is to just to enter each integer **sequentially** when asked in the while loop. Also, when your integer is a negative you do not give a \"-\" symbol for input. The script will ask."
}
] |
[
{
"body": "<h2>Pythonic. Zen of Python. Idioms of Python.</h2>\n\n<p>These are phrases that will come up in python code. Basically they refer to the readability.</p>\n\n<p>Other programmers have to be able to read the code you write. Here are a few things that can be done to improve your knowledge.</p>\n\n<ul>\n<li>In the console, <code>help()</code> can be used in conjunction of other methods to get the docstring and information on how things work in python.</li>\n<li><code>type()</code> will show the data type you are currently working with.</li>\n<li><code>input()</code> returns a string.</li>\n<li><code>int(str, base)</code> returns an integer with the base of the given value <code>(2 <= base <= 36)</code></li>\n<li><code>enumerate(tuple)</code> allows for indices, is fast (because it doesn't need to make a new list).</li>\n<li><code>while 0==0:</code> is ugly. <code>while True:</code> is <em>infinitely</em> more beautiful.</li>\n</ul>\n\n<pre><code>print('user instructions')\n\nresponse = input('Pick an integer value less than infinity:\\n')\nmapped_response = map(int, response)\nresponse_length = len(response) - 1 # eewww!\nresult = ''\n\nfor index, value in enumerate(mapped_response):\n result = f\"{result}\\\n {':' if not value else ''.join('1' for _ in range(value))}\\\n {'_' if index < response_length else ''}\"\n\nprint(result)\n</code></pre>\n\n<h2>input</h2>\n\n<p><code>543210</code></p>\n\n<h2>output</h2>\n\n<p><code>11111_1111_111_11_1_:</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T07:38:07.257",
"Id": "445896",
"Score": "1",
"body": "The points you make in this answer are all valid, but they should be targeted towards a beginner. A beginner doesn't know what you mean with \"input returns a string\" and what that means for the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T07:41:03.400",
"Id": "445897",
"Score": "2",
"body": "Unless I am mistaken, your code produces not the same output as the original code from the question, e.g. \"11111\" for 5 instead of \"111 11\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T07:45:57.103",
"Id": "445898",
"Score": "2",
"body": "*\"Pythonic. Zen of Python. Idioms of Python.\"* likely don't mean anything to a beginner (Roland Illig already pointed in that direction), not even I \"get\" anything from it (and I consider myself at least at a reasonable Python skill level)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T07:47:57.057",
"Id": "445900",
"Score": "0",
"body": "@MartinR Formatting for individual values were not clear, and you even tried for clarification well before I tackled responding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-16T03:34:43.590",
"Id": "482207",
"Score": "0",
"body": "Awesome answer!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T07:07:47.500",
"Id": "229292",
"ParentId": "229287",
"Score": "4"
}
},
{
"body": "<p>This is a very interesting task. Good work on doing it. Here are some criticism. </p>\n\n<hr>\n\n<blockquote>\n<pre><code>print('If your integer is a negative, the script will ask.')\nprint(\"DO NOT GIVE -X integers for input!!!\")\nprint('Script will output multiple - symbols for a negative integer transformation')\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Do not use both double quote\n(<code>\"\"</code>) and single quote (<code>''</code>) strings. Pick one. I personally prefer <code>\"\"</code>.</li>\n</ul>\n\n<blockquote>\n<pre><code>while 0 == 0:\n ask = input('Enter an integer from a subset-sum instance sequentially.')\n</code></pre>\n</blockquote>\n\n<ul>\n<li>It's considered a best practice to indent using 4 spaces instead of 2.</li>\n<li>Also it would be better to move actual transform functionality to a new function.</li>\n<li>Also it's better to use <code>while True</code> instead of <code>while 0 == 0</code> to indicate a endless loop.\n\n<ul>\n<li><strong>Reason:</strong> This is more readable. </li>\n</ul></li>\n</ul>\n\n<blockquote>\n<pre><code> askStr = str(ask)\n res = list(map(int, str(askStr))\n</code></pre>\n</blockquote>\n\n<ul>\n<li>You are converting <code>ask</code> twice to a string. This is redundant. </li>\n<li>Since <code>input()</code> returns a string you don't need to convert this at all.</li>\n<li>It is also a better to use python conventions for names. Ex: <code>ask_str</code> or <code>value</code></li>\n</ul>\n\n<blockquote>\n<pre><code> x = (res)\n</code></pre>\n</blockquote>\n\n<ul>\n<li>You don't need parenthesis here. </li>\n<li>There is also no need to assign to <code>x</code> you can directly use <code>res</code>.</li>\n</ul>\n\n<blockquote>\n<pre><code> if asktwo == str(\"y\"):\n twinkle = str('-')\n else:\n twinkle = str(\" \")\n</code></pre>\n</blockquote>\n\n<ul>\n<li>You don't need to convert a string literal to a string again.</li>\n<li>You can directly use <code>\"y\"</code> as a string.</li>\n<li><code>twinkle</code> is not a good name. Use something like <code>sign</code>. </li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T09:24:27.683",
"Id": "229299",
"ParentId": "229287",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "229299",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T02:35:17.453",
"Id": "229287",
"Score": "9",
"Tags": [
"python",
"beginner",
"integer"
],
"Title": "Converting integers into Unary Notation"
}
|
229287
|
<blockquote>
<p>Q: Write a method that transforms a list into an array (don't use
collections or already implemented methods in lists, make your own
method)</p>
</blockquote>
<p>I've come with this solution:</p>
<pre><code>public static Object[] toArray(List<Object> list) {
Object[] arr = new Object[list.size()];
for (int i = 0; i < list.size(); ++i) {
arr[i] = list.get(i);
}
return arr;
}
</code></pre>
<p>I've read this <a href="https://stackoverflow.com/questions/6522284/convert-a-generic-list-to-an-array">Convert a generic list to an array</a>, and seems like they overcomplicated the solution. Why they choose to use generics? Is there something wrong with my approach?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T08:12:44.113",
"Id": "445902",
"Score": "1",
"body": "Perhaps it has to do with _boxing_ and _variance_ that generics are used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T11:28:23.813",
"Id": "445924",
"Score": "2",
"body": "did you try to call the method with a `List<String>` arg?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:42:54.080",
"Id": "445991",
"Score": "0",
"body": "You would have to cast the result back to whatever type. This feels like a hack"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T19:37:47.963",
"Id": "446001",
"Score": "1",
"body": "See https://stackoverflow.com/questions/34939499/how-to-properly-return-generic-array-in-java-generic-method"
}
] |
[
{
"body": "<p>I think, as per your solution, in every case you'll get a list of objects not the list of actual class you need. If you want to use this array you have to cast the object to your desired class. To do that you have to check if you can cast the object to your desired class as the down casting can cause error if you don't use instanceOf. <br/>\nIn short you have to do all this by your self every time you want to use this method for any kind of list.<br/> On the other hand the generic code will always return you the array of your class not object. <br/> I think the generic code has 2 advantage over your code which are:</p>\n\n<ol>\n<li>No casting needed </li>\n<li>Can be used any where with any kind of list.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T20:34:22.553",
"Id": "229402",
"ParentId": "229293",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T07:18:50.013",
"Id": "229293",
"Score": "2",
"Tags": [
"java",
"array",
"reinventing-the-wheel",
"collections"
],
"Title": "transform list to array"
}
|
229293
|
<p>I have 2 functions, which are going to hide/ unhide the multiple languages plain text.</p>
<p>Security is not a major concern.</p>
<blockquote>
<p>The objectives are</p>
<ol>
<li>Just want to find a way to hide multiple languages plain text from ordinary user. Even he spends some effort to unhide it, that is
completely Ok.</li>
<li>Works well for all kind of String.</li>
</ol>
</blockquote>
<p><strong><em>I was wondering, do I miss out any possible edge cases?</em></strong></p>
<hr>
<h2>Functions to obfuscate and deobfuscate String</h2>
<pre><code>public static String obfuscate(String string) {
if (string == null) {
return null;
}
if (string.equals("")) {
return "";
}
byte[] input = string.getBytes(Charset.forName(UTF_8));
byte[] binary = Base64.encode(input, Base64.NO_WRAP);
String encoded = new String(binary, Charset.forName(UTF_8));
// Reverse the string
String reverse = new StringBuffer(encoded).reverse().toString();
return reverse;
}
public static String deobfuscate(String reverse) {
if (reverse == null) {
return null;
}
if (reverse.equals("")) {
return "";
}
// Reverse the string
String encoded = new StringBuffer(reverse).reverse().toString();
byte[] binary = encoded.getBytes(Charset.forName(UTF_8));
try {
byte[] input = Base64.decode(binary, Base64.NO_WRAP);
if (input.length == 0) {
return null;
}
return new String(input, Charset.forName(UTF_8));
} catch (java.lang.IllegalArgumentException e) {
Log.e(TAG, "", e);
return null;
}
}
</code></pre>
<p>The below are my unit test, which try to capture all possible cases.</p>
<h2>Unit test</h2>
<pre><code>@Test
public void obfuscate() {
String input = null;
String output = Utils.obfuscate(input);
String expectedOutput = null;
assertEquals(expectedOutput, output);
input = "";
output = Utils.obfuscate(input);
expectedOutput = "";
assertEquals(expectedOutput, output);
input = " ";
output = Utils.obfuscate(input);
expectedOutput = "==AI";
assertEquals(expectedOutput, output);
input = "a";
output = Utils.obfuscate(input);
expectedOutput = "==QY";
assertEquals(expectedOutput, output);
input = "a quick fox jump over the lazy dog 敏捷的棕色狐狸跨過懶狗";
output = Utils.obfuscate(input);
expectedOutput = "=c5inb7hm7Ygpj6toj7inD5inLbioX5omTomnfbjm/YlmDyZvRGI5pXYsBSZoRHIyVmdvBCctVnagg3bmByajlWdxBSY";
assertEquals(expectedOutput, output);
input = "キツネが怠惰な犬を飛び越える a quick fox jump over the lazy dog 敏捷的棕色狐狸跨過懶狗 Ein schneller Fuchs springt über den faulen Hund สุนัขจิ้งจอกตัวเตี้ยกระโดดข้ามสุนัขขี้เกียจ быстрый лис перепрыгнуть через ленивую собаку";
output = Utils.obfuscate(input);
expectedOutput = "=MY06CNsQHL0+CdgRDijRPY0yCNuQ3L01C9uQDytQXL0AGdtQfY0gwY0CG9gR3L0zC9iRDY0/CdtQDY01C9vQDSgRjL07CNI5C9iRDY0CGdgRvY0xCNIIiL4iiL41iL4BiL4AmL4JmL41iL4CiL4CiL4xiL4ZiL44iL4qiL4hiL4yiL4JmL4CiL4UiL4UiL4CmL4wiL4jiL4BiL4iiL4JmL41iL4ViL4AmL4niL4xiL4ViL4BiL4tiL4IiL4HiL4JmL40iL4IiL4CiL4xiL4ZiL44iL4qiL4gQmb1hEIuVGb1FmZg4WZkBiclJGvDDCdn5WayB3cgMHajVnRgIXZsxWZuh2YzBibpVEIXu452eo5OGY6oeL64u45Qu45ymI6VOq5Eq5532o5PWp5gc2bkBSe6FGbgUGa0BiclZ3bgAXb1pGI49mZgs2YpVXcgEGILK44IG44KaL6zG44bOa6SK44sq45qG44wOo5gCo5MG44NO44EO44tK44";
assertEquals(expectedOutput, output);
}
@Test
public void deobfuscate() {
String input = null;
String output = Utils.deobfuscate(input);
String expectedOutput = null;
assertEquals(expectedOutput, output);
input = "";
output = Utils.deobfuscate(input);
expectedOutput = "";
assertEquals(expectedOutput, output);
input = "==AI";
output = Utils.deobfuscate(input);
expectedOutput = " ";
assertEquals(expectedOutput, output);
input = "==QY";
output = Utils.deobfuscate(input);
expectedOutput = "a";
assertEquals(expectedOutput, output);
input = "=c5inb7hm7Ygpj6toj7inD5inLbioX5omTomnfbjm/YlmDyZvRGI5pXYsBSZoRHIyVmdvBCctVnagg3bmByajlWdxBSY";
output = Utils.deobfuscate(input);
expectedOutput = "a quick fox jump over the lazy dog 敏捷的棕色狐狸跨過懶狗";
assertEquals(expectedOutput, output);
input = "=MY06CNsQHL0+CdgRDijRPY0yCNuQ3L01C9uQDytQXL0AGdtQfY0gwY0CG9gR3L0zC9iRDY0/CdtQDY01C9vQDSgRjL07CNI5C9iRDY0CGdgRvY0xCNIIiL4iiL41iL4BiL4AmL4JmL41iL4CiL4CiL4xiL4ZiL44iL4qiL4hiL4yiL4JmL4CiL4UiL4UiL4CmL4wiL4jiL4BiL4iiL4JmL41iL4ViL4AmL4niL4xiL4ViL4BiL4tiL4IiL4HiL4JmL40iL4IiL4CiL4xiL4ZiL44iL4qiL4gQmb1hEIuVGb1FmZg4WZkBiclJGvDDCdn5WayB3cgMHajVnRgIXZsxWZuh2YzBibpVEIXu452eo5OGY6oeL64u45Qu45ymI6VOq5Eq5532o5PWp5gc2bkBSe6FGbgUGa0BiclZ3bgAXb1pGI49mZgs2YpVXcgEGILK44IG44KaL6zG44bOa6SK44sq45qG44wOo5gCo5MG44NO44EO44tK44";
output = Utils.deobfuscate(input);
expectedOutput = "キツネが怠惰な犬を飛び越える a quick fox jump over the lazy dog 敏捷的棕色狐狸跨過懶狗 Ein schneller Fuchs springt über den faulen Hund สุนัขจิ้งจอกตัวเตี้ยกระโดดข้ามสุนัขขี้เกียจ быстрый лис перепрыгнуть через ленивую собаку";
assertEquals(expectedOutput, output);
input = "?";
output = Utils.deobfuscate(input);
expectedOutput = null;
assertEquals(expectedOutput, output);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T08:19:07.733",
"Id": "445905",
"Score": "2",
"body": "Obfuscation is part of security. You want to hide plain text from user, but also state that security isn't a main concern. Could you explain more precisely what exactly you are looking for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T16:22:28.270",
"Id": "445965",
"Score": "0",
"body": "Where does the input come from? Should you be testing every character?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T04:02:25.287",
"Id": "446060",
"Score": "0",
"body": "The input is from user, and it can be anything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T04:07:14.833",
"Id": "446061",
"Score": "2",
"body": "@dfhwze We want to stop average Joe from looking at the content of String. But, we don't need bank level security encryption like AES and key management. That's why we name it \"obfuscate\" instead of \"encryption\"."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T07:49:47.613",
"Id": "229295",
"Score": "1",
"Tags": [
"java",
"strings",
"android",
"security"
],
"Title": "Functions to obfuscate and deobfuscate String. Am I missing out any edge cases?"
}
|
229295
|
<p>I am new to making <code>shopify</code> applications. I have made one application which helps merchants add additional features in their stores.</p>
<p>I have written some PHP code that is given below.</p>
<pre><code>$themeList = shopify_call($token,$shop,"/admin/api/2019-07/themes.json",array(),'GET');
$themeList = json_decode($themeList['response'], JSON_PRETTY_PRINT);
$theme_id = $themeList['themes'][0]['id'];
$customTheme = shopify_call($token,$shop,"/admin/api/2019-07/themes/".$theme_id."/assets.json?asset[key]=layout/theme.liquid&theme_id=".$theme_id,array(),'GET');
$customTheme = json_decode($customTheme['response'], JSON_PRETTY_PRINT);
$currentTheme = $customTheme['asset']['value'];
$pos = strpos($currentTheme,"</body>");
$str = "{% include 'back-to-the-top' %}\n";
$currentTheme = substr_replace( $currentTheme, $str, $pos, 0 );
</code></pre>
<p>This code fetches the store theme files and append my customize code into theme file.</p>
<p>I want to know that what is right way to do it. Please check it and tell me that this is right way to do it or not? Please tell me the right way to do it.</p>
|
[] |
[
{
"body": "<p>I haven't used shopify so I don't know if you can accomplish your task with fewer shopify calls, but I do find it a little odd that the URL in the second call requires redundant theme identification. I mean, the theme id is in the path and the querystring. </p>\n\n<p>Outside of that, I spy some basic refinements.</p>\n\n<ul>\n<li>As a general rule, avoid declaring single-use variables. Reasonable exceptions to this rule include when:\n\n<ul>\n<li>the merging of multiple processes/declarations results in a code line which exceeds a sensible length (horizontal scrolling is a drag and I generally obey PHPStorm's visual guide line when deciding when a line is too long) or</li>\n<li>the data being processed/produced/declared is clarified by the variable name</li>\n</ul></li>\n<li>Within a given project, determine if variables will be written in <strong>camelCase</strong> or <strong>snake_case</strong>. Use one style consistently throughout.</li>\n<li>There is no <code>JSON_PRETTY_PRINT</code> for <code>json_decode()</code> -- you are looking for the <code>true</code> parameter to make an array. The outcome is the same, but it is a typo worth fixing to avoid future confusion.</li>\n<li>Write a space between all comma-separated parameters in functions.</li>\n</ul>\n\n<p>Application:</p>\n\n<pre><code>$themeList = shopify_call($token, $shop, \"/admin/api/2019-07/themes.json\", array(), 'GET');\n$themeList = json_decode($themeList['response'], true);\n$themeId = $themeList['themes'][0]['id'];\n$themePath = \"/admin/api/2019-07/themes/{$themeId}/assets.json?asset[key]=layout/theme.liquid&theme_id={$themeId}\";\n\n$customTheme = shopify_call($token, $shop, $themePath, array(), 'GET');\n$customTheme = json_decode($customTheme['response'], true);\n$currentTheme = $customTheme['asset']['value'];\n$pos = strpos($currentTheme, \"</body>\");\n$str = \"{% include 'back-to-the-top' %}\\n\";\n$currentTheme = substr_replace($currentTheme, $str, $pos, 0);\n</code></pre>\n\n<p>In conclusion, I reckon only the PRETTY_PRINTing, variable formatting, and the spacing should be changed. The choice of how/when to declare data is mostly about personal taste.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T04:58:13.080",
"Id": "446065",
"Score": "0",
"body": "Thank you for guide me. Its help me to write proper code.\nBut I want to know that can I modified theme.liquid file this way or it is wrong way to do it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T05:05:21.130",
"Id": "446067",
"Score": "0",
"body": "Sorry, I am unable to provide that kind of review."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T23:11:51.843",
"Id": "229349",
"ParentId": "229297",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T08:31:17.177",
"Id": "229297",
"Score": "3",
"Tags": [
"php",
"e-commerce"
],
"Title": "Add customized code to Shopify theme"
}
|
229297
|
<p>There's a puzzle game called
<a href="https://store.steampowered.com/app/632000/CrossCells/" rel="nofollow noreferrer">CrossCells</a> (not
affiliated; there's also multiple other ones with the same kind of idea,
but slightly different layout and rule set) that I've been playing on
and off. After getting a bit frustrated with one puzzle (they're
getting larger and larger and I'm not very methodical with solving them
anymore) I thought of what environment I'd use to solve them
automatically (brute force not being a great idea).</p>
<p>This is also kind of spoiler-ish for puzzle 25, though I'm not printing
the full solution, you'd have to run the code to see it.</p>
<hr>
<p>I set up a quick hack in Prolog
(<a href="https://www.swi-prolog.org/" rel="nofollow noreferrer">SWI Prolog</a> using one of the
<a href="https://www.swi-prolog.org/pldoc/man?section=clpfd" rel="nofollow noreferrer">constraint solving modules</a>; <code>apt-get install swi-prolog</code> should do the trick)
and wanted to get some feedback on the solution, especially regarding</p>
<ul>
<li>whether this the go-to approach for this kind of puzzle, or whether a
more simple approach would work too,</li>
<li>whether a different environment would be a <em>much</em> better match for the
kind of problem (I'm not familiar enough with Prolog, but the
documentation was enough to let me at least get this done in a matter
of hours; I'd be more happy with, say, Java/Python/..., anything where
I can still switch to an imperative mode for e.g. I/O).</li>
</ul>
<p>For the specifics of the code also</p>
<ul>
<li>how this could be shortened while still being readable. It took quite a
while (after one failed attempt at expressing the equations) to
actually write down the whole puzzle in a readable way. E.g. not
having to write down all the variables explicitly in the goal <em>and</em>
when invoking it would be fantastic.</li>
<li>Whether the equations could be more concise. I deliberately wrote them
down row by row and column by column to be able to visually compare
them with the game's representation. But, that comes at the cost of
additional variables (<code>Nx</code>) and screen space.</li>
<li><del>Printing and comparing the solution is cumbersome, any hints how this
could be improved?</del> Edit: The second goal <code>solve</code> now prints each row, yet I can't think of a good way to truly show this as the original grid pattern, making comparing it with the real thing still a bit annoying. Still happy to find a better way!</li>
</ul>
<p>Edit: Since there was no answer yet I trimmed it down a bit myself, the noise is manageable now, focus would be more on how the equations could be simplified even more.</p>
<hr>
<p>Okay so the rules of the game for this particular puzzle:</p>
<p><a href="https://i.stack.imgur.com/MsW8m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MsW8m.png" alt="screenshot of unsolved puzzle 25 of the game CrossCells"></a></p>
<p>(Red was edited on top just in case.)</p>
<ul>
<li>Each cell can be toggled on (highlighted in blue by default), toggled
off (barely visible, same as the background basically) or undecided
(what's shown in the picture, dark gray). This corresponds to the
"term" in the cell being part of the expression, not being part of the
expression, or undecided. Only if all cells in the sequence are
either on or off can the constraint be satisfied or not; if any cell
is still in undecided state, the puzzle is <em>not solved yet</em>. (In the
solution there's no need to model the undecided state, we always
assign either on or off to each cell.)</li>
<li>Precedence is the usual, except that there's implied parentheses
between each cell; e.g. the first row reads
<code>(((+ 1) + 2) * 4) + 2 = 4</code>! If the first two cells were off, it
would be essentially <code>(((0) + 0) * 4) + 2 = 4</code> though.</li>
<li>Each column, row and sub-square <em>can</em> have a constraint. Those are
always after all cells in the sequence / at the boundary of the
square. In this one there's 10 of those for columns and rows and one for
the highlighted square ("[6] tiles").</li>
<li>The constraints are either number of tiles allowed to be set in the
sequence ("[1] tiles") or the total of evaluating the arithmetic
expression made up of the chosen cells ("24 total").</li>
</ul>
<p>Part of the problem of expressing this is that you can't simply write
(for the first row) <code>(1 * A + 2 * B) * 4 * C + 2 = 4</code> (given A-D as
integers between 0 and 1), because if e.g. "x4" is off, it's simply not
part of the expression, instead the full expression would read
<code>(+)1 + 2 ___ + 2 = 4</code> (<em>not</em> <code>((+)1 + 2) * 0 + 2 = 4</code>).</p>
<p>(Hope I didn't forget to explain anything, showing this interactively
would be a little bit easier.
<a href="https://www.youtube.com/watch?v=gULZAevKu50" rel="nofollow noreferrer">Here's one YouTube link</a>;
of course there are others too and it might disappear.)</p>
<hr>
<p>So the solution below</p>
<ul>
<li>uses variables <code>Bx</code> as integers 0 or 1 to express whether a cell
(numbered from top left to bottom right, row by row) is present or
not,</li>
<li>uses variables <code>Nx</code> where necessary to deal with optional factors /
"xA" cells (by, annoyingly, either constraining them to <code>1</code> if the corresponding value <code>Bx</code> isn't on/<code>0</code>, or constraining them to their factor if <code>Bx</code> is on/<code>1</code>; I'd <em>love</em> to have a better way for this) - the goal <code>factor</code> abstracts out this pattern,</li>
<li>and finally simply lists the constraints row by row and column by column.</li>
</ul>
<p>While <code>puzzle25</code> computes the solution, <code>solve</code> (for the lack of a better name), prints the solution for a given puzzle goal (so <code>solve(puzzle25).</code> will solve it and show the solution), that's already preparing for more puzzles to come.</p>
<pre><code>:- use_module(library(clpfd)).
factor(B, N, Factor) :-
B #= 0 #==> N #= 1,
B #= 1 #==> N #= Factor.
puzzle25(Rows) :-
Rows = [ [B1, B2, B3, B4], % =4
[B5, B6, B7, B8], % =5
[B9, B10, B11, B12, B13, B14, B15, B16], % =24
[B17, B18, B19, B20], % =2
[B21, B22, B23, B24] % =6
% =6 =12 [1] =6
% and the inner block can only have 6 selected
],
flatten(Rows, Flat),
Flat ins 0..1,
factor(B3, N3, 4),
((1 * B1) + (2 * B2)) * N3 + (2 * B4) #= 4,
factor(B6, N6, 2),
(2 * B5) * N6 + (2 * B7) + (1 * B8) #= 5,
factor(B10, N10, 2),
factor(B11, N11, 2),
factor(B12, N12, 3),
factor(B13, N13, 2),
factor(B14, N14, 3),
factor(B15, N15, 4),
(1 * B9) * N10 * N11 * N12 * N13 * N14 * N15 + (8 * B16) #= 24,
factor(B18, N18, 2),
factor(B20, N20, 2),
((1 * B17) * N18 + (2 * B19)) * N20 #= 2,
factor(B23, N23, 2),
factor(B24, N24, 2),
((3 * B21) + (3 * B22)) * N23 * N24 #= 6,
((1 * B1) + (2 * B5)) * N11 + (1 * B17) + (3 * B21) #= 6,
(2 * B2) * N6 * N12 * N18 + (3 * B22) #= 12,
B3 + B7 + B13 + B19 + B23 #= 1,
((2 * B4) + (1 * B8)) * N14 * N20 * N24 #= 6,
B1 + B2 + B3 + B5 + B6 + B7 + B11 + B12 + B13 + B17 + B18 + B19 #= 6.
solve(Puzzle) :-
apply(Puzzle, [L]),
flatten(L, M),
label(M),
forall(member(Row, L), write_term(Row, [nl(true)])).
</code></pre>
<p>I'm fairly certain this is correct, because the output works when put into the game and there's only a single solution (which is what I'd expect from how the game is set up, multiple solutions would be more complicated for the player).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T17:10:08.273",
"Id": "446626",
"Score": "0",
"body": "I'm not even a prolog beginner, but is so that you are brute forcing your way through the constraints with the possible candidates with backtracking?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T17:40:59.647",
"Id": "446638",
"Score": "1",
"body": "@dfhwze it's slightly fancier, [Wikpedia has a good explanation](https://en.wikipedia.org/wiki/Constraint_programming#Domains)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T17:42:43.627",
"Id": "446639",
"Score": "0",
"body": "I was thinking about https://en.wikipedia.org/wiki/Knuth%27s_Algorithm_X. But you need to tweak it to take into account dynamic updates of the remaining constraints."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T15:25:25.043",
"Id": "447143",
"Score": "1",
"body": "Can a multiplication square be first in a row or column that has a numerical constraint? Can there be squares with '-' or '/' or '%' operators?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T19:04:10.893",
"Id": "447165",
"Score": "0",
"body": "@RootTwo Yes, but only because sometimes you have constraints on _both_ sides, which requires you to satisfy them read from the left _and_ read from the right. I'm relatively sure I haven't seen one when it wasn't set up like that though.\n\nThere are no other constraint types I've encountered, no."
}
] |
[
{
"body": "<p>I haven't looked at any Prolog code in at least a decade. So, I really can't give any useful feedback on your code. However, the question piqued my interest, and you did say you'd be more happy with ... Python...... </p>\n\n<p>So I rolled my own solver in Python. It's rough and under-tested, has very little error checking, and could use some refactoring. But here it is:</p>\n\n<pre><code>import re\n\nfrom collections import defaultdict\nfrom enum import Enum\nfrom operator import add, mul\n</code></pre>\n\n<p>Enum for the state of each square</p>\n\n<pre><code>class State(Enum):\n OFF = 0\n ON = 1\n UNASSIGNED = 2\n</code></pre>\n\n<p>Class for the squares</p>\n\n<pre><code>class Variable:\n\n def __init__(self, op, value):\n self.op = op\n self.value = int(value)\n self.state = State.UNASSIGNED\n self.shorthand = f\"{op}{value}\"\n\n self.func = {'+':add, '*':mul}[op]\n\n def evaluate(self, left):\n if self.state != State.ON:\n return left\n else:\n if left:\n return self.func(left, self.value) \n\n else:\n return self.value\n\n def __str__(self):\n return f\"Variable('{self.op}','{self.value}'): {self.state.name})\" \n\n def __repr__(self):\n return f\"V('{self.op}','{self.value}')\" \n\n def code(self):\n # OFF ON UNKNOWN\n return ['', self.shorthand, '?' ][self.state.value]\n</code></pre>\n\n<p>Enum for status of a constraint</p>\n\n<pre><code>class Status(Enum):\n FAILED = 0\n PASSED = 1\n UNKNOWN = 2\n</code></pre>\n\n<p>Class for the constraints</p>\n\n<pre><code>class Constraint:\n\n def __init__(self, variables, op, value):\n self.variables = list(variables)\n self.op = op\n self.value = int(value)\n\n def check(self):\n if self.op == '#':\n value = 0\n for v in self.variables:\n if v.state==State.UNASSIGNED:\n return Status.UNKNOWN\n\n if v.state==State.ON:\n value += 1\n\n else:\n value = None\n for variable in self.variables:\n if variable.state == State.UNASSIGNED:\n return Status.UNKNOWN\n\n value = variable.evaluate(value)\n\n return Status.PASSED if value == self.value else Status.FAILED\n\n def __str__(self):\n variables = ','.join(repr(v) for v in self.variables)\n return f\"Constraint([{variables}], '{self.op}', '{self.value}')\"\n</code></pre>\n\n<p>Class for the puzzle</p>\n\n<pre><code>class Puzzle:\n\n def __init__(self, puzzle):\n self.puzzle = puzzle[:]\n\n self.constraints = []\n self.by_var = defaultdict(list)\n self.variables = []\n\n rows = defaultdict(list)\n cols = defaultdict(list)\n groups = defaultdict(list)\n\n last_var_row = 0\n\n # gather the variables\n for r,row in enumerate(puzzle):\n for match in re.finditer(r\"(?P<op>[+*])(?P<val>\\d+)(?P<group>\\w?)\", row):\n variable = Variable(match['op'], match['val'])\n\n self.variables.append(variable)\n rows[r].append(variable)\n\n for left,right in cols.keys():\n if match.start() <= right and match.end() >= left:\n key = (left, right)\n break\n else:\n key = (match.start(),match.end())\n\n cols[key].append(variable)\n\n if match['group']:\n groups[match['group']].append(variable)\n\n last_var_row = max(last_var_row, r)\n\n # gather the constraints\n for r,row in enumerate(puzzle):\n for match in re.finditer(r\"(?P<group>\\w?)(?P<op>[#=])(?P<val>\\d+)\", row):\n if match['group']:\n cvars = groups[match['group']]\n\n elif r <= last_var_row:\n cvars = rows[r]\n\n else:\n for left,right in cols.keys():\n if match.start() <= right and match.end() >= left:\n key = (left, right)\n break\n else:\n raise ValueError(\"Unaligned column constraint: {match[0]} @ line {r}, col {match.start()}\")\n\n cvars = cols[key]\n\n constraint = Constraint(cvars, match['op'], match['val'])\n self.constraints.append(constraint)\n\n for v in cvars:\n self.by_var[v].append(constraint)\n\n def consistent(self, variable):\n for constraint in self.by_var[variable]:\n check = constraint.check()\n\n s = ' '.join(v.code() for v in constraint.variables)\n\n if check == Status.FAILED:\n return False\n\n return True\n\n\n def solve(self, pretty=False):\n\n def search(variables):\n if not variables:\n return [v.state.value for v in self.variables]\n\n first, *rest = variables\n for state in (State.ON, State.OFF):\n first.state = state\n\n check = self.consistent(first)\n if check:\n\n result = search(rest)\n\n if result is not None:\n return result\n\n first.state = State.UNASSIGNED\n return None\n\n solution = search(self.variables[:])\n\n if solution is not None:\n if pretty == True:\n index = 0\n\n def sub(match):\n nonlocal index\n\n state = self.variables[index].state\n index += 1\n\n return match[0] if state == State.ON else ' '*len(match[0])\n\n\n print(re.sub(r\"(?P<op>[+*])(?P<val>\\d+)(?P<group>\\w?)\", sub, '\\n\\n'.join(self.puzzle)))\n\n return solution\n</code></pre>\n\n<p>A puzzle is defined graphically by a list of strings as shown in the example below. </p>\n\n<p>A square is an operator followed by an integer, and an optional group id (a letter). For example, '+12' or '*3f'. All squares and column constraints must line up under the top square in the column (they must overlap). </p>\n\n<p>A constraint is an optional group id, and operator ('=' or '#'), and then an int. An '=' sign means the formula equals the int. A '#' means that many squares are ON. For example, '=8', '#1', or 'f#5'.</p>\n\n<p><code>Puzzle.solver()</code> returns a list of 0/1 that corresponds to the squares in left-to-right, top-to-bottom order. A '1' means the square is ON and a '0' means it's OFF. </p>\n\n<p>Here's your example coded for this solver:</p>\n\n<pre><code>puzzle = [\n \" +1a +2a *4a +2 =4\",\n \" +2a *2a +2a +1 =5\",\n \" +1 *2 *2a *3a *2a *3 *4 +8 =24\",\n \" +1a *2a +2a *2 =2\",\n \" +3 +3 *2 *2 =6\",\n \" =6 =12 #1 =6 \",\n \"a#6\"\n ]\n\np = Puzzle(puzzle)\n\np.solve()\n</code></pre>\n\n<p>If you pass <code>pretty=True</code> to the <code>Puzzle.solver()</code>, it also prints out a picture of the solution.</p>\n\n<pre><code>p.solve(pretty=True)\n\n +2a +2 =4\n\n +2a +2a +1 =5\n\n +1 *2 *3a *4 =24\n\n +1a *2a =2\n\n +3 *2 =6\n\n =6 =12 #1 =6 \n\na#6\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T13:01:25.440",
"Id": "449218",
"Score": "0",
"body": "Thanks for your answer! I really like the much more readable representation of the puzzle too and how you did made it work with the parser, definitely something to learn from."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T22:40:12.907",
"Id": "229766",
"ParentId": "229298",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229766",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T08:57:29.373",
"Id": "229298",
"Score": "6",
"Tags": [
"algorithm",
"game",
"prolog"
],
"Title": "Constraint solving CrossCells puzzle game solution"
}
|
229298
|
<p>I'm just trying to learn python: I tend to write my own customized wrappers arround "more complicated" python functionalities so that i can use them more easily, more consistent, easier to change in one place, etc.</p>
<p>I.e. if wrote my own class <code>my_os</code> with i.e. has the functions <code>rm(path)</code> or <code>mv(from_path, to_path)</code> so that on application- or script-level I don't need to know or care (or remember ;)) about the specialities of <code>os</code> , <code>shutil</code>, <code>pathlib</code> or whatever.</p>
<p>I did the same for <code>argparse</code>. Even though my own functions are quite sparse in this case, I still prefer a named <code>my_add_required_arg</code> over worrying about the action parameter of the native function in every script I write.</p>
<p>So much to the history of this class:</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Wrapper functionality for Pythons built-in argparse package."""
import argparse
class myArgparser(argparse.ArgumentParser):
"""Offers a wrapper for Pythons built-in argparse package.
It offers simple named functions to
* add a brief description
* set a version
* set optional named arguments
* set non optional named arguments
* set optional flags
and then to return the parsed arguments.
"""
def __init__(self, description=None):
"""Create the main argparser object.
Args:
description: The optional description.
"""
super(myArgparser, self).__init__(description=description)
# required arguments is just printed out on "-h"
self.myRequired = self.add_argument_group("required arguments")
def my_set_version(self, version):
"""Set the version information, printed out by --version.
Args:
version: version string
"""
self.add_argument("--version", action="version", version=version)
def my_add_flag(self, short, long, help):
"""Add a boolean flag.
If it is set, the flag argument is set to True, else to False.
Args:
short: the short name, i.e. '-d'
long: the long name, i.e. '--debug'
help: description printed out on '-h'
"""
self.add_argument(short, long, help=help, action="store_true")
def my_add_arg(self, short, long, help):
"""Add an optional named argument of string type.
If it isn't set on the commandline, it defaults to None.
Args:
short: the short name, i.e. '-ld'
long: the long name, i.e. '--logdir'
help: description printed out on '-h'
"""
self.add_argument(short, long, help=help, action="store")
def my_add_required_arg(self, short, long, help):
"""Add an required named argument of string Type.
Args:
short: the short name, i.e. '-ld'
long: the long name, i.e. '--logdir'
help: description printed out on '-h'
"""
self.myRequired.add_argument(
short, long, help=help, action="store", required=True
)
def my_get_args(self):
"""Return the arguments depending on the configured and set arguments.
Return:
Namespace-Object containing values for all added arguments
"""
return self.parse_args()
</code></pre>
<p>But using this class, I realized that I was using the same functions with oftenly the same parameters at the beginning of each of my scripts which needed arguments, so i added another function:</p>
<pre class="lang-py prettyprint-override"><code>@classmethod
def get_args(
cls,
description=None,
version=None,
optional_args=[],
required_args=[],
flags=[],
):
"""Return the parsed arguments.
Each passed argument or flag tuple must contain the short name, the long name and the description
of the argument.
Args:
description: the optional description
version: the optional version string
optional_args: as list of tuples
required_args: as list of tuples
flags: as list of tuples
"""
argparser = cls(description)
if version is not None:
argparser.my_set_version(version)
for arg in optional_args:
argparser.my_add_arg(*arg)
for arg in required_args:
argparser.my_add_required_arg(*arg)
for flag in flags:
argparser.my_add_flag(*flag)
return argparser.my_get_args()
</code></pre>
<p>So now I can start a script with a clean argument definition, which I like:</p>
<pre class="lang-py prettyprint-override"><code># set global vars & args
version = 'mySpeedtest-20190918'
description = "Test the actual internet connection speed and log the result"
optional_args = [('-ld','--logdir', 'set destination directory for the logfile')]
flags = [('-d', '--debug', 'set loglevel to debug')]
args = my_util.my_argparse.myArgparser.get_args(description, version, optional_args, flags=flags)
</code></pre>
<p>Furthermore I don't have bloated init-function and still could use the single functions if I allready strongly had or wanted to.</p>
<p>Now the question: Does it make sense/is it good practice/is it "pythonic" to use a <code>@classmethod</code> as a pseudo-constructer like this? </p>
<p>(Kind of "Because you can do it, doesn't mean necessarily you should do it!"-Question ;))</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T09:38:56.393",
"Id": "445910",
"Score": "1",
"body": "Your question \"Is it good practice to use a @classmethod as a pseudo-constructer ? \" is a question that I feel belongs more to Software Engineering. In general Code Review will give you more advices about how to structure implementation, while SE helps more structuring interfaces."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T11:10:56.450",
"Id": "445921",
"Score": "0",
"body": "@ArthurHavlicek I guess after reading Gloweyes response, my question might not be as desired, but the response is a perfect kind of code review :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T11:38:29.027",
"Id": "445928",
"Score": "0",
"body": "Just to be clear, I didn't mean that your question is offtopic there because you did post code to be reviewed and it's acceptable scopes of stack exchanges overlap a bit but if you did want a theoritical, elaborate point of view about structuring your classes API, with pro/cons of alternatives based on your requirements, then SE was more likely to give that. I actually would be surprised you don't already find good practices questions about classmethods there, if you are interested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T17:49:08.850",
"Id": "445974",
"Score": "0",
"body": "Have you ever used the [docopt library](https://github.com/docopt/docopt)? You just write the help docstring and it automatically figures out everything from that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T05:31:38.157",
"Id": "446068",
"Score": "0",
"body": "@Justin No I didn'i know it yet, thank you. Allthough it reads nice I don't think that I'm gonna use it: The helptext and parameter description printed out with ```-h``` for the user mustn't necessarily be same information as the docstring for the developer."
}
] |
[
{
"body": "<p>Using <code>@classmethod</code> for constructors is perfectly fine. It is basically the only reason you ever need to use them.</p>\n\n<p>Classes create a namespace (and <a href=\"https://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow noreferrer\">Namespaces are one honking great idea -- let's do more of those!</a>). You don't need to preface all your methods and classes with <code>my_</code>. Your code becomes much more readable if you just name them according to what they do:</p>\n\n<pre><code>class ArgParser(argparse.ArgumentParser):\n ...\n def set_version(self, version):\n ...\n def add_flag(self, short, long, help):\n ...\n ...\n</code></pre>\n\n<p>Python also has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which programmers are recommended to follow. It recommends using <code>lower_case</code> for methods and variables.</p>\n\n<p>In general I am not a huge fan of this class. It makes building an argument parser slightly easier (nice!) at the cost of hiding away all advanced functionality (not so nice). I would try finding an interface that at least allows you to add additional options (like specifying types, defaults, nargs, etc). Maybe each argument is also allowed to be a tuple of a tuple and a dictionary (for positional and keyword arguments)? </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T11:20:20.893",
"Id": "445923",
"Score": "0",
"body": "Thank you for your answer. Concerning namespaces: yes you're right and in general i don't preface all my methods. But in this special case, as my Class inherits from the general ArgumentParser I just wanted to make sure not to \"hide\" something of it (without the need of checking if it exists or not ;)) At the moment the functionality of Argparse is totally fine for me."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T10:30:02.803",
"Id": "229304",
"ParentId": "229300",
"Score": "3"
}
},
{
"body": "<p>I disagree on you with the need for a wrapper around the stdlib argparse, but that's a matter of taste. And I don't see anything wrong with your implementation of the rather thin wrapper.</p>\n\n<h1>Classmethod as Constructor</h1>\n\n<p>This is NOT what you're doing. A constructor creates an instance in a way somehow different from the standard and returns it. An example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Thing:\n def __init__(self, arg1, arg2)\n self.var1 = arg1\n self.var2 = arg2\n\n @classmethod\n def from_other_thing(cls, other_thing)\n return cls(other_thing.somevar, other_thing.othervar)\n</code></pre>\n\n<h1>Your usecase</h1>\n\n<p>What you're doing is creating a class method that creates an instance to do work, then returning the results of that work. I'd like to emphasize that this is a perfectly valid usecase. However, your classmethod is also just about doing what you made the rest of your wrapper class for. You can easily cut down on the amount of new methods like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class myArgparser(argparse.ArgumentParser):\n \"\"\" Your perfectly fine docstring \"\"\"\n\n @classmethod\n def get_args(\n cls,\n description=None,\n version=None,\n optional_args=None,\n required_args=None,\n flags=None,\n ):\n \"\"\"Your other perfectly fine docstring\"\"\"\n optional_args = optional_args if optional_args is not None else []\n required_args = required_args if required_args is not None else []\n flags = flags if flags is not None else []\n\n argparser = cls(description)\n if version is not None:\n argparser.add_argument(\"--version\", action=\"version\", version=version)\n for arg in optional_args:\n argparser.add_argument(*arg, action=\"store\")\n for arg in required_args:\n argparser.add_argument(*arg, action=\"store\", required=True)\n for flag in flags:\n argparser.add_argument(*flag, action=\"store_true\")\n return argparser.parse_args()\n\n</code></pre>\n\n<p>I reduced the whitespace a bit - to many newlines make reading harder. I've also changed the get_args argument to do the work you had spread over all the other 1-line functions - if a function is 1 line and used in just 1 place, then you don't really need a function for it. That's premature optimization.</p>\n\n<h3>Mutable Default Arguments</h3>\n\n<p><a href=\"https://docs.python-guide.org/writing/gotchas/\" rel=\"nofollow noreferrer\">Don't use mutable defaults.</a> Instead, use None and create empty lists, or change the default to an empty tuple, which is safe. I've gone for the first option, but as far as I can tell the empty tuple version would be perfectly fine as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T11:29:13.557",
"Id": "445925",
"Score": "0",
"body": "Thank you very much. Reading your version I had to ask myself, why I didn't do it like that \"out of the box\" ;) Also the reminder not to use mutable defaults is a nice one. I even _read_ that once before, but just didn't think of it after my first test ended with the result \"cannot iterate over NoneType\" :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T11:30:51.450",
"Id": "445927",
"Score": "0",
"body": "\"Why didn't I do it like that\" is a rather common thought when developing. I've had it about my own code more than I can remember. Glad to help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T11:39:10.457",
"Id": "445929",
"Score": "0",
"body": "If you are reducing the whole class to a single `classmethod`, you might as well simplify it to a simple function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T11:50:29.150",
"Id": "445930",
"Score": "0",
"body": "This class still extends the ArgumentParser class. But yes, it could also be a stand-alone function that receives the class as argument. I think both are valid choices."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T10:36:47.287",
"Id": "229305",
"ParentId": "229300",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229305",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T09:26:09.147",
"Id": "229300",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"object-oriented",
"wrapper"
],
"Title": "Wrapper for Python's argparse class"
}
|
229300
|
<p>I want to condense it and get rid of any noob programming errors.</p>
<p>The code works fine but I know it's not as elegant as it could be and I really want to improve. Your advice would be brilliant!</p>
<p>I've talked to other engineers and had some basic help but not a lot.</p>
<pre><code>#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <io.h>
#include <time.h>
void serialPort(HANDLE Comms);
int readPort(HANDLE Comms, int testNum);
void parseFile(int fileNum);
int fileExist(void);
int main(){
//OPENING SERIAL PORT
int res = 0; //variables to be passed to functinos
int logNum = 0;
HANDLE hComm;
hComm = CreateFile( "\\\\.\\COM4", //port name
GENERIC_READ | GENERIC_WRITE, //Read/Write
0, // No Sharing
NULL, // No Security
OPEN_EXISTING,// Open existing port only
0, // Non Overlapped I/O
NULL); // Null for Comm Devices
if (hComm == INVALID_HANDLE_VALUE){ //print if COM port wont open
printf("Error opening port");
exit(42);
}
else {
printf("Opening of port successful\n"); //Print to know serial port is open
}
//Calling necessary functions
serialPort(hComm);
res = fileExist();
logNum = readPort(hComm, res);
parseFile(logNum);
CloseHandle(hComm);//Closing the Serial Port
return 0; //main returns 0
}
void serialPort(HANDLE Comms){
//CONFIGURING SERIAL PORT
BOOL Status;
DCB dcbSerialParams = { 0 }; // Initializing DCB structure
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
dcbSerialParams.BaudRate = CBR_57600; // Setting BaudRate = 9600
dcbSerialParams.ByteSize = 8; // Setting ByteSize = 8
dcbSerialParams.StopBits = ONESTOPBIT;// Setting StopBits = 1
dcbSerialParams.Parity = NOPARITY; // Setting Parity = None
SetCommState(Comms, &dcbSerialParams); //Assignin serial settings to comm handle
Status = EscapeCommFunction(Comms, SETRTS); //RTS Request to Send Signal to esentially reset Serial port (arduino)
Status = EscapeCommFunction(Comms, SETDTR); //DTR data terminal ready, PC side terminal ready to recieve data
}
int fileExist(void){
//DOES FILENAME ALREADY EXIST
int result = 0;
char testNum[10];
char fp[80];
char file[80] = "C:/Users/jgrayjt/Documents/Logs/TestLog_";
char fileEnd[5] = ".txt";
for (int i = 1; i < 1000; i++){
sprintf(testNum, "%d", i); //converting testNum as int to string
//adding test num to file dir
strcpy(fp, file); //adding strings to make file name
strcat(fp, testNum);
strcat(fp, fileEnd);
printf("%s", fp);
/* Check for existence */
if((_access(fp, 0 )) != -1 ){ //Function to check if file exists
printf( "\nFile logs exists\n" );
}
else { //if file doesnt exists
printf("\nFile doesnt exist\n");
result = i; //set result to equal current value for i
break;
}
}
return result; //send file num to next function
}
int readPort(HANDLE Comms, int testNum){
//READING DATA FROM SERIAL PORT
//time_t rawtime;
//struct tm * timeinfo;
//time (&rawtime);
//timeinfo = localtime (&rawtime);
char word[14] = "Test Finished"; //Text to look for
char SerialBuffer[256];//Buffer for storing Rxed Data
DWORD NoBytesRead; //set type for NoBytesRead
char Num[10];
sprintf(Num, "%d", testNum); //convert test num to string
char str[80];
//char buf[100];
char *file = "C:/Users/jgrayjt/Documents/Logs/TestLog_";
//char tandd[8] = "_%x_%X";
char fileEnd[5] = ".txt";
//strftime(buf,64, "_%x_%X", timeinfo);
strcpy(str, file); //adding strings to make file name
strcat(str, Num);
//strcat(str, buf);
strcat(str, fileEnd);
printf("%s", str);
FILE *fp; //create file pointer
fp = fopen(str, "w"); //create file to write serial data to
do { //start do while loop
ReadFile(Comms, //Handle of the Serial port
SerialBuffer, //
sizeof(SerialBuffer) -1,//Size of Buffer
&NoBytesRead, //Number of bytes read
NULL);
SerialBuffer[NoBytesRead] = '\0'; //Specify null terminator to stop data rxing strangly
printf("%s", SerialBuffer); //Print rx'd data to CMD
fprintf(fp, "%s", SerialBuffer); //Save rx'd data to txt file
char *fin = strstr(SerialBuffer, word); //Find 'search' in SerialBuffer and assign to 'fin'
//if fin has data then close Serial and close/save file
if (fin != NULL){
printf("Results Successfully logged \n \r \n \r");
fclose(fp); //close file
fp = NULL; //set file pointer to equal null to break from the loop
}
} while (fp != NULL); //while, from do while loop
return testNum; //return testNum for use in another function
}
void parseFile(int fileNum){
//FUNCTION TO PARSE DATA FROM LOG FILE TO FIND FAILED TESTS
char Num[10]; //set Num as char and give extra memory
sprintf(Num, "%d", fileNum); //Convert filenNum to string
char dir[80]; //set dir as char and give extra memory
char *file = "C:/Users/jgrayjt/Documents/Logs/TestLog_";
char fileEnd[5] = ".txt";
strcpy(dir, file); //adding strings to make file name
strcat(dir, Num);
strcat(dir, fileEnd);
printf("%s", dir);
FILE *fp1; //create file pointer
char str[512]; //string to store data read from log file
const char fail[5] = "FAIL"; //text to look for
const char testnum[23] = "Test Iteration"; //text to look for
char *ret; //create char variables
char *num;
fp1 = fopen(dir , "r"); //Open file to read
if (fp1 == NULL){ //if you cant open file, print
printf("File open fail");
}
//Loop to find test number and fail strings
while( fgets (str, 512, fp1)!=NULL ) {
num = strstr(str, testnum); //find test num in string and assign to num
ret = strstr(str, fail); //find 'fail' in string and assign to ret
if (ret != NULL && num != NULL){ //if both variables have data then print num
printf("\n \r %s\n\r", num); //num has been given enough mem to include the fail that comes after it
}
}
fclose(fp1); //close/save fil
getchar();
getchar();
}
</code></pre>
|
[] |
[
{
"body": "<p>Welcome to Code Review, nice first question.\nDon't Panic, and always take a towel with you.</p>\n\n<p><strong>General Observations</strong><br>\nThis may be a copy and paste error, but the level of indentation is inconsistent. This makes writing, reading and debugging the program very difficult. </p>\n\n<p>There are too many comments. Code should be self documenting for the most part, only things that won't be apparent by reading the code should be in comments.</p>\n\n<p>Comment blocks are ok at the top of a function to describe what the function does and when it should be called.</p>\n\n<p>Code needs to be maintained, there may be features added or bugs fixed. Since code will change, the comments may have to change or they become irrelevant. For this reason most developers write only absolutely necessary comments indicating strategy or citing requirements.</p>\n\n<p>The only type of programming that would require the level of comments in this program would be assembly code programming.</p>\n\n<p><strong>The exit() Function and Magic Numbers</strong><br>\nGenerally the <code>exit(int status)</code> function isn't necessary in the <code>main()</code> function, the use of <code>return</code> would be better. The <code>exit()</code> function can be used in subroutines if a none recoverable error occurs in a subroutine but there are also other ways to handle these errors that you may want to look into in the future. Return from the <code>main()</code> function should return one of two values, <a href=\"https://en.cppreference.com/w/c/program/EXIT_status\" rel=\"nofollow noreferrer\"><code>EXIT_SUCCESS</code> or <code>EXIT_FAILURE</code></a>. These symbolic constants are available from <code>stdlib.h</code> which is included in this program.</p>\n\n<pre><code> exit(42);\n</code></pre>\n\n<p>It's not clear what 42 means unless you're a fan of \"Hitchhiker's Guide to the Galaxy\". The use of numeric constants rather than symbolic constants in code is sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>. Generally <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">symbolic constants are preferred</a> because they make the code easier to understand and maintain.</p>\n\n<p>In the the C programming language there are 2 methods for defining symbolic constants, the more modern method is</p>\n\n<pre><code>const int StringSize = 80;\n</code></pre>\n\n<p>The historic method defining symbolic constants is to use a macro</p>\n\n<pre><code>#define SERIAL_BUFFER_SIZE 256\n</code></pre>\n\n<p>Symbolic constants are very helpful for arrays, not only can one define the array using the symbolic constants, but any loops that access the array can use the symbolic constant as the end of the loop. This allows the programmer to change array sizes with only one edit rather than modifying the constant value everywhere.</p>\n\n<p>The function <code>int readPort(HANDLE Comms, int testNum)</code> has a number of arrays with numeric constants that should be converted.</p>\n\n<pre><code>char word[14] = \"Test Finished\"; //Text to look for\nchar SerialBuffer[256];//Buffer for storing Rxed Data\nchar Num[10];\nchar str[80];\nchar *file = \"C:/Users/jgrayjt/Documents/Logs/TestLog_\";\nchar fileEnd[5] = \".txt\";\n</code></pre>\n\n<p>If the array SerialBuffer was defined using a symbolic constant then the code to read the serial port doesn't need the <code>sizeof(SerialBuffer)</code> it can use the symbolic constant.</p>\n\n<p><em>Note: C style strings don't necessarily require an array constant.</em></p>\n\n<pre><code> char word[14] = \"Test Finished\"; //Text to look for\n</code></pre>\n\n<p>would be easier to define and use as </p>\n\n<pre><code> char *word = \"Test Finished\";\n</code></pre>\n\n<p>The code already uses this method for </p>\n\n<pre><code> char *file = \"C:/Users/jgrayjt/Documents/Logs/TestLog_\";\n</code></pre>\n\n<p>The variable name <code>word</code> might better be <code>SearchString</code>.</p>\n\n<p>It is best to be consistent through out a program as to how something is done, whether it is code indentation or variable declarations</p>\n\n<p><em>The variable str might better be defined using <code>BUFSIZ</code> which is defined in <code>stdio.h</code>. File names can be at least <code>BUFSIZ</code>, 80 is not a realistic value for a fully defined file spec.</em> </p>\n\n<p><strong>Missing Error Check</strong><br>\nThe function <code>int readPort(HANDLE Comms, int testNum)</code> Uses <code>fopen()</code> but doesn't check the value to see if the file has actually been opened. The <code>do while</code> loop terminates at the end if the file pointer is NULL, but the loop still executes at least one time and can attempt to write to a file that didn't open. This would cause the program to crash. The loop should not be entered if the file was not opened. The error should at least be reported if not handled. </p>\n\n<p><strong>Use DRY Code</strong><br>\nThere is a programming principle called <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself</a>. There is code in the function <code>int fileExist(void)</code> that creates a filename, this same code is in the function <code>int readPort(HANDLE Comms, int testNum)</code> and <code>void parseFile(int fileNum)</code>. It might be better if the code to create the filename was a function itself that was called by all of these function. One of the benefits of this is the code only has to be written and debugged once, and any maintenance can be done in one place rather than two places.</p>\n\n<p><strong>Code Complexity</strong><br>\nThe function <code>main()</code> has the appropriate complexity, but the functions <code>int fileExist(void)</code>, <code>int readPort(HANDLE Comms, int testNum)</code> and <code>void parseFile(int fileNum)</code> are too complex (do too much). Each of these functions could have subroutines that they call and could make the function shorter and perform a single function.</p>\n\n<p>There is also a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> that applies here. The Single Responsibility Principle states:</p>\n\n<blockquote>\n <p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<p>This programming principle compliments the DRY programming principle.</p>\n\n<p><strong>Declare the Variables When They are Needed</strong><br>\nThe original definition of the C programming language required all variable to be declared at the top of the function, but this is no longer necessary. Older books and examples misrepresent this.</p>\n\n<p>An example:</p>\n\n<pre><code>int main(){\n HANDLE hComm;\n hComm = CreateFile( \"\\\\\\\\.\\\\COM4\", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\n if (hComm == INVALID_HANDLE_VALUE){\n printf(\"Error opening port\");\n exit(EXIT_FAILURE);\n }\n else {\n printf(\"Opening of port successful\\n\");\n }\n\n serialPort(hComm);\n int res = fileExist();\n int logNum = readPort(hComm, res);\n parseFile(logNum);\n\n CloseHandle(hComm);//Closing the Serial Port\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T09:02:13.453",
"Id": "446961",
"Score": "0",
"body": "Absolutely brilliant answer, thank you so much very very useful tips!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:07:26.337",
"Id": "229332",
"ParentId": "229303",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229332",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T10:24:54.880",
"Id": "229303",
"Score": "4",
"Tags": [
"c",
"file-system",
"io",
"winapi",
"arduino"
],
"Title": "This program reads from serial port, Saves this to a text file, increments file name each time it is run"
}
|
229303
|
<blockquote>
<p>Q: Given a list, reverse the order of its elements (don't use
collections).</p>
</blockquote>
<p>Here is my solution:</p>
<pre><code>public static <T> void reverse(List<T> list) {
if (list.size() > 0) {
T t;
t = list.get(0);
list.remove(0);
reverse(list);
list.add(t);
}
}
</code></pre>
<ol>
<li>I want to know if this is an efficient way of reversing a list</li>
<li>Is this working for every list as input?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T12:28:54.587",
"Id": "445934",
"Score": "3",
"body": "You could compare performance of this against [Collection.reverse](https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/util/Collections.java#LC421). My guess is Collection.reverse would be faster"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T17:19:45.173",
"Id": "445969",
"Score": "2",
"body": "I'm voting to close this question since it's unclear what the scope of restrictions is concerning the use of collections."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T20:53:34.350",
"Id": "446021",
"Score": "0",
"body": "@dustytrash That's explicitly disallowed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T20:55:00.983",
"Id": "446023",
"Score": "0",
"body": "@dfhwze Likely the [Collections API](https://en.wikipedia.org/wiki/Java_collections_framework), what's unclear?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T21:06:56.937",
"Id": "446028",
"Score": "2",
"body": "@Mast I'd say it's not entirely clear whether it's the Collections API, or just collections in general."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T08:05:40.753",
"Id": "446076",
"Score": "1",
"body": "It's a while since I did Java, but I'm pretty sure `List<T>` is part of Collections."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T08:48:15.093",
"Id": "446080",
"Score": "0",
"body": "Wow, moments like this make Python so much prettier... `mylist = mylist[::-1]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T10:06:39.007",
"Id": "446086",
"Score": "0",
"body": "@Gloweye that isn't in-place, and I'd take a method call with the word `reverse` in it over that any day ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T10:12:46.497",
"Id": "446087",
"Score": "1",
"body": "list.reversed() works just as well, but the question disallows builtin methods, and reverse slicing isn't a method. (and for pure iteration, slicing may even be faster...I'd have to check.)"
}
] |
[
{
"body": "<p>No and no. This is a very inefficient way to reverse, for example, a dynamic array based list (it's a different story with a linked list). With a dynamic array based (e.g. <code>ArrayList</code>) The <code>remove(0)</code> operation will require moving every other element in the list (linear in the length), so the whole method is quadratic in the total length of the list. It also requires a linear number of stack frames, which are actually pretty expensive and if you ask for too many the program will crash, which means this method will not work for long lists.</p>\n\n<p>An efficient solution would work in linear time with a constant space requirement.</p>\n\n<hr />\n\n<p>When thinking about inputs, it's important to also consider <code>null</code> as a possible input. The deficient spec does not indicate what should be done with a <code>null</code> input, which means you have had to make a decision, and that decision should be documented. The 'easy' (and often best) option is to explicitly test for a <code>null</code> input and throw an <code>IllegalArgumentException</code> exception, so that anyone using your method receives a useful error message. You could argue that your code should do nothing with a <code>null</code>, but that's a bit iffy, because the spec doesn't qualify the behaviour, and that would 'silently' fail if someone passed it a <code>null</code> incorrectly: throwing an exception forces any unexpected usage to be address directly, which may or may not prompt a decision change, which makes it a good 'default' choice.</p>\n\n<hr />\n\n<p>There is no need here to pre-declare <code>t</code>: just declare and assign it in one go:</p>\n\n<pre><code>T t = list.get(0);\n</code></pre>\n\n<p>This makes it easier to find out what it means. You could also make it <code>final</code> in this case, so that it is entirely clear that it is only assigned once, which makes it that little bit easier to reason about the code.</p>\n\n<hr />\n\n<p>When writing recursive code like this, it can pay select the 'most ideal' base case. In this instance, any list of length no more than 1 is already reversed, so you could change the <code>if</code> condition to <code>list.size() > 1</code>. This doesn't change the complexity, but is something of which to be aware.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T12:44:28.677",
"Id": "229310",
"ParentId": "229308",
"Score": "10"
}
},
{
"body": "<p>Java doesn't handle recursion very well. And by not very well I mean it should be avoided almost every time where you cannot limit the depth to something small. To show you how bad it is let's take a look at this simple program:</p>\n\n<pre><code>public static void main(String[] args) {\n for(int n = 0; n < 100_000; n+=100) {\n List<Integer> list = new ArrayList<>();\n for(int i = 0; i < n; i++) {\n list.add(i);\n }\n reverse(list);\n System.out.println(n);\n }\n}\n</code></pre>\n\n<p>At some point in the output we can see this:</p>\n\n<pre><code>17800\n17900\nException in thread \"main\" java.lang.StackOverflowError\nat slowness.SlowApp.reverse(SlowApp.java:24)\nat slowness.SlowApp.reverse(SlowApp.java:24)\n</code></pre>\n\n<p>This means that on my machine with default settings I can't even handle a list of 18000 integers. Any list bigger than that just crashes the program.</p>\n\n<p>Is it possible to do it without recursion then?</p>\n\n<p>This has proven a little trickier than I expected when I started writing this answer.</p>\n\n<p>I was thinking of 2 possible approaches. </p>\n\n<p>One is to always update the list in place. Just take the last element from the list and insert it into the correct spot (insert at 0, next insert at 1, next ...). Since we don't know which kind of List we are working with this could be a really expensive operation.</p>\n\n<p>The other approach is to first take a copy of all the elements. Then clear the input list. Reverse the copied elements and insert them back into the input list. The main advantage here is that we can copy them into an array which allows O(1) access to each element even for updating them.</p>\n\n<p>An example implementation is then:</p>\n\n<pre><code>public static <T> void reverse2(List<T> list) {\n T[] array = (T[]) list.toArray();\n\n list.clear();\n\n for(int i = 0; i < array.length/2; i++) {\n T temp = array[i];\n array[i] = array[array.length - i-1];\n array[array.length-i-1] = temp;\n }\n\n for(T item : array) {\n list.add(item);\n }\n}\n</code></pre>\n\n<p>This implementation has no issue with a List of a million Integers.</p>\n\n<p>Edit: just inserting backwards was too obvious after I tried to use list.addAll(aray) which didn't work (needs collection, not an array). I'll leave the current implementation as-is in my answer.</p>\n\n<p>Note that this also isn't the most efficient way. I highly advise you to look at the implementation of the internal Collection.reverse to see a better way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T14:15:17.733",
"Id": "445949",
"Score": "0",
"body": "Argh, done it again. I keep forgetting `List` is an interface in Java... @CristianIacob this should probably be the answer, because it isn't wrong and is more general (I'll address that first part in mine presently...)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T14:18:55.647",
"Id": "445950",
"Score": "1",
"body": "Note that the OP did specify that they don't want to use other collections."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T14:23:47.650",
"Id": "445952",
"Score": "2",
"body": "@VisualMelon I interpreted that as \"don't use collections.reverse, implement it yourself\". Otherwise you couldn't even use *add* or *remove*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T00:41:50.837",
"Id": "446051",
"Score": "0",
"body": "Is `for (int i = array.length - 1; i >= 0; i--) { list.add(array[i]); }` (backwards iteration + add) different than the 1.5x iteration?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T05:54:31.770",
"Id": "446070",
"Score": "2",
"body": "why do you bother reversing the array, rather than just inserting in reverse order?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T06:06:01.807",
"Id": "446071",
"Score": "0",
"body": "@IvanGarcíaTopete it is obviously better ... but both are O(n) time complexity so it doesn't make too much of a difference. My example implementation is clearly far from perfect. Note that the collectitons.reverse does even better :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T17:29:25.157",
"Id": "446174",
"Score": "0",
"body": "Just tested it with a list with 1,000,000 items a 1,000,000 times with each method, there's just 1 second of difference so yes, it doesn't make too much of a difference"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T14:10:07.337",
"Id": "229318",
"ParentId": "229308",
"Score": "10"
}
},
{
"body": "<p>Already answered, but as <em>task</em>, one probably fares better with not introducing too many extra structures.</p>\n\n<p>I'll immediately give an iterative version. It shows some improvements that could also be made to your recursive solution.</p>\n\n<p>The recursive solution is fine, though seemingly needing a call stack the size of the list. However tail-recursion can be optimized by a good compiler (made iterative).\nThe iterative version needs an extra variable to hold a temporary result (the recursive call's result).</p>\n\n<pre><code>public static <T> void reverse(List<T> list) {\n if (list.size() > 1) { // Not needed, heuristic optimisation\n //List<T> reversed = new ArrayList<>(list.size());\n List<T> reversed = new LinkedList<>();\n while (!list.isEmpty()) { // Or list.size() > 1\n T t = list.remove(0);\n reversed.add(t);\n }\n list.addAll(reversed);\n }\n}\n</code></pre>\n\n<blockquote>\n <p>I want to know if this is an efficient way of reversing a list</p>\n</blockquote>\n\n<p>Already answered by others, but it could be astonishly good.\nNicer would be if the <code>list</code> was not modified <em>in-situ</em>, but substituted by a new List,\nas then the <code>list.addAll(reversed)</code> could be exchanged for <code>return reversed;</code>.</p>\n\n<blockquote>\n <p>Is this working for every list as input?</p>\n</blockquote>\n\n<p>Yes, though the list must not be operated upon at the same time.</p>\n\n<p>There are some lists, immutable lists (that are not allowed to be changed) or lists that are backed by arrays (strudcturally immutable), that will throw an error.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T11:03:56.440",
"Id": "229367",
"ParentId": "229308",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229318",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T12:21:27.340",
"Id": "229308",
"Score": "5",
"Tags": [
"java",
"reinventing-the-wheel",
"collections"
],
"Title": "reverse a list of generic type"
}
|
229308
|
<h1>An Algorithm For Scheduling Your Time</h1>
<p>There is a strong body of research in cognitive science which has large implications for how best to plan your day to get the most out of it. However, it isn't practical for everyone to understand it, keep on up to date on recent findings, weigh up the relative importance of different principles, then apply them to optimally plan their day. What if there was an algorithm which could do it for you?</p>
<p>This is my first attempt at the first peice of the puzze: how to go about algorithmically scheduling a day? The literature on scheduling mainly addresses the following variables: activity duration, activity order, what time to perform an activity relative to your circadium rhymthms. I present an attempt to integrate these types of infomation into a cost function, represent schedules mathematically, then optimise schedules according to the cost function.</p>
<p>(At the moment, the GA uses a contrived cost-function designed to produce a clear optimal solution against which the algorithm's outputs can be compared, no real world data is incorperated yet.)</p>
<p>I'm looking for big picture advice on the approach I've taken, but I'd also be very grateful for information about errors I've made in the execution of my approach. This is my first ever python project, so I'm sure there are plenty of mistakes. With that in mind, it would be extremely useful to me if anyone could identify systematic errors in my thinking.</p>
<h2>Dependencies and global variables</h2>
<pre class="lang-py prettyprint-override"><code>from collections import Counter
import statistics as stat
import random as random
import numpy as np
import operator
import pandas as pd
import matplotlib.pyplot as plt
import pdb
</code></pre>
<pre class="lang-py prettyprint-override"><code>numActivities = 8
popSize = 500
eliteSize = 4
mutationRate = 0.08
generations = 200
numDurationGenes = 8 # This should be equal to number of ST genes
</code></pre>
<p>Thus far, these have been the values with which have most reliably produced good schedules. To test it using more than eight activities, first delete all line featuring the word "custom" then run as normal. Those modules which aren't called directly are included because they are very useful for debugging or analysing populations of candidate solutions.</p>
<h2>Representing Activities, Time, and How They Interact</h2>
<pre class="lang-py prettyprint-override"><code>quantaDuration = 5 # each block of time is equal to 5 mins long
hoursPerDayToSchedule = 12
dailyQuanta = int(60 * 24 * (hoursPerDayToSchedule / 24) / quantaDuration)
</code></pre>
<p>The algorithm divides a time period into 5 minute quanta, so named because they are the fundamental unit of time. However, unlike the vast majority of scheduling algorithms I've seen, this algorithm's computerational complexity scales nicely with the number of quanta so one can efficiently achieve a high granularity of time. </p>
<pre class="lang-py prettyprint-override"><code>activitiesInteractionList = []
for i in range(0, numActivities**2):
activitiesInteractionList.append(random.randint(1, 10))
activitiesInteractionMatrix = np.array(activitiesInteractionList).reshape(
[numActivities, numActivities])
activitiesInteractionMatrix
</code></pre>
<pre><code>array([[ 1, 4, 5, 7, 7, 5, 2, 8],
[ 9, 8, 5, 5, 2, 7, 10, 5],
[ 4, 4, 4, 9, 4, 2, 3, 6],
[ 5, 8, 1, 8, 8, 8, 7, 10],
[10, 5, 1, 8, 8, 8, 8, 2],
[ 2, 8, 7, 2, 8, 5, 3, 7],
[ 6, 2, 5, 10, 4, 2, 8, 7],
[ 5, 9, 2, 9, 1, 7, 5, 5]])
</code></pre>
<p>This generates a numpy array consisting of random integers such that index x,y represents the cost associated with activity x preceeding activity y. This exists purely as a placeholder which can be replaced with something more complex representing real world data</p>
<pre class="lang-py prettyprint-override"><code>timesOfDay = ["morning", "mid-day", "afternoon", "night"]
activityTimeInteractionList = []
for i in range(0, numActivities * len(timesOfDay)):
activityTimeInteractionList.append(random.randint(1, 10) / 10)
activityTimeInteractionMatrix = np.array(
activityTimeInteractionList).reshape(numActivities, len(timesOfDay))
activityTimeInteractionMatrix
</code></pre>
<pre><code>array([[0.4, 0.3, 0.2, 0.3],
[0.9, 0.1, 0.8, 0.7],
[0.3, 1. , 0.2, 0.1],
[0.1, 0.9, 0.5, 0.6],
[1. , 0.7, 0.7, 0.3],
[0.8, 0.2, 0.7, 0.9],
[0.1, 0.2, 0.7, 0.8],
[0.9, 0.4, 0.7, 0.4]])
</code></pre>
<p>For now, four time periods are considered, each of equal aproximately length. An array is created such that index [x,y] corresponds to the cost associated with scheduling a quanta of activity x during time period y</p>
<pre class="lang-py prettyprint-override"><code>quantaClassificationsPrecursor = []
quantaClassifications = []
for i in range(len(timesOfDay)):
quantaClassificationsPrecursor.append(
(int(dailyQuanta // len(timesOfDay)) * [i])) # this creates a compound list
for i in range(len(timesOfDay)): # this flattens the aforementioned list
quantaClassifications = quantaClassifications + \
quantaClassificationsPrecursor[i]
# fixes imperfect divisions by extending last time period to cover remainder
while len(quantaClassifications) < dailyQuanta:
quantaClassifications = quantaClassifications + [len(timesOfDay) - 1]
# using this algo, last time period can only exceed others by
# len(timesOfDay) -1 quanta
</code></pre>
<p>To capture the fact that it is worse to mischedule long tasks, cost is attributed on a per quanta basis. quantaClassifications is a list created such that index [x] will return the period of time (i.e. morning, mid-day, afternoon, night) that the quanta is classified as belonging to.</p>
<pre class="lang-py prettyprint-override"><code>customActivitiesInteractionMatrix=np.zeros([8,8])
customActivitiesInteractionMatrix[0,]=np.array([0,0,5,10,15,20,25,30])
customActivitiesInteractionMatrix[1,]=np.array([0,0,0,5,10,15,20,25])
customActivitiesInteractionMatrix[2,]=np.array([5,0,0,0,5,10,15,20])
customActivitiesInteractionMatrix[3,]=np.array([10,5,0,0,0,5,10,15])
customActivitiesInteractionMatrix[4,]=np.array([15,10,5,0,0,0,5,10])
customActivitiesInteractionMatrix[5,]=np.array([20,15,10,5,0,0,0,5])
customActivitiesInteractionMatrix[6,]=np.array([25,20,15,10,5,0,0,0])
customActivitiesInteractionMatrix[7,]=np.array([30,25,15,10,5,0,0,0])
activitiesInteractionMatrix=customActivitiesInteractionMatrix
activitiesInteractionMatrix
</code></pre>
<pre><code>array([[ 0., 0., 5., 10., 15., 20., 25., 30.],
[ 0., 0., 0., 5., 10., 15., 20., 25.],
[ 5., 0., 0., 0., 5., 10., 15., 20.],
[10., 5., 0., 0., 0., 5., 10., 15.],
[15., 10., 5., 0., 0., 0., 5., 10.],
[20., 15., 10., 5., 0., 0., 0., 5.],
[25., 20., 15., 10., 5., 0., 0., 0.],
[30., 25., 15., 10., 5., 0., 0., 0.]])
</code></pre>
<p>This matrix is designed to produce an ideal session order of 0,1,2,3,4,5,6,7. I choose this order as it is easy to verfiy visually when inspecting scheudules. The same is true of the below matrix which covers the interaction between time of day and an activity. It overwrites the randomly generated version for demonstration puposes. To replace with your own custom version, alter the matrix. To use random values, delete this and every line featuring the word "custom". </p>
<pre class="lang-py prettyprint-override"><code>customActivityTimeInteractionMatrix= np.zeros([8,len(timesOfDay)])
customActivityTimeInteractionMatrix[0,] = np.array([0,3,6,9])
customActivityTimeInteractionMatrix[1,] = np.array([0,3,6,9])
customActivityTimeInteractionMatrix[2,] = np.array([3,0,3,6])
customActivityTimeInteractionMatrix[3,] = np.array([3,0,3,6])
customActivityTimeInteractionMatrix[4,] = np.array([6,3,0,3])
customActivityTimeInteractionMatrix[5,] = np.array([6,3,0,3])
customActivityTimeInteractionMatrix[6,] = np.array([9,6,3,0])
customActivityTimeInteractionMatrix[7,] = np.array([9,6,3,0])
customActivityTimeInteractionMatrix=customActivityTimeInteractionMatrix/10
activityTimeInteractionMatrix= customActivityTimeInteractionMatrix
activityTimeInteractionMatrix
</code></pre>
<pre><code>array([[0. , 0.3, 0.6, 0.9],
[0. , 0.3, 0.6, 0.9],
[0.3, 0. , 0.3, 0.6],
[0.3, 0. , 0.3, 0.6],
[0.6, 0.3, 0. , 0.3],
[0.6, 0.3, 0. , 0.3],
[0.9, 0.6, 0.3, 0. ],
[0.9, 0.6, 0.3, 0. ]])
</code></pre>
<p>The index a, b gives the cost of scheduling a quanta of activity a during time period b.</p>
<h2>Class and Method Overview</h2>
<pre class="lang-py prettyprint-override"><code>
class Schedule:
def __init__(self, durationGenes, startTimeGenes):
self.durationGenes = durationGenes
self.startTimeGenes = startTimeGenes
self.list = ScheduleListGenerator(durationGenes=self.durationGenes,
startTimeGenes=self.startTimeGenes)
</code></pre>
<p>For the purpose of minimising the number of variables to be optimised, I chose to represent a block of scheduled activity as a start time, a duration, and an index. The index indicates which activity is being scheduled. e.g. activity 1 will begin at Schedule.startTimeGenes[1] and last for a total of Schedule.durationGenes[1] quanta.</p>
<pre class="lang-py prettyprint-override"><code> def ExtractSessionInfomation(self):
sessionOrder = []
for i in self.list:
if i == "-":
pass
else:
sessionOrder.append(i)
break
sessionChangeQuanta = []
sameCounter = 0
changeCounter = 0
sessionLengthsChronological = []
for i in range(0, len(self.list)):
if self.list[i] == "-":
continue
elif self.list[i - 1] == self.list[i]:
sameCounter = sameCounter + 1
else:
changeCounter = changeCounter + 1
sessionLengthsChronological.append(sameCounter + 1)
sameCounter = 0
sessionOrder.append(self.list[i])
sessionChangeQuanta.append(i)
sessionLengthsChronological.append(sameCounter + 1)
numSessions = changeCounter + 1
sessionLengthsChronological.pop(0)
sessionOrder.pop(0)
self.sessionOrder = sessionOrder
self.sessionLengthsChronological = sessionLengthsChronological
self.sessionChangeQuanta = sessionChangeQuanta
</code></pre>
<p>Many crucial methods belonging to this class depend upon knowing the order in which activities are scheduled and how long each activity is scheduled for. This method extracts and stores that infomation as attributes. One session is defined as a succession of quanta dedicated exclusively to one activity. They appear on schedules as many of the same number in an uninterupted chain.</p>
<pre class="lang-py prettyprint-override"><code> def CalculateOrderCosts(self):
sessionOrderCosts = []
for i in range(0, len(self.sessionOrder) - 1):
sessionOrderCosts.append(
activitiesInteractionMatrix[self.sessionOrder[i], self.sessionOrder[i + 1]])
self.sessionOrderCosts = sessionOrderCosts
self.SessionOrderCostTotal = sum(sessionOrderCosts)
def CaclulateTimeOfDayCosts(self):
timeOfDayCostsByActivity = []
for i in range(0, len(self.list)):
if self.list[i] == "-":
timeOfDayCostsByActivity.append(0)
else:
timeOfDayCostsByActivity.append(
activityTimeInteractionMatrix[self.list[i], quantaClassifications[i]])
self.timeOfDayCostsByActivity = timeOfDayCostsByActivity
self.timeOfDayCostByActivityTotal = sum(timeOfDayCostsByActivity)
</code></pre>
<p>These methods exploit the properties of the matrices created above to calculate the cost associated with the timing of activities</p>
<pre class="lang-py prettyprint-override"><code>
def CalculateSessionLengthCosts(self):
sessionLengthsCosts = []
for i in self.sessionLengthsChronological:
if i < 18:
sessionLengthsCosts.append((18 - i) * 5)
else:
sessionLengthsCosts.append(0)
self.sessionLengthCosts = sessionLengthsCosts
self.sessionLengthCostsTotal = sum(sessionLengthsCosts)
</code></pre>
<p>For ease of visualising the ideal solution when viewing candidates solutions proposed by the algorithm, the cost function demands that all each of the eight activities take up precisely one eighth of the schedule. This could later be adapted to consider the relative importance of tasks, and to deal with different ideal task lengths.</p>
<pre class="lang-py prettyprint-override"><code> def CalculateTotalCosts(self):
self.ExtractSessionInfomation()
self.CaclulateTimeOfDayCosts()
self.CalculateOrderCosts()
self.CalculateSessionLengthCosts()
# self.CalculateOpportunityCost()
self.CalculateExclusionCosts()
self.suboptimality = (
self.SessionOrderCostTotal +
self.timeOfDayCostByActivityTotal +
self.sessionLengthCostsTotal +
# self.opportunityCost +
self.exclusionCostsTotal)
def FillerSoThatAboveFunctionIsntAtEndOfClassDefinition(self):
pass # exists to prevent silent misindentation errors
</code></pre>
<p>The nature of the rest of the cost calculating methods shown so far causes the algorithm to schedule as few activities per day. CalculateExclusionCosts is designed to counter that.</p>
<p>CalculateTotalCosts acts as a way of calling all cost related methods in a single line of code.</p>
<p>There is an error in the above class definition which causes the last-defined method to break. I wasn't able to find it, so I included a filler method to protect CalculateTotalCosts()</p>
<h2>The Core of the Algorithm</h2>
<pre class="lang-py prettyprint-override"><code>def GenerateRandomStartTimeGenes():
randomStartTimeGenes = np.zeros([numActivities], dtype=int)
for i in range(numActivities):
randomStartTimeGenes[i] = round(random.uniform(0, dailyQuanta), 0)
return (randomStartTimeGenes)
def GenerateRandomDurationGenes():
randomDurationGenes = np.zeros([numActivities], dtype=int)
for i in range(numActivities):
randomDurationGenes[i] = round(random.uniform(5, 40), 0)
return randomDurationGenes
</code></pre>
<p>These generate random genes. They are called when creating the initial population, and every time a mutation is made.</p>
<p>It is this representation of time which allows for computationally efficient optimisation despite high time granularity, because it maximally reduces the number of variables to be optimised per item to be scheduled.</p>
<p>The arguments inside random.uniform() are chosen to reduce the number of very bad genes within the pool. </p>
<pre class="lang-py prettyprint-override"><code>def ScheduleListGenerator(durationGenes, startTimeGenes):
schedule = ["-"] * dailyQuanta
for g in range(startTimeGenes.size):
indiciesToChange = range(
startTimeGenes[g],
startTimeGenes[g] +
durationGenes[g])
for i in indiciesToChange:
if i > dailyQuanta -1:
break
else:
schedule[i] = g
return(schedule)
</code></pre>
<p>This function generates schedules in the form of lists. It locates the first quanta of a session, then changes it to a number which corresponds to the number representing the activity to be scheduled. It then changes the next element downstream to the same number, and repeats this until the duration of the session matches the value given by it's corresponding duration gene.</p>
<pre class="lang-py prettyprint-override"><code>def GenerateInitialPopulation(popSize):
initialPopulation = []
for i in range(popSize):
initialPopulation.append(
Schedule(
durationGenes=GenerateRandomDurationGenes(),
startTimeGenes=GenerateRandomStartTimeGenes()))
initialPopulation[i].index = i
return(initialPopulation)
</code></pre>
<p>This produces randomised genes, uses those to create a schedule object, and repeats until a population of the desired size is achieved.</p>
<pre class="lang-py prettyprint-override"><code>def CalculatePopulationSuboptimalities(population):
for i in population:
i.CalculateTotalCosts()
def SortPopulation(pop):
pop.sort(key=lambda x: x.suboptimality,
reverse=False) # sort population by suboptimality
return(pop)
</code></pre>
<p>Once an initial population is generated, the list is sorted by it's suboptimality (the lesser the index, the lesser the suboptimality). This comes in handy for the tournament selection function shown below and makes it simple to extract the best schedule within each generation for comparison purposes (using population[0].list).</p>
<pre class="lang-py prettyprint-override"><code>
def Selection(sortedPopulation): # uses tournament selection
selectionResults = []
for i in range(eliteSize):
selectionResults.append(sortedPopulation[i])
for i in range(eliteSize, popSize):
# returns a list with 2 random integers
a = random.sample(range(popSize), 2)
if a[0] < a[1]:
selectionResults.append(sortedPopulation[a[0]])
else:
selectionResults.append(sortedPopulation[a[1]])
return(selectionResults)
</code></pre>
<p>As the population is already sorted by suboptimality, it's possible to implement tournament selection (randomly paired schedules "fight", only the winner, i.e. the one with the lowest suboptimalitiy, passes on their genes) by simply comparing the indices of combatants. </p>
<pre class="lang-py prettyprint-override"><code>def Breed(selectedPopulation):
matingPool = selectedPopulation[eliteSize:popSize]
children = []
breedingPartnersInOrder = random.sample(matingPool, len(matingPool))
for i in range(
len(matingPool)): # for every in the mating pool, choose another at randomu
parent1DurationGenes = matingPool[i].durationGenes
parent1StartTimeGenes = matingPool[i].startTimeGenes
parent2DurationGenes = breedingPartnersInOrder[i].durationGenes
parent2StartTimeGenes = breedingPartnersInOrder[i].startTimeGenes
childDurationGenes = np.zeros(numDurationGenes, dtype=int)
childStartTimeGenes = np.zeros(numDurationGenes, dtype=int)
for d in range(
numDurationGenes): # for every gene pair, decide at random which parents genes
p = random.sample(range(1, 3), 1) # to use in the next generation
if p == 1:
childDurationGenes[d] = parent1DurationGenes[d]
childStartTimeGenes[d] = parent1StartTimeGenes[d]
else:
childDurationGenes[d] = parent2DurationGenes[d]
childStartTimeGenes[d] = parent2StartTimeGenes[d]
# create a new entity per set of child genes
children.append(Schedule(childDurationGenes, childStartTimeGenes))
return (children)
</code></pre>
<p>The breeding step, sometimes referred to as "crossing over", is the use of the selected parents genes to create the next generation. Every schedule within the mating pool produces one offspring by "mating" with another member of the mating pool at random. I use a random "sample" of size equal to that of the mating pool, as this generates a new list in random order representing the same population. This allows for mating to be performed randomly, which I believe is better than mating the best with the best (i.e. selective breeding) as it leads more diverse resultant populations which are better able to escape local minima.</p>
<pre class="lang-py prettyprint-override"><code>def Mutate(population, mutationRate=mutationRate):
numberOfGenesToMutatePerType = int(
round(mutationRate * numDurationGenes * popSize))
for d in range(numberOfGenesToMutatePerType):
indexOfAnimalToMutate = random.sample(range(eliteSize, len(population)), 1)
geneMutationIndex = random.sample(range(numDurationGenes), 1)
population[indexOfAnimalToMutate[0]].durationGenes[geneMutationIndex[0]] = GenerateRandomDurationGenes()[
geneMutationIndex[0]]
for ST in range(numberOfGenesToMutatePerType):
indexOfAnimalToMutate = random.sample(
range(eliteSize, len(population)), 1)
geneMutationIndex = random.sample(range(numDurationGenes), 1)
population[indexOfAnimalToMutate[0]].startTimeGenes[geneMutationIndex[0]] = GenerateRandomStartTimeGenes()[
geneMutationIndex[0]]
return(population)
</code></pre>
<p>The mutation step exists to increase the diversity of the resultant generation. I chose to equally distribute mutations between start-time and duration genes because I couldn't see any reason not to. In hindsight, if the startTime or duration genes are already very close to perfect, but the other type were weak, it would be more useful to have an uneven distribution of mutations between gene types as that way some of the mutants would only see changes to the weak genes (leaving the near perfect genes intact). This will be verified then fixed in my next draft.</p>
<pre class="lang-py prettyprint-override"><code>def IndexAdder(population):
for i in range(len(population)):
population[i].index = i
return (population)
</code></pre>
<p>The index of populations are absent in children. This exists to add them. While these index attributes aren't required for the algorithm to function, it is useful to have if you want to see the before and after of a schedule while testing a function which involves rearranging the population as it allows you to query a resultant schedule for the index of its precursor. </p>
<pre class="lang-py prettyprint-override"><code>
def GeneticAlgorithm(
initialPopulation = initialPopulation,
popSize = popSize,
eliteSize = eliteSize,
mutationRate = mutationRate,
generations = generations):
global progress
population = initialPopulation
for i in range(generations):
for p in population:
p.CalculateTotalCosts()
population = SortPopulation(population)
progress.append(population[0].suboptimality)
selectedPopulation = Selection(population)
newGenerationPreMutation = Breed(
selectedPopulation) + selectedPopulation[0:eliteSize]
population = Mutate(newGenerationPreMutation)
return(population)
</code></pre>
<p>This calls every step in order and iterates for the desired number of generations. With every generation it appends a list with the suboptimality of the best schedule within a population, and this list can be used to visualise how schedule quality improved with each generation.</p>
<pre class="lang-py prettyprint-override"><code>initialPopulation = GenerateInitialPopulation(popSize)
finalGeneration = GeneticAlgorithm(initialPopulation)
for i in finalGeneration:
i.CalculateTotalCosts()
plt.plot(progress)
plt.show()
progress = []
sortedFinalGeneration=SortPopulation(finalGeneration)
sortedFinalGeneration[0].list
</code></pre>
<p>This runs the genetic algorithm, and opens a window featuring a graph of schedule quality vs time, then shows you the best solution found.</p>
<pre><code>from collections import Counter
import statistics as stat
import random as random
import numpy as np
import operator
import pandas as pd
import matplotlib.pyplot as plt
import pdb
numActivities = 8
popSize = 100
eliteSize = 4
mutationRate = 0.04
generations = 100
numDurationGenes = 8 # This should be equal to number of ST genes
quantaDuration = 5 # each block of time is equal to 5 mins long
hoursPerDayToSchedule = 12
dailyQuanta = int(60 * 24 * (hoursPerDayToSchedule / 24) / quantaDuration)
activitiesInteractionList = []
for i in range(0, numActivities**2):
activitiesInteractionList.append(random.randint(1, 10))
activitiesInteractionMatrix = np.array(activitiesInteractionList).reshape(
[numActivities, numActivities])
timesOfDay = ["morning", "mid-day", "afternoon", "night"]
activityTimeInteractionList = []
for i in range(0, numActivities * len(timesOfDay)):
activityTimeInteractionList.append(random.randint(1, 10) / 10)
activityTimeInteractionMatrix = np.array(
activityTimeInteractionList).reshape(numActivities, len(timesOfDay))
quantaClassificationsPrecursor = []
quantaClassifications = []
for i in range(len(timesOfDay)):
quantaClassificationsPrecursor.append(
(int(dailyQuanta // len(timesOfDay)) * [i])) # this creates a compound list
for i in range(len(timesOfDay)): # this flattens the aforementioned list
quantaClassifications = quantaClassifications + \
quantaClassificationsPrecursor[i]
# fixes imperfect divisions by extending last time period to cover remainder
while len(quantaClassifications) < dailyQuanta:
quantaClassifications = quantaClassifications + [len(timesOfDay) - 1]
# using this algo, last time period can only exceed others by
# len(timesOfDay) -1 quanta
customActivitiesInteractionMatrix = np.zeros([8, 8])
customActivitiesInteractionMatrix[0, ] = np.array(
[0, 0, 5, 10, 15, 20, 25, 30])
customActivitiesInteractionMatrix[1, ] = np.array([0, 0, 0, 5, 10, 15, 20, 25])
customActivitiesInteractionMatrix[2, ] = np.array([5, 0, 0, 0, 5, 10, 15, 20])
customActivitiesInteractionMatrix[3, ] = np.array([10, 5, 0, 0, 0, 5, 10, 15])
customActivitiesInteractionMatrix[4, ] = np.array([15, 10, 5, 0, 0, 0, 5, 10])
customActivitiesInteractionMatrix[5, ] = np.array([20, 15, 10, 5, 0, 0, 0, 5])
customActivitiesInteractionMatrix[6, ] = np.array([25, 20, 15, 10, 5, 0, 0, 0])
customActivitiesInteractionMatrix[7, ] = np.array([30, 25, 15, 10, 5, 0, 0, 0])
activitiesInteractionMatrix = customActivitiesInteractionMatrix
customActivityTimeInteractionMatrix = np.zeros([8, len(timesOfDay)])
customActivityTimeInteractionMatrix[0, ] = np.array([0, 3, 6, 9])
customActivityTimeInteractionMatrix[1, ] = np.array([0, 3, 6, 9])
customActivityTimeInteractionMatrix[2, ] = np.array([3, 0, 3, 6])
customActivityTimeInteractionMatrix[3, ] = np.array([3, 0, 3, 6])
customActivityTimeInteractionMatrix[4, ] = np.array([6, 3, 0, 3])
customActivityTimeInteractionMatrix[5, ] = np.array([6, 3, 0, 3])
customActivityTimeInteractionMatrix[6, ] = np.array([9, 6, 3, 0])
customActivityTimeInteractionMatrix[7, ] = np.array([9, 6, 3, 0])
customActivityTimeInteractionMatrix = customActivityTimeInteractionMatrix / 10
activityTimeInteractionMatrix = customActivityTimeInteractionMatrix
class Schedule:
def __init__(self, durationGenes, startTimeGenes):
self.durationGenes = durationGenes
self.startTimeGenes = startTimeGenes
self.list = ScheduleListGenerator(durationGenes=self.durationGenes,
startTimeGenes=self.startTimeGenes)
def ExtractSessionInfomation(self):
sessionOrder = []
for i in self.list:
if i == "-":
pass
else:
sessionOrder.append(i)
break
sessionChangeQuanta = []
sameCounter = 0
changeCounter = 0
sessionLengthsChronological = []
for i in range(0, len(self.list)):
if self.list[i] == "-":
continue
elif self.list[i - 1] == self.list[i]:
sameCounter = sameCounter + 1
else:
changeCounter = changeCounter + 1
sessionLengthsChronological.append(sameCounter + 1)
sameCounter = 0
sessionOrder.append(self.list[i])
sessionChangeQuanta.append(i)
sessionLengthsChronological.append(sameCounter + 1)
numSessions = changeCounter + 1
sessionLengthsChronological.pop(0)
sessionOrder.pop(0)
self.sessionOrder = sessionOrder
self.sessionLengthsChronological = sessionLengthsChronological
self.sessionChangeQuanta = sessionChangeQuanta
def CalculateOrderCosts(self):
sessionOrderCosts = []
for i in range(0, len(self.sessionOrder) - 1):
sessionOrderCosts.append(
activitiesInteractionMatrix[self.sessionOrder[i],
self.sessionOrder[i + 1]])
self.sessionOrderCosts = sessionOrderCosts
self.SessionOrderCostTotal = sum(sessionOrderCosts)
def CaclulateTimeOfDayCosts(self):
timeOfDayCostsByActivity = []
for i in range(0, len(self.list)):
if self.list[i] == "-":
timeOfDayCostsByActivity.append(0)
else:
timeOfDayCostsByActivity.append(
activityTimeInteractionMatrix[self.list[i], quantaClassifications[i]])
self.timeOfDayCostsByActivity = timeOfDayCostsByActivity
self.timeOfDayCostByActivityTotal = sum(timeOfDayCostsByActivity)
def CalculateSessionLengthCosts(self):
sessionLengthsCosts = []
for i in self.sessionLengthsChronological:
if i < 18:
sessionLengthsCosts.append((18 - i) * 5)
else:
sessionLengthsCosts.append(0)
self.sessionLengthCosts = sessionLengthsCosts
self.sessionLengthCostsTotal = sum(sessionLengthsCosts)
# def CalculateOpportunityCost(self):
# self.opportunityCost = Counter(self.list)["-"] * 10
def CalculateExclusionCosts(self):
exclusionCosts = []
for i in range(numActivities):
if Counter(self.list)[i] < 1:
exclusionCosts.append(100)
else:
continue
self.exclusionCosts = exclusionCosts
self.exclusionCostsTotal = sum(exclusionCosts)
def CalculateTotalCosts(self):
self.ExtractSessionInfomation()
self.CaclulateTimeOfDayCosts()
self.CalculateOrderCosts()
self.CalculateSessionLengthCosts()
# self.CalculateOpportunityCost()
self.CalculateExclusionCosts()
self.suboptimality = (
self.SessionOrderCostTotal +
self.timeOfDayCostByActivityTotal +
self.sessionLengthCostsTotal +
# self.opportunityCost +
self.exclusionCostsTotal)
def FillerSoThatAboveFunctionIsntAtEndOfClassDefinition(self):
pass # exists to prevent silent misindentation errors
def GenerateRandomStartTimeGenes():
randomStartTimeGenes = np.zeros([numActivities], dtype=int)
for i in range(numActivities):
randomStartTimeGenes[i] = round(random.uniform(0, dailyQuanta - 4), 0)
return (randomStartTimeGenes)
def GenerateRandomDurationGenes():
randomDurationGenes = np.zeros([numActivities], dtype=int)
for i in range(numActivities):
randomDurationGenes[i] = round(random.uniform(4, 40), 0)
return randomDurationGenes
def ScheduleListGenerator(durationGenes, startTimeGenes):
schedule = ["-"] * dailyQuanta
for g in range(startTimeGenes.size):
indiciesToChange = range(
startTimeGenes[g],
startTimeGenes[g] +
durationGenes[g])
for i in indiciesToChange:
if i > dailyQuanta - 1:
break
else:
schedule[i] = g
return(schedule)
def GenerateInitialPopulation(popSize):
initialPopulation = []
for i in range(popSize):
initialPopulation.append(
Schedule(
durationGenes=GenerateRandomDurationGenes(),
startTimeGenes=GenerateRandomStartTimeGenes()))
# initialPopulation[i].index = i
return(initialPopulation)
def CalculatePopulationSuboptimalities(population):
for i in population:
i.CalculateTotalCosts()
def SortPopulation(pop):
pop.sort(key=lambda x: x.suboptimality,
reverse=False) # sort population by suboptimality
return(pop)
def Selection(sortedPopulation): # uses tournament selection
selectionResults = []
for i in range(eliteSize):
selectionResults.append(sortedPopulation[i])
for i in range(eliteSize, popSize):
# returns a list with 2 random integers
a = random.sample(range(popSize), 2)
if a[0] < a[1]:
selectionResults.append(sortedPopulation[a[0]])
else:
selectionResults.append(sortedPopulation[a[1]])
return(selectionResults)
def Breed(selectedPopulation):
matingPool = selectedPopulation[eliteSize:popSize]
children = []
breedingPartnersInOrder = random.sample(matingPool, len(matingPool))
for i in range(
len(matingPool)): # for every in the mating pool, choose another at randomu
parent1DurationGenes = matingPool[i].durationGenes
parent1StartTimeGenes = matingPool[i].startTimeGenes
parent2DurationGenes = breedingPartnersInOrder[i].durationGenes
parent2StartTimeGenes = breedingPartnersInOrder[i].startTimeGenes
childDurationGenes = np.zeros(numDurationGenes, dtype=int)
childStartTimeGenes = np.zeros(numDurationGenes, dtype=int)
for d in range(
numDurationGenes): # for every gene pair, decide at random which parents genes
p = random.sample(range(1, 3), 1) # to use in the next generation
if p == 1:
childDurationGenes[d] = parent1DurationGenes[d]
childStartTimeGenes[d] = parent1StartTimeGenes[d]
else:
childDurationGenes[d] = parent2DurationGenes[d]
childStartTimeGenes[d] = parent2StartTimeGenes[d]
# create a new entity per set of child genes
children.append(Schedule(childDurationGenes, childStartTimeGenes))
return (children)
def Mutate(population, mutationRate=mutationRate):
numberOfGenesToMutatePerType = int(
round(mutationRate * numDurationGenes * popSize))
for d in range(numberOfGenesToMutatePerType):
indexOfAnimalToMutate = random.sample(
range(eliteSize, len(population)), 1)
geneMutationIndex = random.sample(range(numDurationGenes), 1)
population[indexOfAnimalToMutate[0]].durationGenes[geneMutationIndex[0]
] = GenerateRandomDurationGenes()[geneMutationIndex[0]]
for ST in range(numberOfGenesToMutatePerType):
indexOfAnimalToMutate = random.sample(
range(eliteSize, len(population)), 1)
geneMutationIndex = random.sample(range(numDurationGenes), 1)
population[indexOfAnimalToMutate[0]].startTimeGenes[geneMutationIndex[0]
] = GenerateRandomStartTimeGenes()[geneMutationIndex[0]]
return(population)
#def IndexAdder(population):
# for i in range(len(population)):
# population[i].index = i
# return (population)
initialPopulation = GenerateInitialPopulation(popSize)
progress = []
def GeneticAlgorithm(
initialPopulation = initialPopulation,
popSize = popSize,
eliteSize = eliteSize,
mutationRate = mutationRate,
generations = generations):
global progress
population = initialPopulation
for i in range(generations):
for p in population:
p.CalculateTotalCosts()
population = SortPopulation(population)
progress.append(population[0].suboptimality)
selectedPopulation = Selection(population)
newGenerationPreMutation = Breed(
selectedPopulation) + selectedPopulation[0:eliteSize]
population = Mutate(newGenerationPreMutation)
return(population)
initialPopulation = GenerateInitialPopulation(popSize)
finalGeneration = GeneticAlgorithm(initialPopulation)
for i in finalGeneration:
i.CalculateTotalCosts()
plt.plot(progress)
plt.show()
progress = []
sortedFinalGeneration=SortPopulation(finalGeneration)
sortedFinalGeneration[0].list
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T13:27:13.900",
"Id": "445940",
"Score": "0",
"body": "Welcome to CodeReview! When you say `There is an error in the above class definition which causes the last-defined method to break`, if you expect community input to help fix this, CR isn't the site you need; you'd be better off posting on StackOverflow. If you can live with that bug for now, and you need a review of your code, you should instead describe what it is you're looking for in a code review - are your concerns mainly about performance, or code style, etc.?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T13:29:53.087",
"Id": "445941",
"Score": "0",
"body": "Thanks you! I didn't post this for help with the bug, I will update my post to include what specifically I'd like reviewed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T13:37:21.127",
"Id": "445943",
"Score": "3",
"body": "Your narrative is nice. It would make review easier if, at the end of your post, you show the code again in one blob."
}
] |
[
{
"body": "<h2>Formatting</h2>\n\n<p>Get an IDE or a linter that will give you hints about PEP8, Python's standard for code formatting. Among other things, it will suggest:</p>\n\n<ul>\n<li>Capital letters for your constants, e.g. <code>NUM_ACTIVITIES</code></li>\n<li>lower_camel_case for your variable and function names, e.g. <code>activity_interactions</code> instead of <code>activitiesInteractionList</code> (also note that you shouldn't usually write the type of a variable in its name)</li>\n<li><code>def CalculateOrderCosts(self):</code> becomes <code>calculate_order_costs(self):</code></li>\n<li><code>class Schedule</code> stays as it is</li>\n</ul>\n\n<h2>Order of operations</h2>\n\n<pre><code>int(60 * 24 * (hoursPerDayToSchedule / 24) / quantaDuration)\n</code></pre>\n\n<p>Not sure why the cancelling <code>24</code> terms are written there; you can drop them and use integer division, dropping the parens:</p>\n\n<pre><code>60 * hours_per_day_to_schedule // quanta_duration\n</code></pre>\n\n<h2>Vectorization</h2>\n\n<pre><code>activitiesInteractionList = []\nfor i in range(0, numActivities**2):\n activitiesInteractionList.append(random.randint(1, 10))\n</code></pre>\n\n<p>This should better-leverage numpy vectorization. See for example <a href=\"https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.rand.html\" rel=\"noreferrer\">https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.rand.html</a></p>\n\n<h2>In-place addition</h2>\n\n<pre><code>quantaClassifications = quantaClassifications + \\\n quantaClassificationsPrecursor[i]\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>quanta_classifications += quanta_classifications_precursor[i]\n</code></pre>\n\n<p>Also, this construct:</p>\n\n<pre><code>quantaClassifications = quantaClassifications + [len(timesOfDay) - 1]\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>quanta_classifications.append(len(times_of_day) - 1)\n</code></pre>\n\n<h2>Matrix assignment</h2>\n\n<pre><code>customActivitiesInteractionMatrix[0, ] = np.array(\n [0, 0, 5, 10, 15, 20, 25, 30])\ncustomActivitiesInteractionMatrix[1, ] = np.array([0, 0, 0, 5, 10, 15, 20, 25])\ncustomActivitiesInteractionMatrix[2, ] = np.array([5, 0, 0, 0, 5, 10, 15, 20])\ncustomActivitiesInteractionMatrix[3, ] = np.array([10, 5, 0, 0, 0, 5, 10, 15])\ncustomActivitiesInteractionMatrix[4, ] = np.array([15, 10, 5, 0, 0, 0, 5, 10])\ncustomActivitiesInteractionMatrix[5, ] = np.array([20, 15, 10, 5, 0, 0, 0, 5])\ncustomActivitiesInteractionMatrix[6, ] = np.array([25, 20, 15, 10, 5, 0, 0, 0])\ncustomActivitiesInteractionMatrix[7, ] = np.array([30, 25, 15, 10, 5, 0, 0, 0])\n</code></pre>\n\n<p>The right-hand side should be represented as a single two-dimensional matrix. This should then be possible with a single assignment.</p>\n\n<h2>Null <code>if</code></h2>\n\n<pre><code> if i == \"-\":\n pass\n else:\n ...\n</code></pre>\n\n<p>should just be</p>\n\n<pre><code>if i != '-':\n ...\n</code></pre>\n\n<h2>General</h2>\n\n<p>You do have some methods, but you also have a bunch of globally-scoped code, particularly for matrix setup. This should also be moved into methods. Ideally, the only thing to be found at global scope should be method and class declarations, imports, and constants.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T13:52:19.333",
"Id": "229315",
"ParentId": "229313",
"Score": "6"
}
},
{
"body": "<h3>numpy</h3>\n\n<p><code>numpy.random</code> has functions to generate random arrays. So, this: </p>\n\n<pre><code>activitiesInteractionList = []\nfor i in range(0, numActivities**2):\n activitiesInteractionList.append(random.randint(1, 10))\n\nactivitiesInteractionMatrix = np.array(activitiesInteractionList).reshape(\n [numActivities, numActivities])\n</code></pre>\n\n<p>becomes this:</p>\n\n<pre><code>activitiesInteractionMatrix = np.random.randint(1, 11, size=[numActivities, numActivities])\n</code></pre>\n\n<p>and this:</p>\n\n<pre><code>activityTimeInteractionList = []\nfor i in range(0, numActivities * len(timesOfDay)):\n activityTimeInteractionList.append(random.randint(1, 10) / 10)\n\nactivityTimeInteractionMatrix = np.array(\n activityTimeInteractionList).reshape(numActivities, len(timesOfDay))\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>activityTimeInteractionList = np.random.random(size=[numActivities, numActivities]))\nactivityTimeInteractionList = activityTimeInteractionList * (1 - .1) + .1\n</code></pre>\n\n<p><code>np.array()</code> can take a list of lists.</p>\n\n<pre><code>customActivitiesInteractionMatrix = np.array([[0,0,5,10,15,20,25,30],\n [0,0,0,5,10,15,20,25],\n [5,0,0,0,5,10,15,20],\n [10,5,0,0,0,5,10,15],\n [15,10,5,0,0,0,5,10],\n [20,15,10,5,0,0,0,5],\n [25,20,15,10,5,0,0,0],\n [30,25,15,10,5,0,0,0]])\n</code></pre>\n\n<p>If things named <code>custom...</code> are for testing, put them in a proper test, or at least put it in an <code>if</code> block so you don't need to delete them to get proper operation. You can just set TESTING to True/False to enable/disable the code:</p>\n\n<pre><code>if TESTING:\n customActivitiesInteractionMatrix = ...\n ActivitiesInteractionMatrix = customActivitiesInteractionMatrix\n etc.\n</code></pre>\n\n<h3>list.extend</h3>\n\n<p>Use the <code>extend()</code> method to add multiple elements to the end of a list.</p>\n\n<pre><code>quantaClassifications = []\nfor i in range(len(timesOfDay)):\n quantaClassifications.extend(dailyQuanta // len(timesOfDay) * [i])\n\nquantaClassifications.extend((dailyQuanta - len(quantaClassifications)) * [len(timesOfDay) - 1])\n</code></pre>\n\n<h3>list comprehension:</h3>\n\n<p>Or in this case, use a list comprehension:</p>\n\n<pre><code>quantaClassifications = [i*len(timesOfDay)//dailyQuanta for i in range(dailyQuanta)]\n</code></pre>\n\n<h3>enumerate() and zip()</h3>\n\n<p>When looping over a sequence, like a list, and the index and value are needed, it would be better to use <code>for i,value in enumerate(sequence):</code> rather than <code>for i in range(len(sequence)):</code>. To iterate over multiple sequences in parallel, use <code>zip()</code>. Use slice assignment and itertools.repeat() to eliminate an explicit loop. Like so:</p>\n\n<pre><code>def ScheduleListGenerator(durationGenes, startTimeGenes):\n schedule = [\"-\"] * dailyQuanta\n for g,(start,duration) in enumerate(durationGenes, startTimeGenes):\n end = min(start + duration, dailyQuanta))\n schedule[start:end] = itertools.repeat(g, end-start)\n\n return schedule\n</code></pre>\n\n<h3>readability</h3>\n\n<p>Code should be written to be read and understood. Descriptive names help. But, lines of code that are too long or that wrap to the next line are more difficult to read than shorter lines. So there is a balance between how descriptive a name is and how long it is. </p>\n\n<h3>misc</h3>\n\n<p><code>return</code> doesn't need parens. <code>return schedule</code> instead of <code>return(schedule)</code></p>\n\n<p>The default start for <code>range()</code> is '0', so <code>range(99)</code> is the same as <code>range(0, 99)</code>.</p>\n\n<p>Try to avoid magic numbers: <code>sessionLengthsCosts.append((18 - i) * 5)</code>. Where do the 5 and 18 come from? If the code is edited somewhere else (like the size of a data structure, or the value of <code>quantaDuration</code>) how do you know if these numbers should change? Are they used anywhere else in the code? It would be better to make them a constant, or at least add a doc string or comment to explain them.</p>\n\n<p>Short, one letter, variable names often have a customary usage or implied meaning. For example, it is common to use variables i,j,k as integer indexes, or x,y,z as floating point coordinates. When they are used for something else (e.g. <code>for i in self.list</code>) it can be confusing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T09:45:00.480",
"Id": "446250",
"Score": "0",
"body": "I chose this as the best answer because it lead to a greater reduction in the number of lines I was able to reduce from my program, and it addressed what I believed to be deeper flaws in the program. The other answer was also very good, it was close."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T20:26:15.460",
"Id": "229344",
"ParentId": "229313",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229344",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T13:20:44.507",
"Id": "229313",
"Score": "8",
"Tags": [
"python",
"genetic-algorithm"
],
"Title": "An Algorithm Which Schedules Your Life"
}
|
229313
|
<p>In my current project, I came across a scenario where there will be two sorted <code>list</code> of <code>Decimal</code> values. Let's call them <code>bucket_list</code> and <code>value_list</code></p>
<ol>
<li>Where <code>bucket_list</code> represents the sum of one or more elements from the <code>value_list</code></li>
<li><code>value_list</code> may have duplicate values</li>
<li>Every element in <code>value_list</code> should be picked only once (duplicate values are considered different elements)</li>
<li>In the end, all elements in <code>bucket_list</code> will have one or more element from <code>value_list</code> and no elements in <code>value_list</code> will be left without a mapping to <code>bucket_list</code></li>
</ol>
<p>After a lot of searches, I wrote the code with <code>backtracking</code> and <code>greedy</code>(I think). Below is the part of code that handles the part of the problem.</p>
<pre class="lang-py prettyprint-override"><code> class FindBucketMap(object):
@classmethod
def create_map_list(cls, bucket_list: list, value_list: list, bucket_map_list: list, i: int = 0):
"""
Backtracking code to find possible bucket and value pair
:param bucket_list: List of bucket values
:param value_list: List of values to map to bucket
:param bucket_map_list: List will be updated with the mapping of values from bucket_list to value_list
:param i:
:return:
"""
if i >= len(bucket_list) or len(value_list) == 0:
if i >= len(bucket_list) and len(value_list) == 0:
return True
else:
return False
bucket_map_prospect_list = []
bucket_value = bucket_list[i]
cls.create_map(bucket_value, value_list, [], bucket_map_prospect_list)
if len(bucket_map_prospect_list) == 0:
return False
for bucket_map_prospect in bucket_map_prospect_list:
temp_list = list(value_list)
for x in bucket_map_prospect:
temp_list.remove(x)
if cls.create_map_list(bucket_list, temp_list, bucket_map_list, i + 1):
bucket_map_list.append({"bucket": bucket_value, "split": bucket_map_prospect})
return True
@classmethod
def create_map(cls, value: Decimal, value_list: list, cur_list: list, map_list: list, i: int = 0):
"""
Greedy code to find list of values that matches a sum
:param value: Expected Sum
:param value_list: Possible values
:param cur_list: Processed values
:param map_list: List contains the possible combinations
:param i:
:return:
"""
if value == Decimal(0):
map_list.append(cur_list)
return
if value < Decimal(0):
return
while i < len(value_list):
if value < value_list[i]:
return
cls.create_map(value - value_list[i], value_list, cur_list + [value_list[i]], map_list, i + 1)
i += 1
</code></pre>
<p>Please give reviews on the approach and the code.</p>
<p><strong>EDIT 1:</strong></p>
<p>For a large test case ( <code>len(bucket_list) > 50</code> and <code>len(value_list) > 1000</code> ), the program almost never ends. So I changed the code to the following:</p>
<pre class="lang-py prettyprint-override"><code> class FindBucketMap(object):
@classmethod
def create_map_list(cls, bucket_list: list, value_list: list, i: int = 0):
if i >= len(bucket_list):
return True
return cls.create_map(bucket_list[i], bucket_list, value_list, [], i)
@classmethod
def create_map(cls, value: int, bucket_list: list, value_list: list, cur_list: list, i: int, j: int = 0):
if value == 0:
temp_list = list(value_list)
for x in cur_list:
temp_list.remove(x)
print(i, bucket_list[i], cur_list)
result = cls.create_map_list(bucket_list, temp_list, i + 1)
if result is True:
return [{"value": bucket_list[i], "split": cur_list}]
elif isinstance(result, list):
return result + [{"value": bucket_list[i], "split": cur_list}]
else:
return False
if len(value_list) == 0 or value < Decimal(0):
return False
while j < len(value_list):
if value < value_list[j]:
return False
result = cls.create_map(value - value_list[j], bucket_list, value_list, cur_list + [value_list[j]], i,
j + 1)
if isinstance(result, list):
return result
j += 1
return False
</code></pre>
<p>This is faster than the first but still not fast enough.</p>
|
[] |
[
{
"body": "<p>Just a couple ways to shorten your code</p>\n\n<p>This code</p>\n\n<pre><code>if i >= len(bucket_list) or len(value_list) == 0:\n if i >= len(bucket_list) and len(value_list) == 0:\n return True\n else:\n return False\n</code></pre>\n\n<p>can be written like this:</p>\n\n<pre><code>if i >= len(bucket_list) or not value_list:\n return i >= len(bucket_list) and not value_list\n</code></pre>\n\n<p>This allows you to return the boolean value this expression would evaluate too, and <code>not value_list</code> means the length of <code>value_list</code> is 0, or empty. I changed other occurances of this in your code as well.</p>\n\n<hr>\n\n<p>This code</p>\n\n<pre><code>for x in bucket_map_prospect:\n temp_list.remove(x)\n</code></pre>\n\n<p>can be written like this:</p>\n\n<pre><code>temp_list.remove(x for x in bucket_map_prospect)\n</code></pre>\n\n<p><hr>\nIf you're going to use type hints, you might as well hint at what the method is returning. From this</p>\n\n<pre><code>def function(...):\n</code></pre>\n\n<p>to this</p>\n\n<pre><code>def function(...) -> bool/int/etc:\n</code></pre>\n\n<p>You'll see what I mean when you look at the updated code.\n<hr>\n<strong>Updated Code</strong></p>\n\n<pre><code>class FindBucketMap(object):\n \"\"\"\n Class Docstring\n \"\"\"\n @classmethod\n def create_map_list(cls, bucket_list: list, value_list: list, bucket_map_list: list, i: int = 0) -> bool:\n \"\"\"\n Backtracking code to find possible bucket and value pair\n :param bucket_list: List of bucket values\n :param value_list: List of values to map to bucket\n :param bucket_map_list: List will be updated with the mapping of values from bucket_list to value_list\n :param i:\n :return:\n \"\"\"\n if i >= len(bucket_list) or not value_list:\n return i >= len(bucket_list) and not value_list\n\n bucket_map_prospect_list = []\n bucket_value = bucket_list[i]\n cls.create_map(bucket_value, value_list, [], bucket_map_prospect_list)\n\n if not bucket_map_prospect_list:\n return False\n\n for bucket_map_prospect in bucket_map_prospect_list:\n temp_list = list(value_list)\n temp_list.remove(x for x in bucket_map_prospect)\n if cls.create_map_list(bucket_list, temp_list, bucket_map_list, i + 1):\n bucket_map_list.append({\"bucket\": bucket_value, \"split\": bucket_map_prospect})\n return True\n\n @classmethod\n def create_map(cls, value: Decimal, value_list: list, cur_list: list, map_list: list, i: int = 0) -> None:\n \"\"\"\n Greedy code to find list of values that matches a sum\n :param value: Expected Sum\n :param value_list: Possible values\n :param cur_list: Processed values\n :param map_list: List contains the possible combinations\n :param i:\n :return:\n \"\"\"\n if value == Decimal(0):\n map_list.append(cur_list)\n return\n if value < Decimal(0):\n return\n while i < len(value_list):\n if value < value_list[i]:\n return\n cls.create_map(value - value_list[i], value_list, cur_list + [value_list[i]], map_list, i + 1)\n i += 1\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T00:24:52.923",
"Id": "229600",
"ParentId": "229314",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T13:50:24.543",
"Id": "229314",
"Score": "5",
"Tags": [
"python",
"collections"
],
"Title": "Code to pick buckets for a list of value"
}
|
229314
|
<p>This search consists of two functions <code>QuickMatch()</code> which searches for the value and <code>getQuickRowValue()</code> which returns the value of a given row. Both functions have a <code>SearchBy As SearchByIndex</code> parameter which is used to determine which values will be compared. For instance: <code>getQuickRowValue()</code> can return <code>[last name]</code> or <code>[last name] & [first name ]</code> or <code>[date] + [time]</code> depending on the values you are searching. My tests are setup to test a date and time columns for a project.</p>
<h2>Methods</h2>
<pre><code>Option Explicit
Public Enum SearchByIndex
DateTime
LastName
LastNameFirst
End Enum
Public Function QuickMatch(ByRef Values, ByVal SearchDate As Date, SearchBy As SearchByIndex, Optional ComparisonMode As MsoFilterComparison = MsoFilterComparison.msoFilterComparisonLessThan) As Long
Dim low As Long, high As Long, pivot As Long
Dim Value As Variant, NextValue As Variant, PrevValue As Variant
low = LBound(Values) + 1
high = UBound(Values)
Dim Count As Long
While low <> high
Count = Count + 1
pivot = low + (high - low) / 2
Value = getQuickRowValue(Values, pivot, SearchBy)
If pivot > LBound(Values) Then PrevValue = getQuickRowValue(Values, pivot - 1, SearchBy) Else PrevValue = -1
If pivot < UBound(Values) Then NextValue = getQuickRowValue(Values, pivot + 1, SearchBy) Else NextValue = -1
Select Case ComparisonMode
Case MsoFilterComparison.msoFilterComparisonEqual
If high = pivot Then
QuickMatch = -1
Exit Function
End If
If Value = SearchDate Then
If PrevValue = -1 Or PrevValue < SearchDate Then
QuickMatch = pivot
Exit Function
Else
high = pivot - 1
End If
ElseIf Value < SearchDate Then
If NextValue > SearchDate Then
QuickMatch = -1
Exit Function
Else
low = pivot
End If
ElseIf Value > SearchDate Then
high = pivot
End If
Case MsoFilterComparison.msoFilterComparisonLessThanEqual
If Value = SearchDate Then
If PrevValue = -1 Or PrevValue < SearchDate Then
QuickMatch = pivot
Exit Function
Else
high = pivot - 1
End If
ElseIf Value < SearchDate Then
low = pivot
ElseIf Value > SearchDate Then
If PrevValue = -1 Or PrevValue < SearchDate Then
QuickMatch = pivot
Exit Function
Else
high = pivot
End If
End If
Case MsoFilterComparison.msoFilterComparisonGreaterThanEqual
If Value = SearchDate Then
If NextValue = -1 Or NextValue > SearchDate Then
QuickMatch = pivot
Exit Function
Else
high = pivot - 1
End If
ElseIf Value < SearchDate Then
If NextValue = -1 Or NextValue > SearchDate Then
QuickMatch = pivot
Exit Function
Else
low = pivot
End If
ElseIf Value > SearchDate Then
high = pivot
End If
End Select
' DoEvents was added for testing purposes to ensure that I could break the loop
'DoEvents
Wend
End Function
Function getQuickRowValue(ByRef Values, ByVal RowNumber As Long, SearchBy As SearchByIndex) As Variant
Const DateColumn As Long = 1, TimeColumn As Long = 2
Const FirstNameColumn As Long = 3, LastNameColumn As Long = 4
Select Case SearchBy
Case SearchByIndex.DateTime
getQuickRowValue = Values(RowNumber, DateColumn) + Values(RowNumber, TimeColumn)
Case SearchByIndex.LastName
getQuickRowValue = Values(RowNumber, LastNameColumn)
Case SearchByIndex.LastNameFirst
getQuickRowValue = Values(RowNumber, LastNameColumn) & " " & Values(RowNumber, LastNameColumn)
End Select
End Function
</code></pre>
<h2>Stopwatch:Class</h2>
<pre><code>Option Explicit
' Accurate Performance Timers in VBA
' https://bytecomb.com/accurate-performance-timers-in-vba/
Private Declare PtrSafe Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As UINT64) As Long
Private Declare PtrSafe Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As UINT64) As Long
Private pFrequency As Double
Private pStartTS As UINT64
Private pEndTS As UINT64
Private pElapsed As Double
Private pRunning As Boolean
Private Type UINT64
LowPart As Long
HighPart As Long
End Type
Private Const BSHIFT_32 = 4294967296# ' 2 ^ 32
Private Function U64Dbl(U64 As UINT64) As Double
Dim lDbl As Double, hDbl As Double
lDbl = U64.LowPart
hDbl = U64.HighPart
If lDbl < 0 Then lDbl = lDbl + BSHIFT_32
If hDbl < 0 Then hDbl = hDbl + BSHIFT_32
U64Dbl = lDbl + BSHIFT_32 * hDbl
End Function
Private Sub Class_Initialize()
Dim PerfFrequency As UINT64
QueryPerformanceFrequency PerfFrequency
pFrequency = U64Dbl(PerfFrequency)
End Sub
Public Property Get Elapsed() As Double
If pRunning Then
Dim pNow As UINT64
QueryPerformanceCounter pNow
Elapsed = pElapsed + (U64Dbl(pNow) - U64Dbl(pStartTS)) / pFrequency
Else
Elapsed = pElapsed
End If
End Property
Public Sub Start()
If Not pRunning Then
QueryPerformanceCounter pStartTS
pRunning = True
End If
End Sub
Public Sub Pause()
If pRunning Then
QueryPerformanceCounter pEndTS
pRunning = False
pElapsed = pElapsed + (U64Dbl(pEndTS) - U64Dbl(pStartTS)) / pFrequency
End If
End Sub
Public Sub Reset()
pElapsed = 0
pRunning = False
End Sub
Public Sub Restart()
pElapsed = 0
QueryPerformanceCounter pStartTS
pRunning = True
End Sub
Public Property Get Running() As Boolean
Running = pRunning
End Property
'I added this to simplify the testing
</code></pre>
<p>'I added this to simplify the testing</p>
<pre><code>Public Function ElaspseTimeToString(Optional DecimalPlaces As Long = 6) As String
Me.Pause
ElaspseTimeToString = Format(Me.Elapsed, "0." & String(DecimalPlaces, "0")) & "ms"
End Function
</code></pre>
<h2>Tests</h2>
<pre><code>Option Explicit
Sub CreateTestStub()
Application.ScreenUpdating = False
Const RowCount As Long = 500000
Dim Values
ReDim Values(1 To RowCount, 1 To 2)
Dim d As Date, n As Long
d = #1/1/2000#
While n < RowCount
n = n + 1
d = d + TimeSerial(1, 0, 0)
Values(n, 1) = DateValue(d)
Values(n, 2) = TimeValue(d)
Wend
Range("A1").Resize(RowCount, 2).Value = Values
Columns.AutoFit
End Sub
Sub TestQuickMatch()
Const Tab1 = 22, Tab2 = Tab1 + 12, Tab3 = Tab2 + 12, Tab4 = Tab3 + 12, Tab5 = Tab4 + 12
Const TestCount As Long = 5
Dim Values
Values = Range("A1").CurrentRegion.Value
Dim Map As New Collection
While Map.Count < TestCount
Map.Add WorksheetFunction.RandBetween(1, UBound(Values))
Wend
Dim Stopwatch As New Stopwatch
Dim Item
Dim Result As Boolean
Dim RowNumber As Long, Expected As Long
Dim SearchDate As Date
Debug.Print "Comparison Method"; Tab(Tab1); "Pass"; Tab(Tab2); "Time"; Tab(Tab3);
Debug.Print "Row #"; Tab(Tab4); "Expected#"; Tab(Tab5); "Search Date"
For Each Item In Map
RowNumber = Item
Expected = RowNumber ' Both Row Numbers should be Equal
SearchDate = getQuickRowValue(Values, RowNumber, DateTime)
Stopwatch.Start
Result = Passes(Values, SearchDate, RowNumber, Expected, DateTime, msoFilterComparisonEqual)
Debug.Print "Equal"; Tab(Tab1); Result; Tab(Tab2); Stopwatch.ElaspseTimeToString; Tab(Tab3);
Debug.Print RowNumber; Tab(Tab4); Expected; Tab(Tab5); SearchDate
Stopwatch.Reset
Next
For Each Item In Map
RowNumber = Item
Expected = -1 ' Expected = -1 becuase there is not an exact match
SearchDate = getQuickRowValue(Values, RowNumber, DateTime) + TimeSerial(0, 1, 0)
Stopwatch.Start
Result = Passes(Values, SearchDate, RowNumber, Expected, DateTime, msoFilterComparisonEqual)
Debug.Print "Equal Fail"; Tab(Tab1); Result; Tab(Tab2); Stopwatch.ElaspseTimeToString; Tab(Tab3);
Debug.Print RowNumber; Tab(Tab4); Expected; Tab(Tab5); SearchDate
Stopwatch.Reset
Next
For Each Item In Map
RowNumber = Item
Expected = RowNumber + 1 ' Expected is the row after RowNumber because Search Date is between the two row values
SearchDate = getQuickRowValue(Values, RowNumber, DateTime) + TimeSerial(0, 1, 0) ' The Search Date is 1 minute more then the test row value
Stopwatch.Start
Result = Passes(Values, SearchDate, RowNumber, Expected, DateTime, msoFilterComparisonLessThanEqual)
Debug.Print "Less Than Equal"; Tab(Tab1); Result; Tab(Tab2); Stopwatch.ElaspseTimeToString; Tab(Tab3);
Debug.Print RowNumber; Tab(Tab4); Expected; Tab(Tab5); SearchDate
Stopwatch.Reset
Next
For Each Item In Map
RowNumber = Item
Expected = RowNumber - 1 ' Expected is the row before RowNumber because Search Date is between the two row values
SearchDate = getQuickRowValue(Values, RowNumber, DateTime) - TimeSerial(0, 1, 0) ' The Search Date is 1 minute less then the test row value
Stopwatch.Start
Result = Passes(Values, SearchDate, RowNumber, Expected, DateTime, msoFilterComparisonGreaterThanEqual)
Debug.Print "Greater Than Equal"; Tab(Tab1); Result; Tab(Tab2); Stopwatch.ElaspseTimeToString; Tab(Tab3);
Debug.Print RowNumber; Tab(Tab4); Expected; Tab(Tab5); SearchDate
Stopwatch.Reset
Next
End Sub
Function Passes(ByRef Values, ByVal SearchDate As Date, ByVal RowNumber As Long, Expected As Long, SearchBy As SearchByIndex, ComparisonMode As MsoFilterComparison) As Boolean
Passes = QuickMatch(Values, SearchDate, SearchBy, ComparisonMode) = Expected
End Function
</code></pre>
<h2>Results</h2>
<p>Note: The time is in millisecond.</p>
<p><a href="https://i.stack.imgur.com/YDNBa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YDNBa.png" alt="Immediate Window"></a></p>
<h2>Questions</h2>
<ul>
<li>Are there any error handlers that I should add?</li>
<li>The simple comparisons work fine for my needs but comparing mixed alpha and numeric values would not work properly. The <code>getQuickRowValue()</code> function should probably be replaced by a method that compares 2 rows and similar to <code>StrComp()</code> returns -1, 0 or 1. Any suggestions?</li>
</ul>
<h2>Edit</h2>
<p>I forgot to comment out the DoEvents and added a comment stating it was for testing purposes. Since DoEvents was not supposed to be there, I updated my post to reflect the changes in results. --Thanks Matt!!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T22:37:26.440",
"Id": "446037",
"Score": "0",
"body": "Is there any reason for this to be done in VBA? In what context is this used? Can't it be done in VB.net, and then exposed to VBA?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T22:52:12.567",
"Id": "446038",
"Score": "0",
"body": "@KubaOber I wrote it to find the first and last row between two dates in an array. The code could easily be converted to other programming languages."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T22:59:48.410",
"Id": "446039",
"Score": "1",
"body": "@KubaOber It could be written in another language and exposed to VBA but I see no advantage to it. A binary search over the maximum number of rows in a worksheet would only take 21 iterations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T19:12:17.823",
"Id": "446199",
"Score": "0",
"body": "I completely understand, I just wonder why VBA: VB.net gives you LINQ and then the whole thing becomes a one-liner. I also suggest to have a peek at [this splendid crazy hack LINQ-alike implemented in VBA](https://codereview.stackexchange.com/questions/66706/wait-is-this-linq). If you could use the latter, then going LINQ route would relegate hard things to library code."
}
] |
[
{
"body": "<p>I don't understand why <code>QuickMatch</code> would be in standard <code>PascalCase</code>, while <code>getQuickRowValue</code> would be <code>camelCase</code>. Public member names should be <code>PascalCase</code> - not something that's always obvious to do with a case-insensitive language, but it's certainly feasible. Consistency!</p>\n\n<blockquote>\n<pre><code>Dim low As Long, high As Long, pivot As Long\nDim Value As Variant, NextValue As Variant, PrevValue As Variant\n\nlow = LBound(Values) + 1\nhigh = UBound(Values)\n</code></pre>\n</blockquote>\n\n<p>Might be just my opinion, but I find irrelevant (or rather, <em>not-yet-relevant</em>) variable declarations distracting. Avoid strings (or worse, walls) of declarations at the top of procedures; instead, declare them <em>as they're needed</em>. Code will read much more seamlessly, and variable declarations will always appear in the context they're relevant in:</p>\n\n<pre><code>Dim low As Long\nlow = LBound(Values) + 1\n\nDim high As Long\nhigh = UBound(Values)\n\nWhile low <> high\n '...\n DoEvents\nWend\n</code></pre>\n\n<p>Here I'd probably take everything in that loop body, and move it to another procedure scope. I would also replace the <a href=\"http://rubberduckvba.com/Inspections/Details/ObsoleteWhileWendStatement\" rel=\"nofollow noreferrer\">obsolete <code>While...Wend</code></a> with a <code>Do While...Loop</code> construct:</p>\n\n<pre><code>Dim low As Long\nlow = LBound(Values) + 1\n\nDim high As Long\nhigh = UBound(Values)\n\nDo While low <> high\n Dim count As Long\n count = count + 1\n QuickMatch = QuickMatchInternal(values, low, high, count)\nLoop\n</code></pre>\n\n<p>And that would be the whole function's body: everything else belongs at a lower abstraction level... why <code>DoEvents</code> though? Code that clocks sub-millisecond execution times shouldn't need any special measures taken to help keep the UI thread responsive: <code>DoEvents</code> has no business anywhere, unless it's absolutely needed - in which case an explanatory comment is warranted. But commented-out, it's... dead code that should be removed.</p>\n\n<p>So, this <code>QuickMatchInternal</code> private function would only need to be concerned about a single iteration, and needs to take its parameters <code>ByRef</code>.</p>\n\n<p>Inside that procedure's scope, the main element that sticks out is the massive <code>Select Case</code> block. I'd try to break it down and move each <code>Case</code> to its own scope. Glancing at the code, I'd say make these <code>Boolean</code>-returning functions, and if they return <code>True</code> then we can <code>Exit Function</code>:</p>\n\n<pre><code> Select Case ComparisonMode\n Case MsoFilterComparison.msoFilterComparisonEqual\n If HandleComparisonEqual(...) Then Exit Function\n\n Case MsoFilterComparison.msoFilterComparisonLessThanEqual\n If HandleComparisonLessThanEqual(...) Then Exit Function\n\n Case MsoFilterComparison.msoFilterComparisonGreaterThanEqual\n If HandleComparisonGreaterThanEqual(...) Then Exit Function\n\n Case Else\n '?\n End Select\n</code></pre>\n\n<p>...and since nothing guarantees <code>ComparisonMode</code> will be one of these values, there needs to be a <code>Case Else</code> that throws an error accordingly. <a href=\"https://docs.microsoft.com/en-us/office/vba/api/office.msofiltercomparison\" rel=\"nofollow noreferrer\">The enum defines 10 members</a>, and even if inputs are only ever one of these, there is no indication anywhere that the function is only handling a small subset of them.</p>\n\n<p>The <code>Exit Function</code> jumps probably make the move challenging, but if the outer loop's exit condition is met by then, then there shouldn't be a problem doing that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:04:21.393",
"Id": "445975",
"Score": "0",
"body": "DoEvents!! Oops...I had that in there for testing. I removed it and updated my post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:09:53.347",
"Id": "445976",
"Score": "0",
"body": "I use the `get` and `set` prefix because Eclipse generates it's getters and setter let with them. I don't leie `Get` and `Set` and will probably consider a different name. I did not know that `While...WEnd` werre obsolete."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:12:32.100",
"Id": "445977",
"Score": "0",
"body": "You can't `Exit While`, that's why. Also... Java doesn't have properties ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:21:51.020",
"Id": "445981",
"Score": "0",
"body": "Originally, `QuickMatch()` was the only function. I added the Enum and the helper function after I completed the testing. `QuickMatchInternal()` and handling the cases separately is absolute genius!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:28:13.093",
"Id": "445983",
"Score": "0",
"body": "In that case `Case Else`/`Debug.Assert False 'this shouldn't happen` seems appropriate ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:37:02.347",
"Id": "445988",
"Score": "0",
"body": "My mistake. The previous comment has been `stricken from the record`. You are correct an error should be raise for an unhandled enumeration value. I think that the new code deserves its own enumeration. Any suggestion on a prefix for an Enums values?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:39:43.190",
"Id": "445989",
"Score": "0",
"body": "I'm generally not a fan of prefixing, but enum prefixing in COM/VBA typically acts as a surrogate namespace, so `tin` works fine (or no prefix at all)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T21:36:12.237",
"Id": "446032",
"Score": "0",
"body": "Do edits 2 or 3 of the question invalidate your answer? If so, I presume you would roll them back, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T23:05:15.023",
"Id": "446041",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ I was hoping that my comments referencing this post would be enough to make it unnecessary to do the rollback. After all DoEvents was never meant to be part of finished code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T23:26:50.910",
"Id": "446043",
"Score": "0",
"body": "@TinMan I probably shouldn't say this because it *is* technically an invalidating edit as far as site rules go, but I don't mind it at all; I wouldn't remove the `DoEvents` part from my answer though, because it's still valuable info/content for any readers IMO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T23:34:44.297",
"Id": "446044",
"Score": "1",
"body": "@SᴀᴍOnᴇᴌᴀ I would indeed - and feel free to disagree with me and roll it back anyway (that intervention wouldn't be contrary to site rules about answer-invalidating edits), but I believe the way the edit was made (with the seams showing, i.e. it's explicitly called out), with the instruction being commented-out rather than outright removed, keeps the little `DoEvents` side-note relevant. IMO the Q+A as a whole remains coherent, so while it's *technically* invalidating, the *spirit* of the rule is upheld, there are far worse cases of answer invalidation edits that *do* warrant a rollback ;-)"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T15:39:49.107",
"Id": "229323",
"ParentId": "229317",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229323",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T14:07:54.007",
"Id": "229317",
"Score": "4",
"Tags": [
"vba",
"binary-search"
],
"Title": "Flexible Binary Search"
}
|
229317
|
<p>I'm fairly new to object oriented programming and while I understand the basic concepts, I'm still having some trouble organizing my applications. I'm building a small Tkinter application as a learning experience and am trying to make sure I follow correct object oriented principles. I have a couple specific questions regarding what I've done so far (I appreciate any and all suggestions however!).</p>
<p><strong>BACKGROUND INFO</strong></p>
<p>The application will be to handle tasks that are written by the user and stored a database. The user should be able to use a search bar to look up tasks by key words or use radio buttons with a specified filter. The user can add any task they want and include relevant details that will be shown when the task is clicked on. The user will also be able to delete and update tasks as needed. </p>
<p><strong>CONCERNS</strong></p>
<ul>
<li>Is it correct to use static methods often? I wanted to separate the logic from the rest of the application and I realized I'd be writing quite a few static methods from the way I structured my app</li>
<li>Would it be better to create a class for every widget separately? I created my Frame classes (see code below) and packed them with the widgets that goes into that specific frame. This causes the Frame classes to be quite large</li>
<li>I quite like the MVC architecture overall. Is it generally a good architecture to follow when designing GUI application?</li>
</ul>
<p>It's my first time posting, so I apologize in advance if this is too much code or if I missing something important to add that would aid looking at my code. Please let me know if there's something I can add/remove that would clear things up.</p>
<p><strong>WORKING CODE</strong></p>
<pre class="lang-py prettyprint-override"><code>import tkinter as tk
import sqlite3
# I kept the database in the global scope
con = sqlite3.connect('../database/a_db.db')
cur = con.cursor()
class Model:
def __init__(self):
pass
@staticmethod
def get_tasks():
query = ''' SELECT * FROM tasks '''
tasks = cur.execute(query).fetchall()
return tasks
@staticmethod
def get_task_details(selected_task_id):
query = '''SELECT * FROM tasks WHERE task_id=? '''
task = cur.execute(query, (selected_task_id,))
task_details = task.fetchall()[0][2]
return task_details
@staticmethod
def get_task_status(selected_task_id):
query = ''' SELECT assigned.emp_id FROM assigned
INNER JOIN tasks ON tasks.task_id = assigned.task_id
WHERE assigned.task_id=? '''
db_active_task = cur.execute(query, (selected_task_id,)).fetchall()
if len(db_active_task) > 0:
return 'Assigned'
else:
return 'Not Assigned'
@staticmethod
def get_search(value):
query_tasks = ''' SELECT task_id, task_name FROM tasks WHERE task_name LIKE ? OR task_description LIKE ? '''
matched_tasks = cur.execute(query_tasks, ('%' + value + '%', '%' + value + '%'), ).fetchall()
return matched_tasks
class View(tk.Tk):
def __init__(self, controller):
super().__init__()
self.title("My App")
self.middle_of_screen()
self.resizable(False, False)
self.iconbitmap(r'../images/an_icon.ico')
self.controller = controller
self.top_panel = TopFrame()
self.left_panel = LeftFrame()
self.right_panel = RightFrame(self.controller)
def display_task_details(self, status, task_details):
if self.left_panel.list_details.get(0):
self.left_panel.list_details.delete(0, 'end')
self.left_panel.list_details.insert(0, "Status: {}".format(status))
if self.left_panel.list_details:
self.left_panel.list_details.insert(1, "Task Description: {}".format(task_details))
else:
self.left_panel.list_details.insert(1, "Task Description: None")
def display_tasks(self, tasks):
self.left_panel.list_tasks.delete(0, 'end')
for count, task in enumerate(tasks):
self.left_panel.list_tasks.insert(count, '{}. {}'.format(task[0], task[1]))
def middle_of_screen(self):
window_width = 1350
window_height = 750
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
x = (screen_width // 2) - (window_width // 2)
y = (screen_height // 2) - (window_height // 2)
self.geometry(f'{window_width}x{window_height}+{x}+{y}')
def start(self):
self.mainloop()
class TopFrame:
def __init__(self):
self.top_frame = tk.Frame(width=1350, height=70, relief='sunken', bg='#f8f8f8',
borderwidth=2, padx=20)
self.top_frame.pack(side='top', fill='x')
# Task Button
self.book_icon = tk.PhotoImage(file="../images/add_book.png")
self.book_button = tk.Button(self.top_frame, text='Task\nManagement', image=self.book_icon, compound='left',
font='arial 12 bold', bg='red', padx=10)
self.book_button.pack(side='left', padx=(10, 0))
# Employee Button
self.users_icon = tk.PhotoImage(file='../images/users.png')
self.employee_button = tk.Button(self.top_frame, text='Employee\nManagement', image=self.users_icon,
compound='left', font='arial 12 bold', bg='red', padx=10)
self.employee_button.pack(side='left', padx=(10, 0))
# Add Employee To Project
self.givetask_icon = tk.PhotoImage(file='../images/givebook.png')
self.add_emp_button = tk.Button(self.top_frame, text='Assign Task \nTo Employee', image=self.givetask_icon,
compound='left', font='arial 12 bold', bg='red', padx=10)
self.add_emp_button.pack(side='left', padx=(10, 0))
class LeftFrame:
def __init__(self):
self.left_frame = tk.Frame(width=900, height=700, relief='sunken', bg='#e0f0f0',
borderwidth=2)
self.left_frame.pack(side='left')
# TABS
## Tasks Tab
self.tabs = ttk.Notebook(self.left_frame, width=900, height=660)
self.tabs.pack()
self.tab1_icon = tk.PhotoImage(file='../images/books.png')
self.tab2_icon = tk.PhotoImage(file='../images/members.png')
self.tab1 = ttk.Frame(self.tabs)
self.tab2 = ttk.Frame(self.tabs)
self.tabs.add(self.tab1, text='Task Management', image=self.tab1_icon, compound='left')
self.tabs.add(self.tab2, text='Statistics', image=self.tab2_icon, compound='left')
# List tasks
self.list_tasks = tk.Listbox(self.tab1, width=40, height=30, bd=5, font='times 12 bold')
self.scroll_bar = tk.Scrollbar(self.tab1, orient='vertical')
self.list_tasks.grid(row=0, column=0, padx=(10, 0), pady=10, sticky='n')
self.scroll_bar.config(command=self.list_tasks.yview)
self.list_tasks.config(yscrollcommand=self.scroll_bar.set)
self.scroll_bar.grid(row=0, column=0, sticky='nse')
# List Details
self.list_details = tk.Listbox(self.tab1, width=80, height=30, bd=5, font='times 12 bold')
self.list_details.grid(row=0, column=1, padx=(10, 0), pady=10, sticky='n')
# Statistics Tab
self.tasks_count_label = tk.Label(self.tab2, text='Tasks Count', pady=20, font='verdana 14 bold underline')
self.tasks_count_label.grid(row=0, sticky='e')
self.employee_count_label = tk.Label(self.tab2, text='Emp. Count', pady=20, font='verdana 14 bold underline')
self.employee_count_label.grid(row=1, sticky='e')
self.assigned_tasks_count_label = tk.Label(self.tab2, text='Assigned Tasks\n Count', pady=20,
font='verdana 14 bold underline')
self.assigned_tasks_count_label.grid(row=2, sticky='e')
self.unassigned_tasks_count_label = tk.Label(self.tab2, text='Unassigned Tasks\n Count', pady=20,
font='verdana 14 bold underline')
self.unassigned_tasks_count_label.grid(row=3, sticky='e')
class RightFrame:
def __init__(self, controller):
self.controller = controller
self.right_frame = tk.Frame(width=450, height=700, relief='sunken', bg='#e0f0f0',
borderwidth=2)
self.right_frame.pack()
self.search_bar = tk.Frame(self.right_frame, width=440, height=75, bg='#9bc9ff')
self.search_bar.pack(fill='both')
self.search_bar_entry = tk.Entry(self.search_bar, width=30, bd=10)
self.search_bar_entry.grid(row=0, column=2, columnspan=3, padx=(30, 60), pady=10)
self.search_bar_button = tk.Button(self.search_bar, text='Search', font='arial 12 bold', bg='#fcc324',
fg='black', command=self.controller.show_search)
self.search_bar_button.grid(row=0, column=0, padx=(60, 30), pady=10)
# List Bar
self.list_bar = tk.LabelFrame(self.right_frame, text='Filter', width=440, height=175, bg='#fcc324')
self.list_bar.pack(fill='both')
# Radio Buttons for List Bar
self.list_choice = tk.IntVar()
self.all_radio_btn = tk.Radiobutton(self.list_bar, text='All Tasks', var=self.list_choice, value=1,
bg='#fcc324')
self.completed_radio_btn = tk.Radiobutton(self.list_bar, text='Completed Tasks', var=self.list_choice, value=2,
bg='#fcc324')
self.progressing_radio_btn = tk.Radiobutton(self.list_bar, text='Progressing Tasks', var=self.list_choice,
value=3,
bg='#fcc324')
self.employees_radio_btn = tk.Radiobutton(self.list_bar, text='Current Employees', var=self.list_choice,
value=4,
bg='#fcc324')
self.completed_radio_btn.grid(row=0, rowspan=2, column=1, sticky='nsw')
self.progressing_radio_btn.grid(row=0, rowspan=2, column=2, sticky='nsw')
self.all_radio_btn.grid(row=2, rowspan=2, column=1, sticky='nsw', pady=10)
self.employees_radio_btn.grid(row=2, rowspan=2, column=2, sticky='nsw', pady=10)
# Button for List Bar
self.filter_list_btn = tk.Button(self.list_bar, text='Filter', fg='black', font='arial 12 bold', bg='red')
self.filter_list_btn.grid(row=1, column=0, rowspan=2, sticky='nesw', padx=(10, 20), pady=25)
# # Title and image
self.image_bar = tk.Frame(self.right_frame, width=440, height=350)
self.image_bar.pack(fill='both')
self.title_right = tk.Label(self.image_bar, text='Welcome to the CTREL task \nmanagement system',
font='arial 16 bold')
self.title_right.grid(row=0)
self.library_img = tk.PhotoImage(file='../images/library.png') # Have to use self to keep reference!
self.library_img_label = tk.Label(self.image_bar, image=self.library_img)
self.library_img_label.grid(row=2)
class Controller:
def __init__(self):
self.model = Model()
self.view = View(controller=self)
self.show_tasks()
self.view.left_panel.list_tasks.bind('<<ListboxSelect>>', self.show_task_details)
self.view.start()
def show_task_details(self, event):
if self.view.left_panel.list_tasks.curselection():
selected_task = self.view.left_panel.list_tasks.get(self.view.left_panel.list_tasks.curselection())
selected_task_id = selected_task.split('.')[0]
db_task_details = self.model.get_task_details(selected_task_id)
status = self.model.get_task_status(selected_task_id)
self.view.display_task_details(status, db_task_details)
def show_tasks(self):
tasks = self.model.get_tasks()
self.view.display_tasks(tasks)
def show_search(self):
value = self.view.right_panel.search_bar_entry.get()
searched_task = self.model.get_search(value)
self.view.display_tasks(searched_task)
if __name__ == '__main__':
c = Controller()
c.view.start()
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T22:32:58.427",
"Id": "446036",
"Score": "0",
"body": "The use of the global scope is very much problematic. Your static methods aren't really static, they are instance methods that work on objects in global scope. Get rid of static methods, instantiate \"global\" objects within `main`, and pass them to the class's constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T07:29:52.283",
"Id": "446073",
"Score": "0",
"body": "Hi! You successfully explained your concerns about the code but failed to tell us _what_ the code does. What is your Tkinter app all about? Please [edit] your question to explain it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T18:08:09.120",
"Id": "446181",
"Score": "0",
"body": "@KubaOber Would it be more appropriate to instantiate the database in the Model class constructor as an alternative to instantiate through main?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T18:09:09.730",
"Id": "446182",
"Score": "0",
"body": "@MathiasEttinger Hi! Thanks for the feedback, I've added a background section to explain at a high level what the app is accomplishing (and will accomplish). Please me know if anything is unclear!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T19:18:11.360",
"Id": "446200",
"Score": "0",
"body": "@ShockDoctor I have no opinion, but for better composability, the looser the coupling, the better, so moving dependencies out helps with that."
}
] |
[
{
"body": "<h1>Problems with code run</h1>\n\n<ul>\n<li><h3>imports</h3>\n\n<p>I'd qualify the code as non-working. It forgets to import <code>ttk</code></p>\n\n<pre><code>from tkinter import ttk\n</code></pre></li>\n<li><h3>DB structure.</h3>\n\n<p>No table creation code found. We can only guess the db reading queries. Request to include table info next time.</p></li>\n<li><h3>Include sample repo</h3>\n\n<p>For images etc, if we got the link to a sample repo, it might be easier to run the file.</p></li>\n</ul>\n\n<h1>Recommendations</h1>\n\n<h1>Use SQLAlchemy</h1>\n\n<p><strong>models.py</strong></p>\n\n<p>I highly recommend you use <a href=\"https://www.sqlalchemy.org\" rel=\"nofollow noreferrer\">sqlalchemy</a>. Since you are defining a custom model class, sqlalchemy's models are far more flexible.</p>\n\n<pre><code>from sqlalchemy import Column, String, Integer\nfrom sqlalchemy.ext.declarative import declarative_base\n\n\nBase = declarative_base()\n\n\nclass Task(Base):\n __tablename__ = 'tasks'\n\n id = Column(Integer, primary_key=True)\n task_name = Column(String)\n task_description = Column(String)\n</code></pre>\n\n<p>Then for queries it's a lot simpler:</p>\n\n<pre><code>session.query(Task).all()\nsession.query(Task).filter(record.id == some_id).first()\nsession.query(Task).like(search).all()\n</code></pre>\n\n<h1>Why <code>r''</code>?</h1>\n\n<p>I guess you are using <code>r</code> in paths so as not to escape slashes. But forward slashes work on Windows as well.</p>\n\n<h1>A custom function for images</h1>\n\n<p>Since you are appending <code>../images</code> each time, add a function to get the image path by just specifying the name:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import os\n\n\ndef image(item):\n dir_path = '../images'\n return os.path.join(dir_path, item)\n</code></pre>\n\n<h1>Better class naming</h1>\n\n<p><code>class TopFrame:</code> does not give info about the section. Maybe <code>class OptionsFrame:</code> might be better.</p>\n\n<h1>Better way to avoid long lines</h1>\n\n<p>Long lines like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> self.book_button = tk.Button(self.top_frame, text='Task\\nManagement', image=self.book_icon, compound='left',\n font='arial 12 bold', bg='red', padx=10)\n</code></pre>\n\n<p>can be structured like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> self.book_button = tk.Button(\n self.top_frame, \n text='Task\\nManagement', \n image=self.book_icon, \n compound='left',\n font='arial 12 bold', \n bg='red', \n padx=10)\n</code></pre>\n\n<p>It makes the code more readable.</p>\n\n<h1>Group strings in one place.</h1>\n\n<p>Let's say you want to change the welcome message. You'd have to dig in the frame code.</p>\n\n<p>Let's say you had a class:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class UIStrings:\n def __init__(self):\n welcome_message = '...'\n</code></pre>\n\n<p>Then you reference <code>UIStrings.welcome_message</code> in your UI code. This idea can be expanded for internationalisation, maybe using XML files.</p>\n\n<h1>Pass controller explicitly</h1>\n\n<p>Given</p>\n\n<pre><code>c = Controller()\nc.view.start()\n</code></pre>\n\n<p>having:</p>\n\n<pre><code>controller = Controller()\nview = View(controller=controller)\n</code></pre>\n\n<p>might suggest a cleaner architecture.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T21:31:09.983",
"Id": "235986",
"ParentId": "229320",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T14:23:23.623",
"Id": "229320",
"Score": "7",
"Tags": [
"python",
"object-oriented",
"mvc",
"gui",
"tkinter"
],
"Title": "Properly Structuring a Tkinter Application"
}
|
229320
|
<p>I wrote the below answer for the following <a href="https://stackoverflow.com/questions/57977681/javascript-for-survey/">question on SO</a> a couple of days ago, and I was curious if the usage of the generator function is an acceptable one.</p>
<p>I choose the generator function, because I could easily exchange the generator at a later time to ask the question not in sequence, but rather randomized, or whatever algorithm I might come up with at that time :)</p>
<p>One thing I am not entirely fond of is the restart functionality. I guess it might be better to have the logic for restarting the questionaire rather implemented inside the <code>onCompleted</code> callback I have now, rather than as part of the "official" end of the questionaire.</p>
<p>Because of this, I am now reusing an already called callback, so I guess these are things that can be improved.</p>
<p>Still I am curious of having a review of the usage of the generator here, and the potential overlooked drawbacks (the fact that only next is available is not something that I find a problem, I wanted it unidirectional)</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 questions = [
{
question: 'What platform are you on?',
answers: ['Stackoverflow', 'codereview'],
correct: 1,
points: 5
},
{
question: 'What is the answer to everything',
answers: [42, 'I don\'t have a clue'],
correct: 0,
points: 1
},
{
question: 'How much is 7*6',
answers: ['I am not good with maths', 42],
correct: 1,
points: 10
}
];
// a simple generator that is used in the questionaire
function *questionsGenerator( questions ) {
yield* questions;
}
const questionaire = ( query, nextButton, target, onCompleted ) => {
let score = 0;
let totalScore = 0;
let iterator = questionsGenerator( query );
let question = null;
let selectedAnswer = -1;
nextButton.addEventListener('click', nextQuestion);
function evaluateAnswer() {
if (!question) {
// no question yet
return;
}
if (selectedAnswer < 0) {
return;
}
totalScore += question.points;
if (question.correct === selectedAnswer) {
score += question.points;
}
return;
}
function restart() {
btnNext.removeEventListener('click', restart);
questionaire( query, nextButton, target, onCompleted );
btnNext.innerHTML = 'next';
}
function nextQuestion() {
evaluateAnswer();
question = iterator.next();
// this is a bit of a hack to check if we just had the last question or not
if (question.done) {
nextButton.removeEventListener('click', nextQuestion);
nextButton.innerText = 'Restart';
btnNext.addEventListener('click', restart);
onCompleted( (score / totalScore) * 100 );
return;
}
question = question.value;
drawUI();
}
function drawUI() {
// disable next button
nextButton.setAttribute('disabled', true);
selectedAnswer = -1;
// remove existing items
Array.from( target.childNodes ).forEach( child => target.removeChild( child ) );
// create new questions (if available)
const title = document.createElement('h1');
title.innerHTML = question.question;
target.appendChild( title );
question.answers.map( (answer, i) => {
const el = document.createElement('input');
el.type = 'radio';
el.name = 'answer';
el.value = i;
el.id = 'answer' + i;
el.addEventListener('change', () => {
selectedAnswer = i;
nextButton.removeAttribute('disabled');
} );
const label = document.createElement('label');
label.setAttribute('for', el.id );
label.innerHTML = answer;
const container = document.createElement('div');
container.appendChild(el);
container.appendChild(label);
return container;
} ).forEach( a => target.appendChild( a ) );
}
nextQuestion();
};
// create a questionaire and start the first question
questionaire(
questions,
document.querySelector('#btnNext'),
document.querySelector('#questionaire'),
score => alert('You scored ' + score )
);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="questionaire">
</div>
<div class="toolstrip">
<button id="btnNext" type="button">Next</button>
</div></code></pre>
</div>
</div>
</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T14:48:56.867",
"Id": "229321",
"Score": "2",
"Tags": [
"javascript",
"callback",
"generator"
],
"Title": "Customizable unidirectional questionaire in javascript"
}
|
229321
|
<p>This maze solver is a continuation to the maze generator I posted here recently <a href="https://codereview.stackexchange.com/questions/227660/maze-generator-animator-in-python">Maze generator & animator in Python</a></p>
<p>This code takes an image containing a 2-color maze as input and solves the maze and produces an image of the solution or an animated GIF. The algorithm implemented so far is breadth-first search(BFS) and I'm intending to post a follow up when other algorithms (A*, Dijkstra ...) are implemented.</p>
<hr>
<p><strong>It currently has the following features:</strong></p>
<ul>
<li><strong>Automatic marking</strong> of start and end(Top left to bottom right) by passing <code>'a'</code> to <code>start_end</code> constructor parameter.</li>
<li><strong>Manual marking</strong> of start and end(choose any 2 given coordinates that are in path and the program does the rest (by not passing anything to <code>start_end</code></li>
<li><strong>(x0, y0), (x1, y1)</strong> are accepted in <code>start_end</code> constructor for start and end respectively</li>
<li><strong>Solving any 2-color maze</strong> given that the maze has a clear border and a valid path (You might use my maze generator for producing a valid image)</li>
<li><strong>Generation and saving</strong> image of the solution in a given folder path (custom solving color, input resize and output image size).</li>
<li><strong>Generation of animated GIF</strong> (custom solving color and frame size) (150-200 seconds for default values, takes longer for custom values)</li>
</ul>
<hr>
<p><strong>Algorithms implemented so far:</strong></p>
<p><strong>1. Breadth-first search(BFS):</strong></p>
<ul>
<li><p><strong>Example 1 (Maze generated by my code - Solution - Gif)</strong></p>
<p><a href="https://i.stack.imgur.com/pG0fC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pG0fC.png" alt="maze"></a> <a href="https://i.stack.imgur.com/2vgDy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2vgDy.png" alt="solution"></a> <a href="https://i.stack.imgur.com/NWrGM.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NWrGM.gif" alt="gif"></a></p></li>
<li><p><strong>Example 2 (Maze generated by my code - Solution - Gif)</strong></p>
<p><a href="https://i.stack.imgur.com/sPMx5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sPMx5.png" alt="maze"></a>
<a href="https://i.stack.imgur.com/RpGjn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RpGjn.png" alt="solution"></a>
<a href="https://i.stack.imgur.com/75n8h.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/75n8h.gif" alt="gif"></a></p></li>
</ul>
<hr>
<pre><code>#!/usr/bin/env python3
import os
import cv2
import glob
import shutil
import random
import imageio
from PIL import Image
from queue import Queue
from time import perf_counter
class MazeSolver:
"""
Solve a 2-color(wall color and path color) maze using several algorithm choices:
- Breadth-First Search Algorithm(BFS).
"""
def __init__(
self,
maze_path,
marking_color,
start_end=None,
solution_size=(500, 500),
downsize=(150, 150),
):
"""
Initialize maze image, mark start and end points.
maze_path: a string (path to maze image).
marking_color: RGB tuple of color to use for drawing the solution path.
solution_size: a tuple (height, width) of the solved version size.
start_end: a tuple of x, y coordinates of maze start and x, y coordinates of maze end or
'a' for automatic mode.
"""
self.path = input(
"Enter folder path to save images and GIF frames: "
).rstrip()
while not os.path.exists(self.path):
print(f"Invalid folder path {self.path}")
self.path = input(
"Enter folder path to save images and gifs: "
).rstrip()
self.maze = Image.open(maze_path).resize(downsize)
self.downsize = downsize
self.height, self.width = self.maze.size
self.maze_path = maze_path
self.marking_color = marking_color
if start_end == "a":
self.initial_coordinates = []
self._automatic_start_end()
self.start, self.end = self.initial_coordinates
if start_end and start_end != "a":
self.start, self.end = start_end
if not start_end:
self.initial_coordinates = []
self.titles = ["(End)", "(Start)"]
self._set_start_end()
self.start, self.end = self.initial_coordinates
self.path_color = self.maze.getpixel(
(self.start[0], self.start[1])
)
self.wall_color = self.maze.getpixel((0, 0))
self.solution_name = (
str(random.randint(10 ** 6, 10 ** 8))
+ " Maze solution"
)
self.output_image_size = solution_size
self.configurations = {
"bfs": self._breadth_first_search()
}
self.algorithm_names = {
"bfs": "BREADTH-FIRST SEARCH "
}
def _automatic_start_end(self):
"""Determine start and end automatically"""
start = 0
end_rows, end_columns = (
self.height - 1,
self.width - 1,
)
border_color = self.maze.getpixel((0, 0))
while (
self.maze.getpixel((start, start))
== border_color
):
start += 1
while (
self.maze.getpixel((end_rows, end_columns))
== border_color
):
end_rows -= 1
end_columns -= 1
self.initial_coordinates.append((start, start))
self.initial_coordinates.append(
(end_rows, end_columns)
)
def _set_start_end(self):
"""
Show maze image to determine coordinates.
You will be shown the maze, click twice, first to indicate the starting point
and second to indicate ending point and then press any key to proceed.
"""
maze_image = cv2.imread(self.maze_path)
resized_image = cv2.resize(
maze_image, self.downsize
)
cv2.namedWindow("Maze to solve")
cv2.setMouseCallback(
"Maze to solve", self._get_mouse_click
)
cv2.imshow("Maze to solve", resized_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
if len(self.initial_coordinates) != 2:
raise ValueError(
f"Expected 2 clicks for start and end "
f"respectively, got {len(self.initial_coordinates)}"
)
def _get_mouse_click(self, event, x, y, flags, param):
"""Get x, y coordinates for mouse clicks on maze image."""
if event == cv2.EVENT_LBUTTONDOWN:
self.initial_coordinates.append((x, y))
print(
f"Clicked on coordinates {x, y} {self.titles.pop()} color: {self.maze.getpixel((x, y))}"
)
def _get_neighbor_coordinates(self, coordinates):
"""
Return a list of adjacent pixel coordinates that represent a path."""
x, y = coordinates
north = (x - 1, y)
if north[0] < 0:
north = None
if (
north
and self.maze.getpixel(north) == self.wall_color
):
north = None
south = (x + 1, y)
if south[0] > self.height:
south = None
if (
south
and self.maze.getpixel(south) == self.wall_color
):
south = None
east = (x, y + 1)
if east[1] > self.width:
east = None
if (
east
and self.maze.getpixel(east) == self.wall_color
):
east = None
west = (x, y - 1)
if west[1] < 0:
west = None
if (
west
and self.maze.getpixel(west) == self.wall_color
):
west = None
return [
neighbor
for neighbor in (north, south, east, west)
if neighbor
]
def _breadth_first_search(self):
"""Return path and visited pixels solved by a breadth-first search algorithm."""
check = Queue()
check.put([self.start])
visited = []
while not check.empty():
path = check.get()
last = path[-1]
if last == self.end:
return path, visited
if last not in visited:
neighbor_coordinates = self._get_neighbor_coordinates(
last
)
valid_coordinates = [
neighbor
for neighbor in neighbor_coordinates
if neighbor not in visited
]
for valid_coordinate in valid_coordinates:
new_path = list(path)
new_path.append(valid_coordinate)
check.put(new_path)
visited.append(last)
raise ValueError(
f"Too low downsize rate {self.downsize}"
)
def produce_path_image(self, configuration):
"""
Draw path in maze and return solved maze picture.
configuration: a string representing the algorithm:
- 'bfs': solve using breadth-first search algorithm.
"""
start_time = perf_counter()
os.chdir(self.path)
if configuration not in self.configurations:
raise ValueError(
f"Invalid configuration {configuration}"
)
path, visited = self.configurations[configuration]
for coordinate in path:
self.maze.putpixel(
coordinate, self.marking_color
)
if "Solutions" not in os.listdir(self.path):
os.mkdir("Solutions")
os.chdir("Solutions")
maze_name = "".join(
[
self.algorithm_names[configuration],
self.solution_name,
".png",
]
)
resized_maze = self.maze.resize(
self.output_image_size
)
resized_maze.save(maze_name)
end_time = perf_counter()
print(f"Time: {end_time - start_time} seconds.")
return resized_maze
def produce_maze_solving_visualization(
self, configuration, frame_speed, new_size=None
):
"""
Generate GIF for the solution of the maze by the selected algorithm:
configuration: a string:
- 'bfs': Breadth-first search algorithm.
frame_speed: frame speed in ms
new_size: a tuple containing new (height, width)
"""
start_time = perf_counter()
initial_image = Image.open(self.maze_path).resize(
self.downsize
)
os.chdir(self.path)
if configuration not in self.configurations:
raise ValueError(
f"Invalid configuration {configuration}"
)
path, visited = self.configurations[configuration]
count = 1
for coordinate in visited:
self.maze.putpixel(
coordinate, self.marking_color
)
if new_size:
resized = self.maze.resize(new_size)
resized.save(str(count) + ".png")
else:
self.maze.save(str(count) + ".png")
count += 1
if new_size:
resized = initial_image.resize(new_size)
resized.save(str(count) + ".png")
else:
initial_image.save(str(count) + ".png")
count += 1
for coordinate in path[::-1]:
initial_image.putpixel(
coordinate, self.marking_color
)
if new_size:
resized = initial_image.resize(new_size)
resized.save(str(count) + ".png")
else:
initial_image.save(str(count) + ".png")
count += 1
os.mkdir(self.solution_name)
for file in os.listdir(self.path):
if file.endswith(".png"):
shutil.move(file, self.solution_name)
os.chdir(self.solution_name)
frames = glob.glob("*.png")
frames.sort(key=lambda x: int(x.split(".")[0]))
frames = [imageio.imread(frame) for frame in frames]
imageio.mimsave(
self.path + str(self.solution_name) + ".gif",
frames,
"GIF",
duration=frame_speed,
)
end_time = perf_counter()
print(f"Time: {end_time - start_time} seconds.")
if __name__ == "__main__":
test = MazeSolver("test.png", (255, 0, 0), "a")
test.produce_path_image("bfs").show()
</code></pre>
|
[] |
[
{
"body": "<h2>Type hints</h2>\n\n<p>The parameters to your <code>MazeSolver.__init__</code> should get type hints, particularly for things that don't have defaults. For instance, <code>maze_path: str</code>.</p>\n\n<h2>Separate input</h2>\n\n<p>You shouldn't be calling <code>input</code> from <code>__init__</code>. Just accept it as another parameter, and do the input and validation at a higher level.</p>\n\n<h2>In-band logic</h2>\n\n<p>Baking <code>'a'</code> as a special condition into your <code>start_end</code> complicates your code and confuses your interface. Just have a separate boolean to trigger automatic mode.</p>\n\n<h2>Presentation vs. logic</h2>\n\n<p>If I understand this correctly, this:</p>\n\n<pre><code> while (\n self.maze.getpixel((start, start))\n == border_color\n ):\n start += 1\n</code></pre>\n\n<p>relies on an image to run the business logic. This is somewhat fragile. You're at the mercy of the resizing algorithm not to slightly change the colours of the image, particularly if there's interpolation enabled. So first, make sure interpolation is disabled during resize (I'm not sure if this is already the case). And also, you may want to have a nearest-match algorithm that finds pixel colours close to the colours your program expects for borders, etc. In the end this might look like a conversion to a two-dimensional Python list of enum values that represent business logic instead of colours.</p>\n\n<p>For example,</p>\n\n<pre><code>from enum import Enum\n\nclass MazeValue(Enum):\n WALL = (0, 0, 0) # e.g.\n BORDER = (20, 20, 20)\n\n def dist(self, colour):\n return sum((s - o)**2 for s, o in zip(self.value, colour))\n\n @classmethod\n def closest(cls, colour):\n return min(cls, key=lambda c: c.dist(colour))\n\n# ...\n\ngrid = [\n [\n MazeValue.closest(self.maze.getpixel((x, y)))\n for x in self.width\n ]\n for y in self.height\n]\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T16:10:03.863",
"Id": "445962",
"Score": "0",
"body": "Thanks for the feedback, if you have the time please add more details to the interpolation and nearest match algorithm part because I have no idea how to do it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T16:17:51.510",
"Id": "445964",
"Score": "0",
"body": "And what do you mean by 'business logic'?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T17:34:23.270",
"Id": "445971",
"Score": "0",
"body": "Business logic basically constitutes all of the decisions that your application needs to make about your data and application behaviour."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T17:35:49.177",
"Id": "445972",
"Score": "2",
"body": "https://en.m.wikipedia.org/wiki/Business_logic"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T19:06:29.917",
"Id": "445995",
"Score": "0",
"body": "As for the nearest-match stuff: I wrote an example. I only did a little bit of testing for the enum, and didn't feed it a real image, so your mileage may vary. You'll also want to replace the enum values, of course."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T19:30:06.890",
"Id": "445998",
"Score": "0",
"body": "okay, thanks a lot I'll check"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T16:04:25.423",
"Id": "229324",
"ParentId": "229322",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T15:13:09.460",
"Id": "229322",
"Score": "9",
"Tags": [
"python",
"python-3.x",
"image",
"animation",
"breadth-first-search"
],
"Title": "Maze image solver and animator in Python"
}
|
229322
|
<p>Simple code where family and person instances can be created. There is a method where any instance of Person can be added to any instance of Family.</p>
<pre><code>class Family:
def __init__(self):
self.names, self.birthplaces, self.dobs, self.deaths = [], [], [], []
class Person:
def __init__(self, name, birthplace, dob, death=None):
self.name, self.birthplace, self.dob, self.death = name, birthplace, dob, death
def add_member_to(self, family_tree):
family_tree.names.append(self.name)
family_tree.birthplaces.append(self.birthplace)
family_tree.dobs.append(self.dob)
if self.death is None:
family_tree.deaths.append('N/A')
else:
family_tree.deaths.append(self.death)
family = Family()
mike = Person('Michael', 'Nigeria', '06-07-2004')
esther = Person('Esther', 'KC', '03-25-2009')
mike.add_member_to(family)
esther.add_member_to(family)
print(family.dobs)
print(family.names)
print(family.birthplaces)
print(family.deaths)
</code></pre>
|
[] |
[
{
"body": "<p>My one improvement would be this line of code</p>\n\n<pre><code>if self.death is None:\n family_tree.deaths.append('N/A')\nelse:\n family_tree.deaths.append(self.death)\n</code></pre>\n\n<p>can be reduced to one line:</p>\n\n<pre><code>family_tree.deaths.append('N/A' if self.death is None else self.death)\n</code></pre>\n\n<p>Also, I would recommend keeping all code not in these classes in a <a href=\"https://stackoverflow.com/a/19578335/8968906\">main guard</a>, so you can import these classes without also running the code in the module.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T22:14:36.277",
"Id": "229539",
"ParentId": "229325",
"Score": "1"
}
},
{
"body": "<ul>\n<li><p><code>add_member_to</code> acts on <code>family_tree</code> and changes its fields. It is more logical to define the method in the class <code>Family</code> as <code>add_member</code> instead.</p></li>\n<li><p>The <code>Family</code> class should directly store a list of <code>Person</code>s as a field rather than copying all the information of the family members. Information of members can be directly retrieved from <code>Person</code> objects when needed. This avoids the same data being copied redundantly, which adds burden to maintainence (e.g., every change of <code>Person</code> information requires a subsequent change in <code>Family</code> of the copied information). <code>names</code>, <code>birthplaces</code>, <code>dobs</code>, <code>deaths</code> can be defined as class properties and accessed through defined methods.</p></li>\n</ul>\n\n\n\n<ul>\n<li><code>Person</code> can be defined as a <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\">dataclass</a>, which can automatically generate methods such as <code>__init__</code> from field definitions. It may be an overkill for this small program but it will be useful for larger classes.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T01:11:15.850",
"Id": "229544",
"ParentId": "229325",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T16:09:06.217",
"Id": "229325",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"object-oriented",
"game"
],
"Title": "FAMILY.PY | OOPython"
}
|
229325
|
<p>Simple object-oriented, money management code where a user can deposit money in, withdraw from, show, and exit the balance.</p>
<pre><code>class BankAccuount:
def __init__(self, name):
self.name = name
self.balance = 0
print('Hello! Welcome to the Deposit and Withdrawal Machine {}!'.format(self.name))
def deposit(self):
'''adds money to balance'''
amount = float(input('\nEnter amount to be deposited > '))
self.balance += amount
print(f'Amount deposited: {amount}')
self.display()
def withdrawal(self):
'''subtracts money from balance if funds are sufficient'''
amount = float(input('\nEnter amount to be withdrawn > '))
if amount > self.balance:
print('Insufficient balance')
else:
self.balance -= amount
print('Amount withdrawn:', amount)
self.display()
def display(self):
print(f'\nNet Available Balance is {self.balance}')
whats_your_name = input('What is your name? ')
consumer = BankAccuount(whats_your_name)
while True:
action = input('\nWould you like to deposit (D), withdraw (W), show balance (S), or exit (E)? ').upper()
if action in 'DW':
while True:
try:
if action == 'D':
consumer.deposit()
elif action == 'W':
consumer.withdrawal()
break
except ValueError:
print('Use numbers please')
elif action == 'S':
consumer.display()
else:
print(f'Thank you for your visit {whats_your_name}!')
break
</code></pre>
|
[] |
[
{
"body": "<h1>Docstring</h1>\n\n<p>I see that you had some docstrings for <em>some</em> of your methods. But I didn't see any for your <code>BankAccount</code> class, or for the module. You should include these as well.</p>\n\n<h1>Bank Structure</h1>\n\n<p>You take input within the deposit and withdraw methods inside the class. These methods should only have one function: adding and subtracting money from the account itself. You should handle user input outside the class.</p>\n\n<h1>Containment</h1>\n\n<p>Right now, all of your user input code is handled in the global scope of the program. This code should be defined to a function, called from a main guard (will get into that later). This will allow you to structure your code better, and separate your code into chunks as needed. It also lets you see the big picture of your program better.</p>\n\n<h1>Consistency</h1>\n\n<p>I see you using <code>\"\".format()</code> and <code>f\"\"</code>. You should stick to one, as they both do the same thing. Personally, I like to use <code>f\"\"</code> exclusively.</p>\n\n<h1>Main Guard</h1>\n\n<p>As mentioned above, the code outside of your class should be contained in a function called from a main guard, or in the main guard itself.</p>\n\n<p>Main Guard:</p>\n\n<pre><code>if __name__ == '__main__':\n ... code stuff here ...\n</code></pre>\n\n<p>Having a main guard clause in a module allows you to both run code in the module directly and also use procedures and classes in the module from other modules. Without the main guard clause, the code to start your script would get run when the module is imported.</p>\n\n<h1>Type Hints</h1>\n\n<p>Using <a href=\"https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html\" rel=\"nofollow noreferrer\">type hints</a> allows you to see what kinds of variables are to be passed to methods, and what methods return what type of variable. I added some to your class methods, take a look and see how you like them. They can be really helpful.</p>\n\n<p><strong><em>Updated Code</em></strong></p>\n\n<pre><code>\"\"\"\nModule Docstring (a description of your program goes here)\n\"\"\"\nclass BankAccount:\n \"\"\"\n BankAccount Class\n \"\"\"\n def __init__(self, name: str):\n self.name = name\n self.balance = 0\n\n def deposit(self, amount: float) -> bool:\n '''adds money to balance'''\n if amount > 0:\n self.balance += amount\n return True\n return False\n\n def withdraw(self, amount: float) -> bool:\n '''subtracts money from balance if funds are sufficient'''\n if amount > self.balance or amount < 0:\n return False\n self.balance -= amount\n return True\n\n def display_balance(self):\n \"\"\" displays current account balance \"\"\"\n print(f'\\nNet Available Balance is ${self.balance}')\n\ndef interface():\n \"\"\"\n Interface for interacting with the bank account\n \"\"\"\n print(f'Hello! Welcome to the Deposit and Withdrawal Machine {name}!')\n while True:\n action = input('\\nWould you like to deposit (D), withdraw (W), show balance (S), or exit (E)? ').upper()\n\n if action in \"DWSE\":\n if action == \"D\":\n try:\n deposit_amount = float(input(\"How much would you like to deposit: \"))\n if not account.deposit(deposit_amount):\n print(\"Please enter a positive number!\")\n else:\n print(f\"Successfully deposited {deposit_amount} into your account.\")\n except ValueError:\n print(\"Please enter a positive number.\")\n if action == \"W\":\n try:\n withdraw_amount = float(input(\"How much would you like to withdraw: \"))\n if not account.withdraw(withdraw_amount):\n print(\"You do not have enough money to withdraw.\")\n else:\n print(f\"Successfully withdraw {withdraw_amount} from your account.\")\n except ValueError:\n print(\"Please enter a positive number.\")\n if action == \"S\":\n account.display_balance()\n if action == \"E\":\n break\n\nif __name__ == '__main__':\n name = input('What is your name? ')\n account = BankAccount(name)\n interface()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T20:47:17.400",
"Id": "229345",
"ParentId": "229326",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T16:27:26.820",
"Id": "229326",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x",
"object-oriented",
"simulation"
],
"Title": "Bank account class"
}
|
229326
|
<p>I'm looking for feedback on the code I came up with for exercise 1-21 in "The C Programming Language" by K&R.</p>
<blockquote>
<p>Write a program <em>entab</em> that replaces strings of blanks with the minimum number of tabs and blanks to achieve the same spacing. Use the same stops as for <em>detab</em> . When either a tab or a single blank would suffice to reach a tab stop, which should be given preference?</p>
</blockquote>
<p>The feedback I would mainly like is on readability, conventions and general good (or bad) practices.</p>
<p>This was a fun problem to solve and I think I came up with a efficient solution.</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#define TABSIZE 8
#define MAXLENGTH 80
void entab(char s[]);
int _getline(char s[], int lim);
int main()
{
int len;
char line[MAXLENGTH];
while ((len = _getline(line, MAXLENGTH)) > 0)
entab(line);
}
void entab(char s[])
{
int i, c, nb;
nb = 0;
for (i = 0; (c = s[i]) != '\0'; ++i)
{
if (c == ' ')
{
if (++nb > 1)
{
if (i + 1 % TABSIZE == 0)
{
putchar('\t');
nb = 0;
}
}
}
else
{
if (nb > 0)
{
for (; nb > 0; --nb)
putchar('x');
}
putchar(c);
}
}
}
int _getline(char s[], int lim)
{
int c, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
s[i] = c;
if (c == '\n')
{
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
</code></pre>
<p><em>The function <code>_getline()</code> was given by the book.</em>
<em>Only practices encountered in the book up until this assignment are used, I have not yet read about things like pointers and other more advanced features</em></p>
<hr>
<p>My own thoughts</p>
<ul>
<li>Use (more) comments when coding</li>
<li>Use more "self-explaining" variable names</li>
<li>Input longer than 80 characters isn't handled correctly</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T12:00:22.163",
"Id": "446097",
"Score": "1",
"body": "Just in case you don't know - *never* begin your own identifiers with an underscore like that. Standard C reserves those names for the implementation's own use, so you may get a collision. I'll let you off since K&R gave that to you (the book pre-dates the standardisation of the language, so it wasn't as certainly an issue back when it was written)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T21:26:56.390",
"Id": "446211",
"Score": "0",
"body": "@TobySpeight This is definitely my own fault! The book gave the function with the name \"getline\" however I ran into issues because I think the stdio library also contains a function with that name. Coming from python I thought it was a good idea to use an underscore. I will avoid doing so from now on, thank you for the feedback!"
}
] |
[
{
"body": "<p>Welcome to Code Review! I'm always glad to see someone who reads the classics.</p>\n\n<p>You made some interesting observations about the program.</p>\n\n<p>The statement <em>Use more \"self-explaining\" variable names</em> is absolutely correct: the variable name <code>nb</code> could definitely be improved. I would like to point out that <em>self-documenting</em> might be better than <em>self-explaining</em>.</p>\n\n<p>If the variable and symbolic constant names are improved it may not need any additional comments.</p>\n\n<p>The header file <code><stdio.h></code> includes a symbolic constant <code>BUFSIZ</code> that might be a better length than <code>80</code>. In some cases <code>BUFSIZ</code> <strong>may</strong> be the maximum line length for the system; this was true on older Unix systems.</p>\n\n<h3>Possible Bug</h3>\n\n<p>This code seems out of scope for the problem as it is defined, I would expect to see that it was outputing blanks.</p>\n\n<pre><code> for (; blankCount > 0; --blankCount)\n putchar('x');\n</code></pre>\n\n<h3>A Good Coding Practice</h3>\n\n<p>Code needs to be maintained. This may include adding additional lines to control structures such as <code>if</code> statements and loops. In C and C++ a good programming practice is to have code blocks (complex statements) in all <code>if</code>, <code>else</code> and loop statements even if it isn't currently necessary.</p>\n\n<pre><code>if (CONDITION)\n{\n one statement\n}\nelse\n{\n one statement\n}\n\nwhile (CONDITION)\n{\n one statement\n}\n</code></pre>\n\n<h3>Alternate Solution with Simplified Functions</h3>\n\n<p>It might be easier to read, write and modify <code>entab()</code> if it called a function to count all the blanks and print the necessary tabs and blanks. Programming in many cases is breaking down a problem into smaller and smaller pieces until each piece is easy to implement. While this may make the entire program a little more complex, each function is simplified.</p>\n\n<p>This example uses a concept you haven't gotten to in the book yet called pointers.</p>\n\n<pre><code>void print_tabs_or_spaces(int tab_count, int out_value)\n{\n for (int i = 0; i < tab_count; i++)\n {\n putchar(out_value);\n }\n}\n\nchar* count_blanks_and_output_tabs_and_spaces(char *c)\n{\n int blank_count = 0;\n\n while (*c == ' ')\n {\n ++blank_count;\n c++;\n }\n int tab_count = blank_count / TABSIZE;\n int space_count = blank_count % TABSIZE;\n\n print_tabs_or_spaces(tab_count, '\\t');\n print_tabs_or_spaces(space_count, ' ');\n\n return c;\n}\n\nvoid entab(char str[])\n{\n char *c = &str[0]; \n while(*c != '\\0')\n {\n if (*c == ' ')\n {\n c = count_blanks_and_output_tabs_and_spaces(c);\n }\n else\n {\n putchar(*c);\n c++;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T20:48:00.930",
"Id": "446018",
"Score": "1",
"body": "Thank you very much for your observations and feedback! The reason for this loop is because when the global loop starts, we aren't sure yet whether the spaces / blanks we encounter should be tabs, in a case where multiple spaces / blanks are used, but not until the nearest tab stop, a tab shouldn't be used. example: `\"hello world\"` (2 spaces) will be printed as `\"helloxxworld\"` where as `hello world` (3 spaces) will be printed as `\"hello\\tworld\"`. I did however forget to change the `'x'` to a `' '` (space)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T21:06:51.727",
"Id": "446027",
"Score": "2",
"body": "@Ghxst I wasn't questioning why the loop was there, just the `x`. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T19:53:49.870",
"Id": "229342",
"ParentId": "229327",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "229342",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T16:39:11.913",
"Id": "229327",
"Score": "7",
"Tags": [
"c",
"strings",
"formatting",
"io"
],
"Title": "Replacing spaces with tabs. Exercise 1-21 in \"The C Programming Language\""
}
|
229327
|
<p>Backstory: I'm creating department level workbooks that contains director-level information, so I can't use a single workbook (as easy as it would make this). I need to split (and combine) 4 workbooks into 140 or more. I manage to do this relatively quickly (~30 minutes), but I was hoping to speed it up more.</p>
<p>For each sheet I create, I need certain filtered columns from the original 4 reports. After filtering the reports, I have this macro copy the columns:</p>
<pre class="lang-vb prettyprint-override"><code>Sub copyVisibleCells(fromWb As String, fromWS As String, fromCol As Integer, towb As String, toWS As String, toCol As Integer)
On Error GoTo errhnd
Dim myCopyRange As Range
Dim toCopyRange As Range
' Get the intersection of the column we want, and the range that has been used
Set myCopyRange = Intersect(Workbooks(fromWb).Sheets(fromWS).Columns(fromCol), Workbooks(fromWb).Sheets(fromWS).UsedRange)
' If there's at least one visible cell (there was some error here once about trying to copy 0 cells, go figure)
If myCopyRange.SpecialCells(xlCellTypeVisible).Cells.Count > 1 Then
' Remove the first row (swap the 1 with a 2) to remove the headers
Set myCopyRange = Workbooks(fromWb).Sheets(fromWS).Range(Left(myCopyRange.Address, InStr(myCopyRange.Address, ":") - 2) & "2:" & Right(myCopyRange.Address, Len(myCopyRange.Address) - InStr(myCopyRange.Address, ":")))
' Copy the cells over: works, but seems slow
myCopyRange.SpecialCells(xlCellTypeVisible).Copy
Workbooks(towb).Sheets(toWS).Cells(6, toCol).PasteSpecial(xlValues)
End If
' Done
Exit Sub
errhnd:
Debug.Print (vbNewLine & vbNewLine & "Error: " & err.Number & vbNewLine & err.Description & vbNewLine & "Press F8 to see error location")
Stop
Resume
End Sub
</code></pre>
<p>Is there a better way to do this? I was under the impression that Range.Copy and Range.PasteSpecial(xlValues) were very inefficient much like I've heard of Range.Select</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:36:12.883",
"Id": "445987",
"Score": "0",
"body": "@Downvoter: An explanation? What am I doing wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T19:00:21.793",
"Id": "445993",
"Score": "2",
"body": "Not my downvote, but this is Code Review, not Stack Overflow - see our [help/on-topic] for more details, but long story short if your code isn't working as intended, it's not ready for a peer review, and that makes the post off-topic on this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T19:49:32.667",
"Id": "446006",
"Score": "0",
"body": "I mean, it does work with the first method (Copy + PasteSpecial), I just thought it was running slowly. I was trying to show that I was attempting the problem and not immediately turning to the internet to fix my code for me :) Edit- Thank you though"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T19:53:35.510",
"Id": "446007",
"Score": "1",
"body": "If it's about performance bottlenecks and general enhancements, feel free to [edit] your post to remove any ambiguity about whether the code you're submitting for review works as intended or not; the code under review should be the working code you're currently using. You'll find CR is a lot more laid back than SO; SO wants straight-to-the-point and what-did-you-try, CR wants all the context and then some, and only needs to see the working code that needs to be reviewed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T20:14:26.187",
"Id": "446013",
"Score": "1",
"body": "Thank you, that was very helpful! I edited the post, but if anyone needs/wants more context, let me know, I can post more about this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T16:51:22.650",
"Id": "446165",
"Score": "1",
"body": "There are two main parts to your code: the copy/paste operation and creating/opening/closing workbooks (i.e. file I/O -- which is not shown in your code above). While you might get some performance improvement in the copy/paste section, there is likely NO performance improvement possible for the file I/O, especially if you are reading/writing to a network drive. That's a bottleneck in your enterprise, not VBA."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T00:26:07.277",
"Id": "446225",
"Score": "0",
"body": "@PeterT Thank you, I hadn't thought of that! I'm generating each report and copying to the network during the code. I bet it would be a lot faster to copy them over when I'm done and I've verified that they all look correct. Plus I'm uploading to SharePoint later anyways"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-17T18:52:49.907",
"Id": "450065",
"Score": "0",
"body": "@PeterT Wow. You were so right. I started generating all the files in my %Temp% directory and copying them at the end. The reports generate about 10 times faster. :O Thank you so much!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:32:57.397",
"Id": "229334",
"Score": "1",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Copy Non-continuous Cell Values"
}
|
229334
|
<p>I need to generate valid <a href="https://github.com/lifthrasiir/cson" rel="nofollow noreferrer">CSON</a> representation of Python objects for a project; I still didn't make a loader because for this project I only need to export, not load.</p>
<p>CSON is similar to JSON but with prettier syntax IMHO. I am following this <a href="https://gist.github.com/Aerijo/b8c82d647db783187804e86fa0a604a1" rel="nofollow noreferrer">syntax guide</a>.</p>
<p>My goal is to construct custom language grammars for atom automatically from python by an API that should hopefully be easier than the textmate based one and I needed a reliable way to convert python constructs to CSON.</p>
<p>I am also trying to make this module very generalized such that I can use for further projects.</p>
<pre class="lang-py prettyprint-override"><code>"""
Small module for generating cson structures from python objects
"""
__all__ = [
"compile_cson"
]
import re
# Regex to check if a string complies with a variable name
VAR_NAME = re.compile("^[A-Za-z_$][A-Za-z_0-9$]*$")
class NoKey:
"""
Type to indicate the absence of a key
in a cson object eg. inside arrays
"""
pass
# Mapping for correction to match
# python types to cson objects
type_aberrations = {
float("nan"): "Nan",
float("inf"): "Infinity",
float("-inf"): "-Infinity",
None: "null",
False: "false",
True: "true"
}
def dump_cson(obj,
lines=None,
key=NoKey,
indents=2,
indent_level=0,
converter=lambda x: x):
"""
Recursive function that traverses a
tree of objects and converts them to lines of a cson file
"""
if not lines:
lines = []
# allow user defined decoding function to convert custom types
# into primitive types
obj = converter(obj)
if not key == NoKey:
if key in type_aberrations:
key = type_aberrations[key]
# converts key into a string and handle the case where
# it doesn't need quotes
# this could be skipped for string keys but looks so much prettier
key_str = str(converter(key))
if type(key) in (float, int) or VAR_NAME.match(key_str):
key = f"{converter(key_str)}: "
# key must have quotes because it contains
# bad characters that must be escaped
else:
key = f"{repr(converter(key_str))}: "
else:
# there's no, replace with empty string
key = ""
whtspace = " " * indent_level
# handles numbers and truth value types
if type(obj) in (int, float, bool) or obj == None:
# match python's and cson types
obj = type_aberrations.get(obj, obj)
lines.append(f"{whtspace}{key}{obj}")
# handles strings conversion
elif isinstance(obj, str):
obj = repr(obj)
lines.append(f"{whtspace}{key}{obj}")
# handle lists and tuples conversion to array
elif isinstance(obj, (tuple, list)):
lines.append(f"{whtspace}{key}[")
# recursively dump list's content
for obj in obj:
dump_cson(obj,
lines,
NoKey,
indents,
indent_level + indents,
converter)
lines.append(f"{whtspace}]")
# handle dict to object conversion
elif isinstance(obj, dict):
# if we have a key, dont use curly braces for dicts
# the single colon looks better and more readable
if key:
lines.append(f"{whtspace}{key}")
# we have no key, it must use curky braces notation
else:
lines.append(whtspace + "{")
# recursively dump dict's contents with
for dkey, obj in obj.items():
dump_cson(obj,
lines,
dkey,
indents,
indent_level + indents,
converter)
if not key:
lines.append(whtspace + "}")
else:
raise ValueError(f"type {obj} unsupported, you may use a converter function"
f" to convert it to a primitive datatype.")
return lines
def compile_cson(obj, indents=2, converter=lambda x: x):
return "\n".join(dump_cson(obj, indents=indents, converter=converter))
if __name__ == "__main__":
# build random objects tree for test
import random
stuff = ["abc", "123abc", 123, 1.2, 32, "chars+--/",
"variable_name", None, False, True]
length_thresshold = 2
list_n = 5
dict_n = 5
def pick_thing():
return random.choice(stuff)
def build_list(max_depth):
k = length_thresshold / list_n
return [build_random_tree(k, max_depth) for _ in range(list_n)]
def build_dict(max_depth):
k = length_thresshold / list_n
dict = {}
for i in range(dict_n):
dict[pick_thing()] = build_random_tree(k, max_depth)
return dict
def build_random_tree(thresshold=2, max_depth=5):
if random.random() < thresshold and max_depth >= 0:
return random.choice((build_dict, build_list))(max_depth - 1)
else:
return pick_thing()
obj = build_random_tree()
print(compile_cson(obj, indents=2))
</code></pre>
<p>The above script generates random trees of lists and dicts and tries to convert them; could I improve the testing to give more confidence that I got it right?</p>
<h3>Example output:</h3>
<pre><code>{
'123abc': 123
1.2: null
123: false
null: true
abc:
false: 'abc'
variable_name: false
'chars+--/': 'abc'
1.2: '123abc'
32:
variable_name: true
'123abc': 32
false: 123
true: [
true
'123abc'
'chars+--/'
null
null
]
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T20:05:51.047",
"Id": "446012",
"Score": "2",
"body": "Have you tested the code? What do you think doesn't work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T20:21:36.390",
"Id": "446014",
"Score": "0",
"body": "I said I am not sure it works all cases, but I am testing it yet, since I am not used with this kind of translation, I still dont know how to make sure it will always build valid cson syntax.\nThe only test case I made is on the `If __name__` section, it builds and prints random trees but I couldn't figure out how to validate them yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T21:16:08.627",
"Id": "446029",
"Score": "0",
"body": "Can you provide a link to a complete description of CSON? To test it, round trip a python object. Start with a python object dump it to CSON, then load it back into Python and see if it matches the original object. Repeat for any types of object you plan to handle, e.g. a list, a list of lists, a dict of lists of strings, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T21:49:34.007",
"Id": "446033",
"Score": "0",
"body": "I am following this guide for the syntax it https://gist.github.com/Aerijo/b8c82d647db783187804e86fa0a604a1 there's this one which is more specific https://github.com/lifthrasiir/cson and I still didn't make a loader because for this project I only need to export, not load."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T08:24:27.413",
"Id": "446079",
"Score": "0",
"body": "That information should be part of the question; I've edited for you this time, so check that I've got it right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T13:14:19.230",
"Id": "446111",
"Score": "0",
"body": "Its ok, thanks for the edits. newbie here."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:40:37.797",
"Id": "229336",
"Score": "0",
"Tags": [
"python",
"json"
],
"Title": "Creating a cson generator in python"
}
|
229336
|
<p><a href="https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/627" rel="nofollow noreferrer">https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/627</a></p>
<blockquote>
<p>Given a binary tree, check whether it is a mirror of itself (ie,
symmetric around its center).</p>
<p>For example, this binary tree [1,2,2,3,4,4,3] is symmetric:</p>
<pre><code> 1
/ \
2 2
/ \ / \
3 4 4 3
</code></pre>
<p>But the following [1,2,2,null,3,null,3] is not:</p>
<pre><code> 1
/ \
2 2
\ \
3 3
</code></pre>
<p>Note: Bonus points if you could solve it both recursively and
iteratively.</p>
</blockquote>
<pre><code>using System.Collections.Generic;
using GraphsQuestions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TreeQuestions
{
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
/// <summary>
/// https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/627
/// </summary>
[TestClass]
public class SymmetricTreeTest
{
// 1
// / \
// 2 2
// / \ / \
// 3 4 4 3
[TestMethod]
public void ValidSymmetricTree()
{
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(2);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(4);
root.right.left = new TreeNode(4);
root.right.right = new TreeNode(3);
Assert.IsTrue(SymmetricTree.IsSymmetric(root));
}
// 1
// / \
// 2 2
// \ \
// 3 3
[TestMethod]
public void NotValidSymmetricTree()
{
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(2);
root.left.right = new TreeNode(3);
root.right.right = new TreeNode(3);
Assert.IsFalse(SymmetricTree.IsSymmetric(root));
Assert.IsFalse(SymmetricTree.IsSymmetricIterative(root));
}
}
public class SymmetricTree
{
public static bool IsSymmetric(TreeNode root)
{
if (root == null)
{
return true;
}
return Helper(root.left, root.right);
}
public static bool Helper(TreeNode t1, TreeNode t2)
{
if (t1 == null && t2 == null)
{
return true;
}
if (t1 == null || t2 == null)
{
return false;
}
if (t1.val != t2.val)
{
return false;
}
//make sure the MIRRORED SIDES are sent!
return Helper(t1.left, t2.right) && Helper(t1.right, t2.left);
}
public static bool IsSymmetricIterative(TreeNode root)
{
if (root == null)
{
return true;
}
Queue<TreeNode> Q = new Queue<TreeNode>();
Q.Enqueue(root);
Q.Enqueue(root);
while (Q.Count > 0)
{
TreeNode t1 = Q.Dequeue();
TreeNode t2 = Q.Dequeue();
if (t1 == null && t2 == null)
{
continue;
}
if (t1 == null || t2 == null)
{
return false;
}
if (t1.val != t2.val)
{
return false;
}
Q.Enqueue(t1.left);
Q.Enqueue(t2.right);
Q.Enqueue(t1.right);
Q.Enqueue(t2.left);
}
return true;
}
}
}
</code></pre>
<p>Please review for performance</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T19:23:37.583",
"Id": "445996",
"Score": "0",
"body": "This will be a top performer (it's correct). Good luck in the competition."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T21:00:20.257",
"Id": "446026",
"Score": "0",
"body": "@DavidFisher which one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T01:18:46.443",
"Id": "446226",
"Score": "0",
"body": "The iterator one is the great. However, humor me and just expand your tests down one additional branch. trying both: `1 2 3 4 4 3 2 1` and `1 2 2 1 3 4 4 3`"
}
] |
[
{
"body": "<h3>Performance</h3>\n\n<ul>\n<li>The recursive function is as fast as I can think of.</li>\n<li>The iterative function should enqueue <code>root.left</code> and <code>root.right</code> instead of <code>root</code> and <code>root</code> to gain a cycle (micro-optimisation).</li>\n</ul>\n\n<h3>Review</h3>\n\n<ul>\n<li>I find it weird that the null node is considered symmetric <code>IsSymmetric(null)</code>. I would throw an error for invalid input.</li>\n<li>Both algorithms are not able to deal with <code>TreeNode</code> instances that have a cycle (stack overflow exception vs infinite loop respectively). You will lose some performance if you guard against cycles.</li>\n<li><code>Helper</code> is a public method. There is no reason for this. Make it private or local inside the public method, and perhaps rename it to <code>IsSymmetric</code>, which will not be in conflict with the public method because of different signature.</li>\n<li>Parameter names <code>t1</code> and <code>t2</code> are best avoided. Use full and more clear names like <code>node1</code> and <code>node2</code>.</li>\n<li><code>Queue<TreeNode> Q = new Queue<TreeNode>();</code> should be written more concisely and clearly as <code>var queue = new Queue<TreeNode>();</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T19:28:55.923",
"Id": "229339",
"ParentId": "229337",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "229339",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:53:43.600",
"Id": "229337",
"Score": "4",
"Tags": [
"c#",
"performance",
"programming-challenge",
"tree",
"comparative-review"
],
"Title": "LeetCode: Symmetric Tree C#"
}
|
229337
|
<p>I am learning how to create a rest api in which I've decided to use generic for crud operation. I am attaching the code which I have written so far. Please have a look. Thanks for the review in advance.<br/>
<br/>
<em>What I expect from code review: </em><br/></p>
<ol>
<li>Good part of the code (if any)<br/></li>
<li>Code portion which needs improvement(or any alternate way)<br/></li>
<li>Code which should not be there. <br/></li>
<li>Any source from where I can learn how to create the architecture of web-app.
</li>
</ol>
<h3>Brand Model</h3>
<pre><code>package com.test.model;
import java.io.Serializable;
import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity
@Cacheable
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
@Table(name = "brand_master")
public class BrandMaster extends BaseEntity implements Serializable {
private static final long serialVersionUID = 4045918990469712465L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "pk_brandId")
private Integer id;
@Column(name = "brand_name", unique = true)
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
</code></pre>
<h3>BaseEntity:</h3>
<pre><code>package com.test.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.format.annotation.DateTimeFormat;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseEntity {
@CreatedDate
@Column(name = "createdOn")
@DateTimeFormat(pattern = "dd/MM/yyyy")
protected Date createdOn;
@CreatedBy
@Column(name = "createdBy")
protected UserMaster createdBy;
@LastModifiedDate
@Column(name = "updateOn")
@DateTimeFormat(pattern = "dd/MM/yyyy")
protected Date updatedOn;
@LastModifiedBy
@Column(name = "updatedBy")
protected UserMaster updatedBy;
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public UserMaster getCreatedBy() {
return createdBy;
}
public void setCreatedBy(UserMaster createdBy) {
this.createdBy = createdBy;
}
public Date getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Date updatedOn) {
this.updatedOn = updatedOn;
}
public UserMaster getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(UserMaster updatedBy) {
this.updatedBy = updatedBy;
}
}
</code></pre>
<h3>Controller</h3>
<pre><code>package com.test.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.test.dto.BrandDTO;
import com.test.service.BrandService;
@RestController
@RequestMapping(path = "**/Brand")
public class BrandController {
private Logger log = LoggerFactory.getLogger(BrandController.class);
@Autowired
private BrandService BrandService;
@GetMapping(path = "**/{id}")
public ResponseEntity<BrandDTO> get(@PathVariable Integer id) {
log.trace("Starting processing get request for id :" + id);
BrandDTO Brand = BrandService.get(id);
if (Brand != null) {
return new ResponseEntity<BrandDTO>(Brand, HttpStatus.OK);
}
log.info("Entity having id not found, id : " + id);
return new ResponseEntity<BrandDTO>(HttpStatus.NOT_FOUND);
}
@GetMapping
public ResponseEntity<List<BrandDTO>> getAll(@RequestParam(value = "pageNum", required = false) Integer pageNum, @RequestParam(value = "size", required = false) Integer size) {
log.trace("Starting processing getAll request!");
List<BrandDTO> Brandes = BrandService.getAll(pageNum, size);
if (Brandes != null && !Brandes.isEmpty()) {
return new ResponseEntity<List<BrandDTO>>(Brandes, HttpStatus.OK);
}
log.info("No element found while hitting getAll");
return new ResponseEntity<List<BrandDTO>>(HttpStatus.NO_CONTENT);
}
@PostMapping
public ResponseEntity<BrandDTO> save(@RequestBody BrandDTO Brand) {
log.trace("Starting processing Post request!");
try {
Brand = BrandService.saveOrUpdate(Brand);
} catch (Exception err) {
log.error("Error Occured while saving, Message : " + err.getMessage() + "; Cause :" + err.getCause());
return new ResponseEntity<BrandDTO>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<BrandDTO>(Brand, HttpStatus.CREATED);
}
@PutMapping(path = "**/{id}")
public ResponseEntity<BrandDTO> update(@PathVariable Integer id, @RequestBody BrandDTO Brand) {
log.trace("Starting processing put for id :" + id);
if (Brand != null && Brand.getId() == null) {
log.trace("updating id in model for put request for id :" + id);
Brand.setId(id);
}
if (Brand != null && Brand.getId().equals(id)) {
log.trace("processing put request for id :" + id);
try {
Brand = BrandService.saveOrUpdate(Brand);
} catch (Exception err) {
log.error("Error Occured while saving, Message : " + err.getMessage() + "; Cause :" + err.getCause());
return new ResponseEntity<BrandDTO>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<BrandDTO>(Brand, HttpStatus.OK);
}
log.info("Id mismatch for model (" + Brand.getId() + ") and request param :" + id);
return new ResponseEntity<BrandDTO>(HttpStatus.NOT_MODIFIED);
}
@DeleteMapping(path = "**/{id}")
public ResponseEntity<String> delete(@PathVariable Integer id) {
log.trace("Starting processing of delete rrequest for id :" + id);
if (!BrandService.isExist(id)) {
log.info("Entity not found while processing the delete request for id :" + id);
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
BrandService.delete(id);
log.info("Entity deleted having id :" + id);
return new ResponseEntity<>(HttpStatus.OK);
}
}
</code></pre>
<h3>Service:</h3>
<pre><code>package com.test.service;
import com.test.dto.BrandDTO;
import com.test.model.BrandMaster;
public interface BrandService extends GenericService<BrandMaster, Integer, BrandDTO> {
}
</code></pre>
<h3>Service Impl:</h3>
<pre><code>package com.test.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.test.dao.BrandDao;
import com.test.dto.BrandDTO;
import com.test.mapper.BrandMapper;
import com.test.model.BrandMaster;
import com.test.service.BrandService;
@Service("brandService")
public class BrandServiceImpl extends GenericServiceImpl<BrandMaster, Integer, BrandDTO> implements BrandService{
@Autowired
public BrandServiceImpl(BrandDao brandDao) {
super(brandDao);
}
@Override
public BrandMaster transformDTOToEntity(BrandDTO element) {
return BrandMapper.INSTANCE.brandDTOToBrandMaster(element);
}
@Override
public BrandDTO transformEntityToDTO(BrandMaster element) {
return BrandMapper.INSTANCE.brandMasterToBrandDTO(element);
}
}
</code></pre>
<h3> Generic Service</h3>
<pre><code>package com.test.service;
import java.util.List;
public interface GenericService <E, I, D> {
/**
* E : Entity Class
* I : type of Id element
* D : DTO POJO
*/
public D get(I id);
public List<D> getAll(Integer pageNumber, Integer size);
public D saveOrUpdate(D element);
public void delete(I id);
public boolean isExist(I id);
public E transformDTOToEntity(D element);
public D transformEntityToDTO(E element);
}
</code></pre>
<h3>Generic Service Impl</h3>
<pre><code>package com.test.service.impl;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import com.test.service.GenericService;
public abstract class GenericServiceImpl <E, I, D> implements GenericService<E, I, D>{
protected JpaRepository<E, I> repository;
private Logger log = LoggerFactory.getLogger(GenericServiceImpl.class);
public GenericServiceImpl(JpaRepository<E, I> repository) {
this.repository = repository;
}
@Override
public D get(I id) {
log.trace("<== Inside generic get method ==> ");
Optional<E> element = repository.findById(id);
if(element.isPresent()){
log.trace("<== Got the response from dao and received an object ==>");
return this.transformEntityToDTO(element.get());
}
log.info("<== No element is found for the passed id ==>");
return null;
}
@Override
public List<D> getAll(Integer pageNumber, Integer size) {
log.trace("<== Inside getAll() of generic service ==>");
pageNumber = pageNumber != null? pageNumber : 0;
size = size != null? size : 10;
Pageable page = PageRequest.of(pageNumber, size);
List<E> list = repository.findAll(page).getContent();
log.trace("<== Got the response from the repository from getALL ==>");
return list.stream().map(entity -> transformEntityToDTO(entity)).collect(Collectors.toList());
}
@Override
public D saveOrUpdate(D element) {
log.trace("<== Inside sabeOrOpdate() of generic service ==>");
return this.transformEntityToDTO(repository.save(transformDTOToEntity(element)));
}
@Override
public void delete(I id) {
log.trace("<== Inside delete() of generic service ==>");
repository.deleteById(id);
}
@Override
public boolean isExist(I id) {
log.trace("<== Inside isExist() of generic service ==>");
return repository.findById(id).isPresent();
}
@Override
public E transformDTOToEntity(D element) {
return null;
}
@Override
public D transformEntityToDTO(E element) {
return null;
}
}
</code></pre>
<h3>Brand DTO</h3>
<pre><code>package com.test.dto;
import java.io.Serializable;
public class BrandDTO implements Serializable{
private static final long serialVersionUID = -8226355260297089645L;
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
</code></pre>
<h3> Mapper</h3>
<pre><code>package com.test.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import com.test.dto.BrandDTO;
import com.test.model.BrandMaster;
@Mapper
public interface BrandMapper {
BrandMapper INSTANCE = Mappers.getMapper(BrandMapper.class);
BrandDTO brandMasterToBrandDTO(BrandMaster brand);
BrandMaster brandDTOToBrandMaster(BrandDTO brand);
}
</code></pre>
<h3>Brand Dao</h3>
<pre><code>package com.test.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.test.model.BrandMaster;
@Repository
public interface BrandDao extends JpaRepository<BrandMaster, Integer>{
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code is good, but some improvements could be made.\nHere are my suggestions:</p>\n<ol>\n<li><p>Use lowercase for first letter of variable. Example:\n<code>BrandService BrandService;</code> rename to: <code>BrandService brandService;</code></p>\n</li>\n<li><p>Use <a href=\"https://projectlombok.org/features/all\" rel=\"nofollow noreferrer\">Lombok</a> annotations like <code>@Getter</code>, <code>@Setter</code>, <code>@Slf4j</code> and various <code>@*Constructors</code> and so on. It will make code clean and readable.</p>\n</li>\n<li><p>Use <a href=\"https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-controller-advice\" rel=\"nofollow noreferrer\">ControllerAdvice</a> for global error handling:</p>\n<pre class=\"lang-java prettyprint-override\"><code>@ControllerAdvice\n@Slf4j\npublic class ExceptionHandlingAdvice {\n private final Clock clock = Clock.systemDefaultZone();\n\n @ExceptionHandler(Exception.class)\n public ResponseEntity<ErrorResponse> handleException(Exception ex) {\n return handleException(ex.getLocalizedMessage(), HttpStatus.INTERNAL_SERVER_ERROR);\n }\n\n private ResponseEntity<ErrorResponse> handleException(String message, HttpStatus httpStatus) {\n log.error("Error: " + message);\n ErrorResponse errorResponse = ErrorResponse.of(Instant.now(clock), message);\n return new ResponseEntity<>(errorResponse, httpStatus);\n }\n}\n</code></pre>\n</li>\n<li><p>Use dedicated errors for specific cases.</p>\n</li>\n<li><p>It is a good approach to move <code>@Transactional</code> to the service layer. If you call two DAO-methods on the service level they use the same transaction.</p>\n</li>\n<li><p>Can't see any reason for a DTO to implement <code>Serializable</code>.</p>\n</li>\n<li><p>Use lowercase in URI paths, example:\n<code>@RequestMapping(path = "**/Brand")</code> should be <code>**/brand</code></p>\n</li>\n<li><p>Consider to add <a href=\"https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-requestmapping-consumes\" rel=\"nofollow noreferrer\">content-negotiation</a> (for respective HTTP-headers <em>Accept</em> and <em>Content-Type</em>) to your controller-mapping:</p>\n<pre class=\"lang-java prettyprint-override\"><code>@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)\n</code></pre>\n</li>\n<li><p>In my opinion you use a too abstract path mapping:</p>\n</li>\n</ol>\n<ul>\n<li><code>@RequestMapping(path = "**/Brand")</code> could be <code>@RequestMapping(path = "/api/brand")</code></li>\n<li><code>@GetMapping(path = "**/{id}")</code> could be <code>@GetMapping(path = "/{id}")</code></li>\n</ul>\n<ol start=\"10\">\n<li><p>You could use <code>@ResponseStatus</code> to <a href=\"https://www.baeldung.com/spring-response-status\" rel=\"nofollow noreferrer\">Set HTTP Status Code</a> and return just object instead of wrapping into <code>ResponseEntity</code></p>\n<pre class=\"lang-java prettyprint-override\"><code>@PostMapping\n@ResponseStatus(HttpStatus.CREATED)\npublic BrandDTO save(@RequestBody BrandDTO Brand) {\n // omitted\n return brand;\n}\n</code></pre>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:03:43.097",
"Id": "446663",
"Score": "0",
"body": "Thank you so much for the review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T17:23:04.663",
"Id": "506696",
"Score": "0",
"body": "Great post, many good suggestions to __use available Spring/Lombok annotations__ to simplify and enhance readability. (suggested an edit with links, fixed typos + some re-formatting)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:53:52.957",
"Id": "229580",
"ParentId": "229340",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "229580",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T19:33:52.010",
"Id": "229340",
"Score": "4",
"Tags": [
"java",
"generics",
"rest",
"spring",
"crud"
],
"Title": "Rest Api with generic crud operations"
}
|
229340
|
<p>I have been trying to optimize a code snippet which finds the optimal threshold value in a <code>n_patch * 256 * 256</code> probability map to get the highest Jaccard index against ground truth mask.</p>
<p>Consider a single probability map (<code>256 * 256</code>) and its ground truth (<code>256 * 256</code> with <code>1</code> and <code>0</code>). To find the optimal threshold value which yields the highest Jaccard index against the ground truth, we loop over all the probability <code>i</code> in the probability map and threshold the probability map using <code>i</code> and then compute the Jaccard index of the thresholded map against the ground truth. After looping over through all probabilities (65536 in total since 256*256) in the probability map, we will have a threshold value which generates the highest Jaccard index. </p>
<p>The attached code is computing <code>n_patch</code> probability maps at once instead of a single probability map. However, even I have optimized the implementation as vectorized as possible, the code still runs around <strong>330</strong> seconds on a GPU. Note the attached code is also executable on CPU, it will use an Nvidia GPU if you have one. A modified version of the code can be found further down.</p>
<p>The data are available in <a href="https://drive.google.com/open?id=1-4_gxUJRyAh8bl4fV9Ix0Qv4VMURpXNO" rel="nofollow noreferrer">here (around 24MB)</a>. The file named <code>mask.npy</code> is a <code>n_patch * 256 * 256</code> binary (contains only 0 and 1) and the file named <code>pred_mask.npy</code> is a <code>n_patch * 256 * 256</code> probability (contains 0 to 1 probability) maps. </p>
<p>The threshold method is implemented <code>gen_mask</code> and it takes a 3D <code>pred_mask</code> and threshold on each dimension based on a threshold value vector. The <code>jaccard</code> computes the Jarrard index of a 3D thresholded mask agains the ground truth and returned a <code>n_patch * 1</code> shape array. </p>
<pre><code>import numpy as np
import torch
import time
USE_CUDA = torch.cuda.is_available()
def gen_mask(mask_pred, threshold):
mask_pred = mask_pred.clone()
mask_pred[:, :, :][mask_pred[:, :, :] < threshold] = 0
mask_pred[:, :, :][mask_pred[:, :, :] >= threshold] = 1
return mask_pred
def jaccard(prediction, ground_truth):
union = prediction + ground_truth
union[union == 2] = 1
intersection = prediction * ground_truth
union = union.sum(axis=(1, 2))
intersection = intersection.sum(axis=(1, 2))
ji_nonezero_union = intersection[union != 0] / union[union != 0]
ji = ji = torch.zeros(intersection.shape)
if USE_CUDA:
ji = ji.cuda()
ji[union != 0] = ji_nonezero_union
return ji
groundtruth_masks = np.load('./masks.npy')
pred_mask = np.load('./pred_mask.npy')
n_patch = groundtruth_masks.shape[0]
groundtruth_masks = torch.from_numpy(groundtruth_masks)
groundtruth_masks = groundtruth_masks.type(torch.float)
pred_mask = torch.from_numpy(pred_mask)
vector_pred = pred_mask.view(n_patch, -1)
best_threshold_val = torch.zeros(n_patch)
best_jaccard_idx = torch.zeros(n_patch)
if USE_CUDA:
groundtruth_masks = groundtruth_masks.cuda()
pred_mask = pred_mask.cuda()
vector_pred = vector_pred.cuda()
best_threshold_val = best_threshold_val.cuda()
best_jaccard_idx = best_jaccard_idx.cuda()
start = time.time()
# I think this outer for loop is inevitable since
# vector_pred.shape[1] is 65536
# so we cannot simply create a matrix with n_patch * 65536 * 256 * 256
# which is too large even for a GPU to handle
for i in range(vector_pred.shape[1]):
cur_threshold_val = vector_pred[:, i]
cur_threshold_val = cur_threshold_val.reshape(n_patch, 1, 1)
thresholded_mask = gen_mask(pred_mask.squeeze(), cur_threshold_val)
thresholded_mask = thresholded_mask.type(torch.float)
ji = jaccard(thresholded_mask, groundtruth_masks)
cur_threshold_val = cur_threshold_val.squeeze()
best_threshold_val[ji >
best_jaccard_idx] = cur_threshold_val[ji > best_jaccard_idx]
best_jaccard_idx[ji > best_jaccard_idx] = ji[ji > best_jaccard_idx]
print(i, '/', vector_pred.shape[1], end="\r")
end = time.time()
print(best_threshold_val)
print(best_jaccard_idx)
print(end - start)
</code></pre>
<p>Also, the output:</p>
<pre class="lang-none prettyprint-override"><code>Best Threshold: tensor([6.8828e-01, 4.7082e-01, 1.2254e-01, 3.4189e-01, 2.8555e-01, 2.4655e-01,
4.9444e-01, 5.9245e-01, 5.0390e-01, 1.7931e-01, 2.3205e-01, 3.8314e-01,
4.5103e-01, 3.6109e-01, 3.4614e-01, 3.8766e-01, 3.6444e-01, 2.3667e-01,
2.0029e-01, 8.0435e-01, 4.9489e-01, 2.8066e-01, 1.4230e-04, 1.8089e-01,
2.2194e-01, 3.7781e-01, 3.5074e-01, 5.4690e-03, 2.6937e-01, 1.7834e-01,
2.2150e-01, 1.8330e-01], device='cuda:0')
Best Jaccard Index: tensor([0.9978, 0.9936, 0.9975, 0.9956, 0.9921, 0.9977, 0.9938, 0.9972, 0.9987,
0.9983, 0.9974, 0.9972, 0.9955, 0.9851, 0.9979, 0.9938, 0.9960, 0.9936,
0.9967, 0.9852, 0.9963, 0.9924, 0.9890, 0.9946, 0.9954, 0.9971, 0.9945,
0.9919, 0.9964, 0.9947, 0.9920, 0.9977], device='cuda:0')
</code></pre>
<p>Any suggestions to optimize the code snippet are welcome!</p>
<hr>
<p>Update:</p>
<p>I managed to speed up the script by 100s using PyTorch logical <code>and</code> and <code>or</code>. However, this operation is only supported for type <code>torch.uint8</code> which means I have to do type conversion. Now the performance is <strong>232</strong> seconds on a GPU. </p>
<p>The following is the modified version:</p>
<pre><code>import numpy as np
import torch
import time
USE_CUDA = torch.cuda.is_available()
def gen_mask(mask_pred, threshold):
mask_pred = mask_pred.clone()
mask_pred[:, :, :][mask_pred[:, :, :] < threshold] = 0
mask_pred[:, :, :][mask_pred[:, :, :] >= threshold] = 1
return mask_pred.type(torch.uint8)
def jaccard(prediction, ground_truth):
union = prediction | ground_truth
intersection = prediction & ground_truth
union = union.sum(axis=(1, 2))
intersection = intersection.sum(axis=(1, 2))
union = union.type(torch.float)
intersection = intersection.type(torch.float)
union_nonzero_idx = union != 0
cur_jaccard_idx = torch.zeros(intersection.shape)
if USE_CUDA:
cur_jaccard_idx = cur_jaccard_idx.cuda()
cur_jaccard_idx[union_nonzero_idx] = intersection[union_nonzero_idx] / union[union_nonzero_idx]
return cur_jaccard_idx
groundtruth_masks = np.load('./masks.npy')
pred_mask = np.load('./pred_mask.npy')
n_patch = groundtruth_masks.shape[0]
groundtruth_masks = torch.from_numpy(groundtruth_masks)
groundtruth_masks = groundtruth_masks.type(torch.uint8)
pred_mask = torch.from_numpy(pred_mask)
vector_pred = pred_mask.view(n_patch, -1)
best_threshold_val = torch.zeros(n_patch)
best_jaccard_idx = torch.zeros(n_patch)
if USE_CUDA:
groundtruth_masks = groundtruth_masks.cuda()
pred_mask = pred_mask.cuda()
vector_pred = vector_pred.cuda()
best_threshold_val = best_threshold_val.cuda()
best_jaccard_idx = best_jaccard_idx.cuda()
start = time.time()
# I think this outer for loop is inevitable since
# vector_pred.shape[1] is 65536
# so we cannot simply create a matrix with n_patch * 65536 * 256 * 256
# which is too large even for a GPU to handle
for i in range(vector_pred.shape[1]):
cur_threshold_val = vector_pred[:, i]
cur_threshold_val = cur_threshold_val.reshape(n_patch, 1, 1)
thresholded_mask = gen_mask(pred_mask.squeeze(), cur_threshold_val)
cur_jaccard_idx = jaccard(thresholded_mask, groundtruth_masks)
cur_threshold_val = cur_threshold_val.squeeze()
best_threshold_val[cur_jaccard_idx >
best_jaccard_idx] = cur_threshold_val[cur_jaccard_idx > best_jaccard_idx]
best_jaccard_idx[cur_jaccard_idx > best_jaccard_idx] = cur_jaccard_idx[cur_jaccard_idx > best_jaccard_idx]
print(i, '/', vector_pred.shape[1], end="\r")
end = time.time()
print(best_threshold_val)
print(best_jaccard_idx)
print(end - start)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T20:53:49.173",
"Id": "446022",
"Score": "1",
"body": "@dfhwze Sorry my bad. I have updated the description with more details. Please let me know if you need me to elaborate more :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T03:30:43.613",
"Id": "446237",
"Score": "0",
"body": "Not sure whether this helps: the `scipy` library has a built-in function for computing the [jaccard distance](https://docs.scipy.org/doc/scipy-0.19.1/reference/generated/scipy.spatial.distance.jaccard.html)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T03:39:03.600",
"Id": "446238",
"Score": "0",
"body": "@GZ0 Thanks for your suggestion. It seems this method only takes two 1D arrays, which unfortunately does not apply for this problem since we essentially have shape `n_patch * 256 * 256` or `n_patch * 65536` (flat the last two-dimension). But thanks for your comment!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T16:51:28.503",
"Id": "446271",
"Score": "1",
"body": "I rolled this back to revision 10. Editing a question based on feedback from answers is outside of policy. If you want to post the new code, please do so in a separate question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T17:25:27.860",
"Id": "446273",
"Score": "2",
"body": "@Reinderien The edits actually happened before I posted my answer and I wrote my answer based on the edited post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T17:50:33.463",
"Id": "446274",
"Score": "0",
"body": "https://codereview.meta.stackexchange.com/questions/9341/what-do-we-do-with-out-of-sync-questions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T10:12:02.533",
"Id": "446313",
"Score": "2",
"body": "I've rolled back the rollback. If anyone has any questions whatsoever about what is happening, see [this meta question](https://codereview.meta.stackexchange.com/q/9341/52915) or find me in [chat](https://chat.stackexchange.com/rooms/8595/the-2nd-monitor)."
}
] |
[
{
"body": "<p>I think a different approach is needed to achieve a better performance. The current approach recomputes the Jaccard similarity from scratch for each possible threshold value. However, going from one threshold to the next, only a small fraction of prediction values change as well as the intersection and the union. Therefore a lot of unnecessary computation is performed.</p>\n\n<p>A better approach can first compute for each patch a histogram of the prediction probabilities given ground truth = 1, using the thresholds as bin edges. The frequency counts in each bin give the amount of predictions affected going from one threshold to the next. Therefore, the Jaccard similarity values for all thresholds can be computed directly from cummulative frequency counts derived from the histogram.</p>\n\n<p>In your case, the prediction probabilities are used directly as thresholds. Therefore the histograms coincide with the inputs sorted by the probabilities. Consider the following example input probablities and true labels:</p>\n\n<pre><code>Label 1 1 0 0 1 0 0 0\nProb 0.9 0.8 0.7 0.6 0.45 0.4 0.2 0.1\n</code></pre>\n\n<p>The labels themselves are also the counts of true positive instances within each interval. Given a threshold <span class=\"math-container\">\\$t\\$</span> and its index <span class=\"math-container\">\\$i\\$</span>, <span class=\"math-container\">\\$|Label \\cap Predicted|\\$</span> is just the sum of labels with indices <span class=\"math-container\">\\$\\leq i\\$</span>, which is the cumulative sum of labels until <span class=\"math-container\">\\$i\\$</span>. Also note that <span class=\"math-container\">\\$|Predicted|=i+1\\$</span> and <span class=\"math-container\">\\$Label\\$</span> is the count of true positive instances. Therefore the Jaccard similarity</p>\n\n<p><span class=\"math-container\">$$\n\\begin{align*}\nJaccard(Label, Predicted) & = \\frac{|Label \\cap Predicted|}{|Label \\cup Predicted|} \\\\\n & = \\frac{|Label \\cap Predicted|}{|Label|+|Predicted|-|Label \\cap Predicted|} \\\\\n & = \\frac{cumsum(Label, i)}{(\\text{# of true positive instances}) + i + 1 - cumsum(Label, i)}\n\\end{align*}\n$$</span></p>\n\n<p>This computation can be easily vectorized for all possible <span class=\"math-container\">\\$i\\$</span>s to get a Jaccard similarity vector for every threshold.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T20:52:10.263",
"Id": "446370",
"Score": "0",
"body": "Thanks for your answer! I think it is a good suggestion. I will need some time to implement this idea and will update the speedup as soon as possible :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T21:29:43.903",
"Id": "446372",
"Score": "1",
"body": "@yiping You're welcome. Just remember that in case you ever want to post **new code** for further improvements it needs to be done in a new post as required by the policy (you see what happened from the comments if this is not obeyed). The new post can link to this post as a reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T00:18:26.260",
"Id": "446380",
"Score": "1",
"body": "So I implement your algorithms and it now runs 0.02s on a GPU and 0.25s on a CPU. This is very impressive! Thanks, mate. Can I update the code in this question for future reference? (I do not need further improvement :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T00:21:27.800",
"Id": "446381",
"Score": "0",
"body": "You can reply to your own question and post the code as an answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T05:51:53.340",
"Id": "229415",
"ParentId": "229341",
"Score": "4"
}
},
{
"body": "<p>Thanks to the answer of @GZ0, the performance of this code snippet is now around <strong>0.0344s</strong> on a GPU and around <strong>0.2511s</strong> on a CPU. The implementation of @GZ0's algorithm is attached. Please do not hesitate to suggest any modifications to make the code snippet more pythonic :)</p>\n\n<pre><code>import timeit\nimport torch\nimport argparse\nimport numpy as np\n\nUSE_CUDA = torch.cuda.is_available()\n\n\ndef find_optimal_threshold(pred_mask, groundtruth_masks):\n n_patch = groundtruth_masks.shape[0]\n\n groundtruth_masks_tensor = torch.from_numpy(groundtruth_masks)\n pred_mask_tensor = torch.from_numpy(pred_mask)\n\n if USE_CUDA:\n groundtruth_masks_tensor = groundtruth_masks_tensor.cuda()\n pred_mask_tensor = pred_mask_tensor.cuda()\n\n vector_pred = pred_mask_tensor.view(n_patch, -1)\n vector_gt = groundtruth_masks_tensor.view(n_patch, -1)\n vector_pred, sort_pred_idx = torch.sort(vector_pred, descending=True)\n vector_gt = vector_gt[torch.arange(vector_gt.shape[0])[\n :, None], sort_pred_idx]\n gt_cumsum = torch.cumsum(vector_gt, dim=1)\n gt_total = gt_cumsum[:, -1].reshape(n_patch, 1)\n predicted = torch.arange(start=1, end=vector_pred.shape[1] + 1)\n if USE_CUDA:\n predicted = predicted.cuda()\n gt_cumsum = gt_cumsum.type(torch.float)\n gt_total = gt_total.type(torch.float)\n predicted = predicted.type(torch.float)\n jaccard_idx = gt_cumsum / (gt_total + predicted - gt_cumsum)\n max_jaccard_idx, max_indices = torch.max(jaccard_idx, dim=1)\n max_indices = max_indices.reshape(-1, 1)\n best_threshold = vector_pred[torch.arange(vector_pred.shape[0])[\n :, None], max_indices]\n best_threshold = best_threshold.reshape(-1)\n\n return best_threshold\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--pred_mask_path', type=str,\n required=False, default='./pred_mask.npy')\n parser.add_argument('--groundtruth_mask_path', type=str, required=False,\n default='./masks.npy')\n parser.add_argument('--run_times', type=int, required=False,\n default=10000)\n args = parser.parse_args()\n groundtruth_masks = np.load(args.groundtruth_mask_path)\n pred_mask = np.load(args.pred_mask_path)\n t = timeit.timeit(lambda: find_optimal_threshold(pred_mask, groundtruth_masks), number=args.run_times)\n print(t / args.run_times, 'seconds')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T05:42:47.700",
"Id": "446395",
"Score": "0",
"body": "Good job. I hope you have verified the correctness of the implementation (e.g., by comparing the results with your earlier implementation). Meanwhile, `gt_total` can actually be retrieved from the last row of `gt_cumsum` rather than computed again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T05:48:09.430",
"Id": "446396",
"Score": "0",
"body": "Timing program execution is normally done using the [`timeit`](https://docs.python.org/3/library/timeit.html#module-timeit) module or `%timeit` / `%%timeit` in IPython."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T05:48:48.027",
"Id": "446397",
"Score": "0",
"body": "Yes, I have verified the correctness. It agrees with the naive implementation. Oh yeah, you are right! I will update it right now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T07:01:54.397",
"Id": "446399",
"Score": "0",
"body": "Putting the entire code block in a string looks ugly. Instead, the code to be measured can be wrapped into a function `test_func` with no arguments and then called by `timeit.timeit(test_func, ...)` (you could find a better function name BTW)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T19:56:12.897",
"Id": "446511",
"Score": "0",
"body": "@GZ0 Thanks for the suggestions :) I have changed them. Cheers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T20:18:55.660",
"Id": "446513",
"Score": "1",
"body": "There's a typo in the name `find_optiaml_threshold`. Also, accessing / updating global variables generally has some performance overhead (although it is probably negligible in this case). A cleaner way is to pass `groundtruth_masks` and `pred_mask` as function arguments so that the function itself can be directly reused by others. And then in the measurement code, which does not need to be global, you make another wrapper function without arguments. The wrapper function can also be a `lambda` such as `timeit.timeit(lambda:find_optimal_threshold(...), ...)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T23:45:50.657",
"Id": "446901",
"Score": "2",
"body": "Welcome to Code Review! While OPs are [encouraged to answer their own questions](https://codereview.stackexchange.com/help/self-answer) bear in mind that [\"_Your answer must meet the standards of a Code Review answer, just like any other answer. **Describe what you changed, and why.** Code-only answers that don't actually review the code are insufficient and are subject to deletion_\"](https://codereview.stackexchange.com/help/someone-answers)... perhaps adding a new question would be a better solution"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T02:49:58.533",
"Id": "446922",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ I will re-edit my answer based on your link as soon as possible :) Thank you!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T01:25:50.643",
"Id": "229482",
"ParentId": "229341",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229415",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T19:40:00.267",
"Id": "229341",
"Score": "4",
"Tags": [
"python",
"numpy",
"vectorization",
"pytorch"
],
"Title": "PyTorch Vectorized Implementation for Thresholding and Computing Jaccard Index"
}
|
229341
|
<p>Inspired by <a href="https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/627" rel="nofollow noreferrer">This LeetCode Question</a>.</p>
<p>Instead of checking if every layer is symmetric, it instead checks if any <em>aren't</em>. This allows the program to leave early is an early layer fails the test. I'm looking for performance mostly, as I loop through each element in the list, instead of each layer. All feedback is appreciated and considered.</p>
<pre><code>"""
This program determines if a given binary
tree is a mirror of itself
Example:
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
"""
def is_symmetric(tree: list) -> bool:
"""
Returns if the passed tree is symmetric
:param tree: A list representing a binary tree
"""
interval = 2
start = 0
end = 1
for _ in range(len(tree)):
# Find next layer
layer = tree[start:end]
# Determine if layer isn't mirror
if layer != list(reversed(layer)):
return False
# Setup for next layer
start = end
end = (2 ** interval) - 1
interval += 1
return True
if __name__ == '__main__':
assert is_symmetric([1, 2, 2, 3, 4, 4, 3]) # True
assert not is_symmetric([1, 2, 2, None, 3, None, 3]) # False
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T16:04:52.613",
"Id": "446146",
"Score": "0",
"body": "Clearly, `[1, 2, 2, None, 4, 4, None]` is symmetric. If `None` represents a missing node, would `[1, 2, 2, None, 4, 4]` be considered symmetric? As in, incomplete layers could be considered padded with `None`'s?"
}
] |
[
{
"body": "<p>Pretty good! Only two points:</p>\n\n<p>Remove your parens from this -</p>\n\n<pre><code>end = (2 ** interval) - 1\n</code></pre>\n\n<p>due to order of operations. Also, your function is a good candidate for doc tests. Read up here: <a href=\"https://docs.python.org/3.7/library/doctest.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3.7/library/doctest.html</a> This will allow you to move your <code>assert</code>s into the docstring of the function itself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T03:17:40.403",
"Id": "229353",
"ParentId": "229343",
"Score": "1"
}
},
{
"body": "<p>Two things:</p>\n\n<ol>\n<li><p>The function may fail for a tree with an incomplete last layer. For example:</p>\n\n<pre><code>is_symmetric([1, 2, 2, 3, 4, 3]) returns True, but it should be False.\n</code></pre></li>\n</ol>\n\n<p>This can be fixed by checking if layers have the expected length.</p>\n\n<pre><code>if len(layer) != (end - start) or layer != list(reversed(layer)):\n return False\n</code></pre>\n\n<ol start=\"2\">\n<li><p>The for loop iterates more times than needed. The loop only needs to run for each layer in the tree, not for each node. A tree with n layers has 2**n - 1 nodes. It may not matter for small trees, but a tree with 20 layers has over a million nodes. Replace the for loop with a while loop:</p>\n\n<pre><code>while start < len(tree):\n...\n</code></pre></li>\n<li><p>Okay, three things. <code>interval</code> isn't needed. Use:</p>\n\n<pre><code>end = 2 * end + 1\n</code></pre></li>\n</ol>\n\n<p>The revised routine:</p>\n\n<pre><code>def is_symmetric(tree: list) -> bool:\n \"\"\"\n Returns if the passed tree is symmetric\n\n :param tree: A list representing a binary tree\n \"\"\"\n\n start = 0\n end = 1\n\n while start < len(tree):\n # Find next layer\n layer = tree[start:end]\n\n # Determine if layer isn't mirror\n if len(layer) != (end - start) or layer != list(reversed(layer)):\n return False\n\n # Setup for next layer\n start = end\n end = 2 * end + 1\n\n return True\n\n\nif __name__ == '__main__':\n tests = [\n ([1], True),\n ([1, 2, 2, 3, 4, 4, 3], True),\n ([1, 2, 2, None, 3, None, 3], False),\n ([1, 2, 2, 3, 4, 3], False)\n ]\n\n for n, (test, answer) in enumerate(tests):\n result = is_symmetric(test)\n print(f\"Test {n} {'Pass' if answer==result else 'FAIL'}: is_symetric({test})\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T06:51:58.987",
"Id": "229356",
"ParentId": "229343",
"Score": "2"
}
},
{
"body": "<p>As pointed out by @RootToo:</p>\n\n<ol>\n<li>You are looping more times than needed. You loop <code>n</code> times for a list of length <code>n</code>, where you only need to be looping <a href=\"https://docs.python.org/3/library/stdtypes.html#int.bit_length\" rel=\"nofollow noreferrer\"><code>n.bit_length()</code></a> times.</li>\n<li>The function may fail for a tree with an incomplete last layer.</li>\n</ol>\n\n<p>The additional point I'd like to cover is you are also comparing too much.</p>\n\n<p>With your binary tree <code>[1,2,2,3,4,4,3]</code>, you check that:</p>\n\n<pre><code>[1] == list(reversed([1]))\n[2,2] == list(reversed([2,2]))\n[3,4,4,3] == list(reversed([3,4,4,3]))\n</code></pre>\n\n<p>You only need to check:</p>\n\n<pre><code>[2] == list(reversed([2]))\n[3,4] == list(reversed([4,3]))\n</code></pre>\n\n<p>This results in double the number of elements to compare, plus allocation of double the length of slices, which means copying double the number of elements that actually needed to be copied. Plus we don't need to test the first layer, because a list of length 1 is always equal to its reverse, which is the only case of an odd number of items that complicates splitting the layers in half.</p>\n\n<p>Moreover, <code>list(reversed(layer))</code> is inefficient, as a reverse iterator needs to be created, and then the <code>list()</code> needs to traverse this newly created reverse iterator to realize the required list. <code>layer[::-1]</code> does the same thing, but without needing to create the intermediate reverse iterator.</p>\n\n<p>Revised code:</p>\n\n<pre><code>def is_symmetric(tree: list) -> bool:\n \"\"\"\n Returns if the passed tree is symmetric\n\n :param tree: A list representing a binary tree\n \"\"\"\n\n n = len(tree)\n layers = n.bit_length()\n\n if n != 2 ** layers - 1:\n return False\n\n start = 1\n length = 1\n\n for _ in range(1, layers):\n mid = start + length\n end = mid + length\n if tree[start:mid] != tree[end-1:mid-1:-1]:\n return False\n\n start = end\n length *= 2\n\n return True\n\nif __name__ == '__main__':\n\n # Test harness copied from RootToo's answer:\n\n tests = [\n ([], True), # Check empty list as special case, too!\n ([1], True),\n ([1, 2, 2, 3, 4, 4, 3], True),\n ([1, 2, 2, None, 3, None, 3], False),\n ([1, 2, 2, 3, 4, 3], False)\n ]\n\n for n, (test, answer) in enumerate(tests):\n result = is_symmetric(test)\n print(f\"Test {n} {'Pass' if answer==result else 'FAIL'}: is_symetric({test})\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T15:51:16.877",
"Id": "229387",
"ParentId": "229343",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "229356",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T20:17:18.490",
"Id": "229343",
"Score": "5",
"Tags": [
"python",
"performance",
"python-3.x",
"tree"
],
"Title": "Symmetric Tree Check in Python"
}
|
229343
|
<p>Basically I have an url which looks like this structurally speaking:</p>
<p><code>http://www.my-site.com/topic1/topic2/topic3/topic4/topic5</code></p>
<p>and I want to do 2 things to it:</p>
<pre><code>1. check the structure and validate it
2. replace both topic3 and topic4 with a new parameters called topic6
</code></pre>
<p>This is my solution for now but I am interested to build something more optimize.</p>
<pre><code>if ((url.match(/\//g) || []).length === 7) {
const arr = url.split('/');
const topic5 = arr.pop();
arr.pop();
arr.pop();
arr.push('topic6', topic5);
return arr.join('/');
}
</code></pre>
<p>So as you can see, for the fact that I am not very good at regular expressions I have used another approach which doesn't look that good. I basically check for the number of <code>/</code> in the string, if tey are 7 it means that the structure of the url is good and that on this type of url I should apply the next steps. After that I grab the last param of the url and also remove it and next after that I remove the last 2 parameters and add the new one instead along with the <code>topic5</code>.</p>
<p>In case you you have a better approach, please let me know. I think that it can be done by writing less number of lines of code but as I said, I am not very familiar with regular expressions.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T16:20:19.930",
"Id": "446270",
"Score": "1",
"body": "Welcome to CR! The requirements for the function are unclear to me. What sort of characters constitute the placeholders for `topic1`, `topic2` etc? Are they all alphanumeric? Do we always have 5? Counting 7 slashes seems brittle--what if `https://` is omitted? Please provide a variety of valid and invalid examples with explanation for each one as to why it's valid/invalid. Additionally, why do you need to optimize this? I'm surprised if you're running into performance issues on strings that are just a few characters long. Please elaborate. What is the \"slip approach\"? Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T17:56:51.490",
"Id": "446275",
"Score": "0",
"body": "topic1, topic2, etc are slugs, can contain also numbers, - sign but also diacritics from different languages or cyrilic chars. We don't have always 5 because the website have different type of urls but I must detect only the ones which have 5 and do these changes on them. I want to optimize not necessary for performance but for write better code which has more quality."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T18:55:37.077",
"Id": "446277",
"Score": "0",
"body": "Thanks for the clarifications, that helps! Can you provide some sample inputs/outputs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T05:43:10.650",
"Id": "446523",
"Score": "0",
"body": "Input: http://www.my-site.com/topic1/topic2/topic3/topic4/topic5 ; Output: http://www.my-site.com/topic1/topic2/topic6/topic5"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T21:50:02.077",
"Id": "446694",
"Score": "1",
"body": "Please add relevant details to the question itself as an Edit. This puts the full story all in one place. Volunteers don't want to have to read a running dialogue in comments to fully understand the scope of the code to be reviewed."
}
] |
[
{
"body": "<blockquote>\n <p>Your codes looks pretty good, even though (?:I'm not really a code reviewer])*.</p>\n</blockquote>\n\n<p>If you wish to use regular expressions though for validations, there are several strategies that you can follow up, given that validations with regular expressions are a bit difficult to do and it'd be good to know some details of the boundaries and limitations. </p>\n\n<p>My guesswork is that maybe here we would start with some expression similar to:</p>\n\n<pre><code>^((?:https?:\\/\\/)(?:w{3}\\.)?my-site\\.com(?:\\/[a-z0-9]{1,64}){2}\\/)[a-z0-9]{1,64}(\\/[a-z0-9]{1,64}\\/)[a-z0-9]{1,64}(\\/?)$\n</code></pre>\n\n<h3><a href=\"https://regex101.com/r/vCY51o/1/\" rel=\"nofollow noreferrer\">Demo</a></h3>\n\n<p>which has some quantifiers to just limit the sizes, if that'd be desired, and since we'd be replacing the third and fifth topics, then we'd define our replacement similar to,</p>\n\n<pre><code>$1some_other_topic_3$2some_other_topic_5$3\n</code></pre>\n\n<p>for instance. </p>\n\n<hr>\n\n<p>There would be many other options that you could modify your expression with, such as, </p>\n\n<pre><code>^((?:https?:\\/\\/)(?:w{3}\\.)?my-site\\.com(?:\\/[^\\/\\r\\n]+){2}\\/)[^\\/\\r\\n]+(\\/[^\\/\\r\\n]+\\/)[^\\/\\r\\n]+(\\/?)$\n</code></pre>\n\n<p>which would depend on how you'd like to validate the URLs. </p>\n\n<h3><a href=\"https://regex101.com/r/Cd29vB/1/\" rel=\"nofollow noreferrer\">Demo 2</a></h3>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const regex = /^((?:https?:\\/\\/)(?:w{3}\\.)?my-site\\.com(?:\\/[^\\/\\r\\n]+){2}\\/)[^\\/\\r\\n]+(\\/[^\\/\\r\\n]+\\/)[^\\/\\r\\n]+(\\/?)$/gmi;\nconst str = `http://www.my-site.com/topic1/topic2/topic3/topic4/topic5\nhttps://www.my-site.com/topic1/topic2/topic3/topic4/topic5\nhttp://my-site.com/topic1/topic2/topic3/topic4/topic5\nhttps://my-site.com/topic1/topic2/topic3/topic4/topic5\nhttp://www.my-site.com/topic1/topic2/topic3/topic4/topic5/\nhttps://www.my-site.com/topic1/topic2/topic3/topic4/topic5/\nhttp://my-site.com/topic1/topic2/topic3/topic4/topic5/\nhttps://my-site.com/topic1/topic2/topic3/topic4/topic5/\nhttps://notmy-site.com/topic1/topic2/topic3/topic4/topic5/`;\nconst subst = `$1some_other_topic_3$2some_other_topic_5$3`;\n\n\nconst result = str.replace(regex, subst);\n\nconsole.log(result);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p>If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of <a href=\"https://regex101.com/r/vCY51o/1/\" rel=\"nofollow noreferrer\">regex101.com</a>. If you'd like, you can also watch in <a href=\"https://regex101.com/r/vCY51o/1/debugger\" rel=\"nofollow noreferrer\">this link</a>, how it would match against some sample inputs.</p>\n\n<hr>\n\n<h3>RegEx Circuit</h3>\n\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\n<p><a href=\"https://i.stack.imgur.com/XUV2v.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XUV2v.png\" alt=\"enter image description here\"></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T21:44:18.317",
"Id": "229537",
"ParentId": "229358",
"Score": "0"
}
},
{
"body": "<p>You seek to:</p>\n\n<ol>\n<li>validate the url as coming from your site domain, then</li>\n<li>replace the 3rd and 4th directories/topics with a single/new directory/topic.</li>\n</ol>\n\n<p>This is a simple matter of preserving the substrings that you want to keep as \"capture groups\" and writing the new replace substring between the two capture groups.</p>\n\n<p>In my demo, the new topic will be <code>FOO</code>. I'm using negated character classes to match the directory names -- this is relatively \"loose\" validation. If you require a tighter validation rule, see the 2nd snippet. Click on <kbd>Run code snippet</kbd> below to see the resultant output.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const regex = /^((?:https?:\\/\\/)(?:w{3}\\.)?my-site\\.com\\/(?:[^/]+\\/){2})[^/]+\\/[^/]+(\\/[^/]+)$/;\n url = 'http://www.my-site.com/topic1/Topic2/topic3/topic4/слизень',\n replacement = '$1FOO$2';\n\ndocument.write(url.replace(regex, replacement));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>To tighten the validation beyond non-slashes as directory substrings AND extend the characters classes to include multibyte letters, you will need to manually expand the character classes to include the letters that you expect to qualify. Please have a read of <a href=\"https://stackoverflow.com/q/30225552/2943403\">Regular expression with the cyrillic alphabet</a>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const regex = /^((?:https?:\\/\\/)(?:w{3}\\.)?my-site\\.com\\/(?:[À-žа-яa-z\\d-]+\\/){2})[À-žа-яa-z\\d-]+\\/[À-žа-яa-z\\d-]+(\\/[À-žа-яa-z\\d-]+)$/i;\n url = 'http://www.my-site.com/Schnecke/to-pic2/topic3/naaktslak/слизень',\n replacement = '$1FOO$2';\n\ndocument.write(url.replace(regex, replacement));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T22:15:58.747",
"Id": "229667",
"ParentId": "229358",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T08:14:46.743",
"Id": "229358",
"Score": "2",
"Tags": [
"javascript",
"regex",
"validation"
],
"Title": "Manipulate urls with regular expressions instead of the slip approach"
}
|
229358
|
<p>I have made an operator (surrounded by others operators) for training a model in sagemaker in airflow and I have doubts how would it be more readable or more pythonic. First I did this:</p>
<pre><code>transform_data = BashOperator(
task_id = 'transform_data',
bash_command = 'blabla')
container = get_image_uri(boto3.Session().region_name,
'xgboost', repo_version='0.90-1')
estimator = sagemaker.estimator.Estimator(
container,
role = 'AmazonSageMaker-ExecutionRole-201903XXX',
train_instance_count = 1,
train_instance_type = 'ml.m4.2xlarge',
output_path = f"s3://production/models/{domain}-{product}-{today}",
train_use_spot_instances = True,
hyperparameters = {'num_round':'400',
'objective':'binary:logistic',
'eval_metric':'error@0.1',
'gamma':'5',
'scale_pos_weight':'10'}
)
s3_input_train = sagemaker.s3_input(s3_data='s3://production/data/{domain}-{product}-{today}/train_data.csv',
content_type='text/csv')
s3_input_validation = sagemaker.s3_input(s3_data='s3://production/data/{domain}-{product}-{today}/validation_data.csv',
content_type='text/csv')
job_name_timestamp = datetime.today().strftime('%Y-%m-%d-%H-%M-%S')
train_config = training_config(estimator=estimator,
inputs = {'train':s3_input_train,
'validation':s3_input_validation},
job_name = f'{domain}-{product}-{job_name_timestamp}')
model_training = SageMakerTrainingOperator(
task_id = 'model_training',
config = train_config,
wait_for_completion = True)
model_deployment = OperatorX(blabla)
</code></pre>
<p>But then, I have gathered all the information about the training operator, motivated by not stopping the succession of operators in the code. So I have coded:</p>
<pre><code>transform_data = BashOperator(
task_id = 'transform_data',
bash_command = 'blabla')
model_training = SageMakerTrainingOperator(
task_id = 'model_training',
config = training_config(
estimator=sagemaker.estimator.Estimator
(
container=get_image_uri(boto3.Session().region_name,
'xgboost', repo_version='0.90-1'),
role = 'AmazonSageMaker-ExecutionRole-20190XXXX',
train_instance_count = 1,
train_instance_type = 'ml.m4.2xlarge',
output_path = f"s3://production/models/{domain}-{product}-{today}",
train_use_spot_instances = True,
hyperparameters = {'num_round':'400',
'objective':'binary:logistic',
'eval_metric':'error@0.1',
'gamma':'5',
'scale_pos_weight':'10'}
),
inputs =
{
'train':sagemaker.s3_input(s3_data='s3://production/data/{domain}-{product}-{today}/train_data.csv',
content_type='text/csv'),
'validation':sagemaker.s3_input(s3_data='s3://production/data/{domain}-{product}-{today}/validation_data.csv',
content_type='text/csv')
},
job_name = f"{domain}-{product}-{datetime.today().strftime('%Y-%m-%d-%H-%M-%S')}"),
wait_for_completion = True)
model_deployment = OperatorX(blabla)
</code></pre>
<p>What do you think? Which is the best way? Doesn't it matter at all and both can be considered as good (or bad) code? thanks for your answers</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T09:19:15.350",
"Id": "229361",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"comparative-review",
"amazon-web-services"
],
"Title": "SageMakerTrainingOperator in Airflow"
}
|
229361
|
<p>In my project I have to make curve-fitting with a lots of parameters, so scipy curve_fit struggles to find the answer. </p>
<p>For example:
<span class="math-container">\$\ c_0 + c_1 \cdot cos (b_0 + b_1\cdot x + b_2\cdot x^2+ b_3\cdot x^3)\$</span>
,where <span class="math-container">\$ c_i, b_i \$</span>
are the params to determine.</p>
<p>That's why I made a method which first tries to fit the desired function to only a little part of the data, then extends the area of fitting and uses the last optimal parameters as initial values for the next cycle. I wrote this object oriented, however I'm not sure it's nicely written or I don't know it's necessary to make it OO. I've never been taught OOP, this is what I've understood so far. The class has an attribute called obj. That's because it's embedded in a PyQt5 project, so I need the plot there. I modified the code to work on it's own. <a href="https://drive.google.com/file/d/1gH8KzVyGBSsNdejJ12e4gb_9hktMyWcj/view?usp=sharing" rel="nofollow noreferrer">Here</a> is an example dataset you can try.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
########## these functions are actually imported from another file ###########
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(value - array)).argmin()
return array[idx], idx
def cos_fit1(x,c0, c1, b0, b1):
return c0 + c1*np.cos(b0 + b1*x)
def cos_fit2(x,c0, c1, b0, b1, b2):
return c0 + c1*np.cos(b0 + b1*x + b2*x**2)
def cos_fit3(x,c0, c1, b0, b1, b2, b3):
return c0 + c1*np.cos(b0 + b1*x + b2*x**2 + b3*x**3)
def cos_fit4(x,c0, c1, b0, b1, b2, b3, b4):
return c0 + c1*np.cos(b0 + b1*x + b2*x**2 + b3*x**3 + b4*x**4)
def cos_fit5(x,c0, c1, b0, b1, b2, b3, b4, b5):
return c0 + c1*np.cos(b0 + b1*x + b2*x**2 + b3*x**3 + b4*x**4 + b5*x**5)
##############################################################################
class FitOptimizer(object):
"""Class to help achieve better fitting results."""
def __init__(self, x, y, ref, sam, func=None, p0=None):
self.x = x
self.y = y
self.ref = ref
self.sam = sam
if not isinstance(self.x, np.ndarray):
try:
self.x = np.asarray(self.x)
except:
raise
if not isinstance(self.y, np.ndarray):
try:
self.y = np.asarray(self.y)
except:
raise
if not isinstance(self.ref, np.ndarray):
try:
self.ref = np.asarray(self.ref)
except:
pass
if not isinstance(self.sam, np.ndarray):
try:
self.sam = np.asarray(self.sam)
except:
pass
if len(self.ref) == 0 or len(self.sam) == 0:
self._y_norm = self.y
else:
self._y_norm = (self.y - self.ref - self.sam) / (2 *
np.sqrt(self.sam * self.ref))
self.func = func
if p0 is None:
self.p0 = []
else:
self.p0 = p0
self.popt = self.p0
self._init_set = False
self.obj = None
self.counter = 0
def set_initial_region(self, percent, center):
""" Determines the initial region to fit"""
self._init_set = True
_, idx = find_nearest(self.x, center)
self._upper_bound = np.floor(idx + (percent/2)*(len(self.x) + 1))
self._lower_bound = np.floor(idx - (percent/2)*(len(self.x) + 1))
self._upper_bound = self._upper_bound.astype(int)
self._lower_bound = self._lower_bound.astype(int)
if self._lower_bound < 0:
self._lower_bound = 0
if self._upper_bound > len(self.x):
self._upper_bound = len(self.x)
self._x_curr = self.x[self._lower_bound:self._upper_bound]
self._y_curr = self._y_norm[self._lower_bound:self._upper_bound]
def _extend_region(self, extend_by=0.2):
""" Extends region of fit"""
self._new_lower = np.floor(self._lower_bound - extend_by*len(self.x))
self._new_upper = np.floor(self._upper_bound + extend_by*len(self.x))
self._new_lower = self._new_lower.astype(int)
self._new_upper = self._new_upper.astype(int)
self._lower_bound = self._new_lower
self._upper_bound = self._new_upper
if self._new_lower < 0:
self._new_lower = 0
if self._new_upper > len(self.x):
self._new_upper = len(self.x)
self._x_curr = self.x[self._new_lower:self._new_upper]
self._y_curr = self._y_norm[self._new_lower:self._new_upper]
def _make_fit(self):
""" Makes fit """
try:
if len(self._x_curr) == len(self.x):
return True
self.popt, self.pcov = curve_fit(self.func, self._x_curr, self._y_curr,
maxfev = 200000, p0 = self.p0)
self.p0 = self.popt
except RuntimeError:
if len(self.popt) > 4:
self.p0[:3] = self.popt[:3] + np.random.normal(0, 100, len(self.popt)-3)
else:
self.p0 = self.popt + np.random.normal(0,100, len(self.popt))
self.popt, self.pcov = curve_fit(self.func, self._x_curr, self._y_curr,
maxfev = 200000, p0 = self.p0)
def _fit_goodness(self):
""" r^2 value"""
residuals = self._y_curr - self.func(self._x_curr, *self.popt)
ss_res = np.sum(residuals**2)
ss_tot = np.sum((self._y_curr - np.mean(self._y_curr))**2)
return 1 - (ss_res / ss_tot)
def _show_fit(self):
""" Shows fit on self.obj """
try:
self.obj.plot(self._x_curr, self._y_curr, 'k-', label = 'Affected data')
self.obj.plot(self._x_curr, self.func(self._x_curr, *self.popt),
'r--', label = 'Fit')
self.obj.show()
except Exception as e:
print(e)
def run(self, r_extend_by, r_threshold=0.9, max_tries=10000):
if self._init_set == False:
raise ValueError('Set the initial conditions.')
self._make_fit()
while self._fit_goodness() > r_threshold:
self._extend_region(r_extend_by)
self._make_fit()
self.counter +=1
if self._make_fit() == True:
self._show_fit()
return self.popt
break
if self.counter == max_tries:
self._show_fit()
return np.zeros_like(self.popt)
break
while self._fit_goodness() < r_threshold:
self._make_fit()
self.counter +=1
if self.counter == max_tries:
self._show_fit()
return np.zeros_like(self.popt)
break
""" EXAMPLE """
a, b, c, d = np.loadtxt('test.txt', delimiter = ',', unpack = True )
f = FitOptimizer(a, b, c, d, func = cos_fit3)
f.obj = plt
f.p0 = [1,1,1,1,1,1]
f.set_initial_region(0.2, 2.4)
f.run(r_extend_by = 0.1, r_threshold = 0.85)
</code></pre>
<p>I appreciate any improvements in the code.</p>
|
[] |
[
{
"body": "<h2>Don't repeat yourself</h2>\n\n<p>Your family of <code>cos_fit</code> functions can call the full-form function, e.g.</p>\n\n<pre><code>def cos_fit1(x,c0, c1, b0, b1):\n return cos_fit5(x, c0, c1, b0, b1, 0, 0, 0, 0)\n</code></pre>\n\n<p>You may also want to consider using built-in polynomial support, e.g. <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.polynomial.polynomial.polyval.html#numpy.polynomial.polynomial.polyval\" rel=\"nofollow noreferrer\">https://docs.scipy.org/doc/numpy/reference/generated/numpy.polynomial.polynomial.polyval.html#numpy.polynomial.polynomial.polyval</a></p>\n\n<p>As for these expressions:</p>\n\n<pre><code> self._upper_bound = np.floor(idx + (percent/2)*(len(self.x) + 1))\n self._lower_bound = np.floor(idx - (percent/2)*(len(self.x) + 1))\n</code></pre>\n\n<p>reuse the inner term:</p>\n\n<pre><code>delta = percent * (1 + len(self.x)) / 2\nself._upper_bound = np.floor(idx + delta)\nself._lower_bound = np.floor(idx - delta)\n</code></pre>\n\n<h2>No-op except</h2>\n\n<p>Delete this:</p>\n\n<pre><code> except:\n raise\n</code></pre>\n\n<p>It doesn't do anything helpful.</p>\n\n<p>As for your exception-swallowing</p>\n\n<pre><code> except:\n pass\n</code></pre>\n\n<p>this is a deeply bad idea. You need to narrow the exception type caught to the one you're actually expecting. If the program spends any length of time in the <code>try</code> block, this form of <code>except</code> will prevent Ctrl+C break from working.</p>\n\n<h2>Order of operations</h2>\n\n<pre><code>(self.y - self.ref - self.sam) / (2 *\n np.sqrt(self.sam * self.ref))\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>(self.y - self.ref - self.sam) / 2 / np.sqrt(self.sam * self.ref)\n</code></pre>\n\n<p>Similarly, <code>1 - (ss_res / ss_tot)</code> doesn't need parens.</p>\n\n<h2>This is a comment</h2>\n\n<pre><code>def _make_fit(self):\n \"\"\" Makes fit \"\"\"\n</code></pre>\n\n<p>No kidding! Either your comments should add more than the method name, or you should just delete them.</p>\n\n<h2>No-op <code>break</code></h2>\n\n<pre><code> return np.zeros_like(self.popt)\n break\n</code></pre>\n\n<p>The <code>break</code> is never executed due to the <code>return</code>, so you can delete it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T12:44:57.637",
"Id": "229375",
"ParentId": "229362",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T09:20:32.920",
"Id": "229362",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"scipy"
],
"Title": "Many parameter curve-fitting"
}
|
229362
|
<p>In this program, there is a list of <code>Holder</code>s that is managed by a singleton class. Each of the <code>Holder</code>s keeps a copy of the external resource (represented by a String here). When adding a new <code>Holder</code> via <code>addHolder()</code>, the current value of the external resource is copied. At anytime, the external resource can update its value and all previously added <code>Holder</code>s are notified to update their values (simplified with <code>updateHolders(String)</code> here). The aim is to make sure each <code>Holder</code>'s copy of the external resource is up-to-date.</p>
<p>Please review the following examples to demonstrate my progressive improvements on achieving concurrency control:</p>
<pre><code>import java.util.Queue;
import java.util.concurrent.*;
public class ThreadTest1 {
private static final ThreadTest1 INSTANCE = new ThreadTest1();
private Queue<Holder> holders = new ConcurrentLinkedQueue<>();
public static ThreadTest1 instance() {
return INSTANCE;
}
public void updateHolders(String resource) {
System.out.println("Updating holders " + holders);
holders.forEach(h -> h.setResource(resource));
System.out.println("Finished updating holders " + holders);
}
public void addHolder(int delay) throws InterruptedException {
Holder holder = new Holder();
holder.setResource(ExternalResource.getResource());
System.out.println("Adding holder " + holder);
TimeUnit.SECONDS.sleep(delay); // more work to do
holders.add(holder);
System.out.println("Finished adding holder " + holder);
}
public Queue<Holder> getHolders() {
return holders;
}
public static class Holder {
private static int holderId = 1;
private int id;
private String resource;
public Holder() {
this.id = holderId++;
}
public void setResource(String resource) {
this.resource = resource;
}
@Override
public String toString() {
return "H" + id + "[" + resource + "]";
}
}
public static class ExternalResource {
private static String resource = "A";
public static String getResource() {
return resource;
}
public static void setResource(String resource) {
ExternalResource.resource = resource;
System.out.println("External resource changed to " + resource);
ThreadTest1.instance().updateHolders(resource);
}
}
public static Callable<Void> callAddHolderWithDelay(int delay) {
return () -> {
ThreadTest1.instance().addHolder(delay);
return null;
};
}
public static Callable<Void> callSetResource(String resource) {
return () -> {
ExternalResource.setResource(resource);
return null;
};
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.submit(callAddHolderWithDelay(1));
TimeUnit.SECONDS.sleep(1);
executor.submit(callAddHolderWithDelay(5));
TimeUnit.SECONDS.sleep(1);
executor.submit(callSetResource("B"));
TimeUnit.SECONDS.sleep(1);
executor.submit(callAddHolderWithDelay(1));
TimeUnit.SECONDS.sleep(5);
System.out.println(ThreadTest1.instance().getHolders());
executor.shutdown();
}
}
</code></pre>
<p>Output:</p>
<pre><code>Adding holder H1[A]
Adding holder H2[A]
Finished adding holder H1[A]
External resource changed to B
Updating holders [H1[A]]
Finished updating holders [H1[B]]
Adding holder H3[B]
Finished adding holder H3[B]
Finished adding holder H2[A]
[H1[B], H3[B], H2[A]]
</code></pre>
<p>First test is the most basic one without any concurrency control, as you can see an unfortunate event happened and <code>H2</code> ended up with holding <code>A</code> instead of <code>B</code>.</p>
<p>An improvement was made to make sure the above won't happen as follow (only highlighting the changes):</p>
<pre><code>public class ThreadTest2 {
private static final ThreadTest2 INSTANCE = new ThreadTest2();
private Queue<Holder> holders = new ConcurrentLinkedQueue<>();
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public static ThreadTest2 instance() {
return INSTANCE;
}
public void updateHolders(String resource) {
lock.writeLock().lock();
System.out.println("Updating holders " + holders);
holders.forEach(h -> h.setResource(resource));
System.out.println("Finished updating holders " + holders);
lock.writeLock().unlock();
}
public void addHolder(int delay) throws InterruptedException {
lock.readLock().lock();
Holder holder = new Holder();
holder.setResource(ExternalResource.getResource());
System.out.println("Adding holder " + holder);
TimeUnit.SECONDS.sleep(delay); // more work to do
holders.add(holder);
System.out.println("Finished adding holder " + holder);
lock.readLock().unlock();
}
...
</code></pre>
<p>Output:</p>
<pre><code>Adding holder H1[A]
Adding holder H2[A]
Finished adding holder H1[A]
External resource changed to B
Finished adding holder H2[A]
Updating holders [H1[A], H2[A]]
Finished updating holders [H1[B], H2[B]]
Adding holder H3[B]
Finished adding holder H3[B]
[H1[B], H2[B], H3[B]]
</code></pre>
<p>Test 2 is a typical use of a read write lock and the result is correct. However, it is not very efficient as you can see <em>Adding holder H3[B]</em> was pushed until after <em>Finished updating holders [H1[B], H2[B]]</em>, but really it should not be blocked because <em>External resource changed to B</em> had happened already and hence <em>Adding holder H3[B]</em> could pick up the new value with no reason to wait for <em>Finished updating holders [H1[B], H2[B]]</em>.</p>
<p>So what I can optimise here is a non-blocking <code>addHolder</code> and a blocking <code>updateHolders</code>, where it blocks only when there is one or more threads working on <code>addHolder</code> already (e.g. <code>H2</code>) but fine to ignore subsequent calls to <code>addHolder</code> (e.g. <code>H3</code>) as they are good on their own to get the latest value. I used a list of locks to implement that:</p>
<pre><code>public class ThreadTest3 {
private static final ThreadTest3 INSTANCE = new ThreadTest3();
private Queue<Holder> holders = new ConcurrentLinkedQueue<>();
private Queue<Lock> locks = new ConcurrentLinkedQueue<>();
public static ThreadTest3 instance() {
return INSTANCE;
}
public void updateHolders(String resource) {
locks.forEach(l -> l.lock());
System.out.println("Updating holders " + holders);
holders.forEach(h -> h.setResource(resource));
System.out.println("Finished updating holders " + holders);
}
public void addHolder(int delay) throws InterruptedException {
Lock lock = new ReentrantLock();
lock.lock();
locks.add(lock);
Holder holder = new Holder();
holder.setResource(ExternalResource.getResource());
System.out.println("Adding holder " + holder);
TimeUnit.SECONDS.sleep(delay); // more work to do
holders.add(holder);
System.out.println("Finished adding holder " + holder);
lock.unlock();
locks.remove(lock);
}
</code></pre>
<p>Output:</p>
<pre><code>Adding holder H1[A]
Adding holder H2[A]
Finished adding holder H1[A]
External resource changed to B
Adding holder H3[B]
Finished adding holder H3[B]
Finished adding holder H2[A]
Updating holders [H1[A], H3[B], H2[A]]
Finished updating holders [H1[B], H3[B], H2[B]]
[H1[B], H3[B], H2[B]]
</code></pre>
<p>Test 3 result is correct and is more efficient than before as you can see <em>Adding holder H3[B]</em> now happens before <em>Finished updating holders [H1[B], H3[B], H2[B]]</em>, hence <code>addHolder</code> is non-blocking. I can settle here, but further optimisation seems possible as <code>H1</code> wasn't updated until <em>Finished adding holder H2[A]</em> where <code>updateHolders</code> was waiting for it to finish, THEN perform the update for all. It can definitely update <code>H1</code> first as <code>addHolder</code> for <code>H1</code> had finished and only wait for <code>H2</code>, so <code>H1</code> can get the update earlier.</p>
<p>Please point out if my use of the list of locks is something an overkill and can be simplified to achieve the same, also whether my further optimisation can be achieved by what means? Thank you.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T09:35:35.427",
"Id": "446083",
"Score": "1",
"body": "Could you add a specification for the code itself? It's not entirely clear to me what is the target API here (e.g. what are `Holder` and `ExternalResource`, and how do they relate to one another?), and some qualification would make it easier to understand your intention with the locking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T17:38:06.213",
"Id": "446178",
"Score": "0",
"body": "@VisualMelon Added a paragraph to describe more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T03:32:50.423",
"Id": "448605",
"Score": "0",
"body": "Can you give an example input and and the expected behavior?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T09:22:51.983",
"Id": "229363",
"Score": "3",
"Tags": [
"java",
"performance",
"thread-safety",
"concurrency"
],
"Title": "Concurrency control between a non-blocking and a blocking methods"
}
|
229363
|
<p><a href="https://leetcode.com/problems/house-robber-iii/" rel="nofollow noreferrer">https://leetcode.com/problems/house-robber-iii/</a><br></p>
<p>Please review for performance<br></p>
<blockquote>
<p>The thief has found himself a new place for his thievery again. There
is only one entrance to this area, called the "root." Besides the
root, each house has one and only one parent house. After a tour, the
smart thief realized that "all houses in this place forms a binary
tree". It will automatically contact the police if two directly-linked
houses were broken into on the same night.</p>
<p>Determine the maximum amount of money the thief can rob tonight
without alerting the police.</p>
<hr>
<p>Gilad's comment: In simple words - you can't take the sum of parent and child. they have to be no directly connected nodes. for example Max(level 1 +3, level 2)</p>
<hr>
<p><strong>Example 1:</strong></p>
<pre><code>Input: [3,2,3,null,3,null,1]
3
/ \
2 3
\ \
3 1
</code></pre>
<p>Output: 7 </p>
<p>Explanation: Maximum amount of money the thief can rob = 3
+ 3 + 1 = 7. </p>
<p><strong>Example 2:</strong></p>
<pre><code>Input: [3,4,5,1,3,null,1]
3
/ \
4 5
/ \ \
1 3 1
</code></pre>
<p>Output: 9 </p>
<p>Explanation: Maximum amount of money the thief can rob = 4 +
5 = 9.</p>
</blockquote>
<pre><code>using System;
using System.Collections.Generic;
using GraphsQuestions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TreeQuestions
{
/// <summary>
/// https://leetcode.com/problems/house-robber-iii/
/// </summary>
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
[TestClass]
public class HouseRobber3
{
[TestMethod]
public void TestMethod1()
{
// 3 // level 1
// / \
// 2 3 // level 2
// \ \
// 3 1 // level 3
TreeNode root = new TreeNode(3);
root.left = new TreeNode(2);
root.left.right = new TreeNode(3);
root.right = new TreeNode(3);
root.right.right = new TreeNode(1);
//Output: 7
//Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
HouseRobber3Class robber = new HouseRobber3Class();
Assert.AreEqual(7, robber.Rob(root));
}
}
public class HouseRobber3Class
{
//we can't rob directly connected nodes.
// so we can rob root which is level 1 + level 3
// or only level 2 which is root.left+root.right
// we need to find the max of the two
public int Rob(TreeNode root)
{
return Helper(root, new Dictionary<TreeNode, int>());
}
public int Helper(TreeNode root, Dictionary<TreeNode, int> hash)
{
if (root == null)
{
return 0;
}
if (hash.ContainsKey(root))
{
return hash[root];
}
int sum = 0;
if (root.left != null)
{
sum += Helper(root.left.left, hash) + Helper(root.left.right, hash);
}
if (root.right != null)
{
sum += Helper(root.right.left,hash) + Helper(root.right.right, hash);
}
sum = Math.Max(root.val + sum, Helper(root.left, hash) + Helper(root.right, hash));
hash.Add(root, sum);
return sum;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T11:41:17.087",
"Id": "446093",
"Score": "0",
"body": "I really have no idea wherefore the spec is asking here: could you clarify what the actual problem is, because the fluff isn't helping. What do the numbers in the tree mean? What constitutes breaking in?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T11:43:37.020",
"Id": "446094",
"Score": "0",
"body": "so you can only get a sum from level 1 + 3 because they are not directly connected, or the sum of level 2. so you basically need to rob levels of the tree which are not connected and get the maximum sum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T11:45:31.523",
"Id": "446095",
"Score": "0",
"body": "So the task is to find the maximum sum where no two contributors are parent and child? Would you mind putting such a description in the body, because the quoted text isn't working for me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T11:52:21.077",
"Id": "446096",
"Score": "0",
"body": "@VisualMelon I know what you mean it took me a while to understand what do they want."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T12:14:04.397",
"Id": "446099",
"Score": "0",
"body": "Max(level 1 +3, level 2) is only for these 2 examples. In general, no directly connected nodes can be taken into account to calculate the sum. Calculate the max sum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T12:15:27.450",
"Id": "446100",
"Score": "0",
"body": "@dfhwze this is of course an example of directly connected nodes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T12:16:35.267",
"Id": "446101",
"Score": "0",
"body": "Sure, but for the general explanation I don't see why this specific case has to be included."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T12:22:06.053",
"Id": "446104",
"Score": "1",
"body": "@dfhwze I am just trying to make this clearer, you guys, I didn't invent anything ... this is the way leetcode phrase this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T13:42:11.000",
"Id": "446115",
"Score": "0",
"body": "I get that, but we are trying to get this question phrased better for people to get what is exactly requested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T14:29:28.663",
"Id": "446132",
"Score": "1",
"body": "@Gilad I edited your post so the whole thing is easier to read, I hope you don't mind. Otherwise, don't hesitate to rollback the edit"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T14:32:01.967",
"Id": "446135",
"Score": "2",
"body": "Also, if i may offer an explanation of what I understood. You cannot rob two houses that are connected (that is, parent/child or child/parent). So, in the first example, you can rob house 3, meaning you can't rob anything in the second \"level\", because both are connected to the node 3 that we just robbed. We can then rob the third \"level\"' because they aren't *directly* connected to the node 3 that we just robbed. Maybe you can try to use this more \"step by step\" explanation in your post to make it clearer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T14:35:59.893",
"Id": "446137",
"Score": "0",
"body": "@IEatBagels I would copy paste that into the question :)"
}
] |
[
{
"body": "<p>Your testcases are far too simple to be certain your algorithm works. This might be an issue on the challenge's side. Both these testcases have symmetrical solutions. For these testcases, it's best to always rob every second layer. No test cases cover instances where the left side of the tree might follow a different pattern to the right side. Take for example the testcase:</p>\n\n<pre><code>{ 3, 8, 5, 1, 3, 10, 1 }\n</code></pre>\n\n<p>On the left branch, you'd expect the 8 to be robbed on the second layer, while the right side is more beneficial to rob the third layer, foregoing the first layer altogether. </p>\n\n<p>That said, your algorithm appears to handle this correctly. That, along with the caching you do, appears to be working quite well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T15:01:07.190",
"Id": "229385",
"ParentId": "229368",
"Score": "4"
}
},
{
"body": "<p>The </p>\n\n<pre><code>public int Helper(TreeNode root, Dictionary<TreeNode, int> hash)\n</code></pre>\n\n<p>method can (and should) be <code>private</code>. It is not meant to be called from outside the class. </p>\n\n<p>The helper method would also benefit from a (short) explaining comment: How does the recursion work, and what is cached?</p>\n\n<p>The helper method does 6 recursive calls to itself. A dictionary is used to cache the results, so that the tree is essentially traversed only once, but that dictionary has to be passed down in the recursive calls.</p>\n\n<p>A slightly different approach makes the cache obsolete and reduces the numbers of recursive calls. The idea is to compute <em>two sums</em> for every node:</p>\n\n<ul>\n<li>the maximal amount that can be achieved by robbing this house, and</li>\n<li>the maximal amount that can be achieved by not robbing this house.</li>\n</ul>\n\n<p>The implementation is simple and almost self-explaining:</p>\n\n<pre><code>public int Rob(TreeNode root)\n{\n var (with, without) = Helper(root);\n return Math.Max(with, without);\n}\n\n// Recursively determine the maximal amount that can be achieved\n// - by robbing this house,\n// - by skipping this house.\nprivate (int, int) Helper(TreeNode root)\n{\n if (root == null)\n {\n return (0, 0);\n }\n\n var (leftWith, leftWithout) = Helper(root.left);\n var (rightWith, rightWithout) = Helper(root.right);\n\n // If we rob this house then we cannot rob its immediate children:\n var sumWith = root.val + leftWithout + rightWithout;\n // Otherwise we can rob the immediate children (and pick the\n // maximal possible sum for both):\n var sumWithout = Math.Max(leftWith, leftWithout) + Math.Max(rightWith, rightWithout);\n\n return (sumWith, sumWithout);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T21:04:27.910",
"Id": "231281",
"ParentId": "229368",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229385",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T11:30:03.677",
"Id": "229368",
"Score": "4",
"Tags": [
"c#",
"programming-challenge",
"tree",
"dynamic-programming"
],
"Title": "LeetCode: House Robber III C#"
}
|
229368
|
<p>The following problem is from <a href="https://leetcode.com/problems/reverse-words-in-a-string-iii/" rel="nofollow noreferrer">LeetCode</a>:</p>
<blockquote>
<p>Given a string, you need to reverse the order of characters in each
word within a sentence while still preserving whitespace and initial
word order.</p>
<p>Example 1: Input: "Let's take LeetCode contest"</p>
<p>Output: "s'teL ekat edoCteeL tsetnoc"</p>
</blockquote>
<p>The following code is working correctly, but its runtime is 8 ms, which is only faster than 42.44% of Java online submissions. <strong>How to make the following code faster?</strong></p>
<pre><code>class Solution {
public String reverseWords(String s) {
StringBuilder sb = new StringBuilder();
int length = s.length();
int start = 0;
int end = 0;
while(start < length){
while( (end < length) && (s.charAt(end) != ' ')){
end++;
}
doReverse(s, start, end -1, sb);
start = ++end;
}
return sb.toString();
}
private void doReverse(String s, int start, int end, StringBuilder sb){
if(start >0)
sb.append(" ");
while(end >= start){
sb.append(s.charAt(end));
end--;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T14:20:18.637",
"Id": "446130",
"Score": "0",
"body": "Hello. Unfortunately, I don't think the code is entirely correct, because some characters may be expressed with two code units, and those must not be reversed. See https://dzone.com/articles/the-right-way-to-reverse-a-string-in-java for more info. Good luck!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T14:36:10.490",
"Id": "446139",
"Score": "0",
"body": "@Elegie if Leetcode accepted the results I guess we can consider it as working as intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T15:56:12.407",
"Id": "446145",
"Score": "0",
"body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 6 → 5"
}
] |
[
{
"body": "<p>First: if you look into <code>StringBuilder.reverse()</code> you'll encounter some extra work for some Unicode symbols needing two chars for a symbol (called a <em>surrogate pair</em>), which should <em>not</em> be reversed.</p>\n\n<p>But let's not consider that.</p>\n\n<ul>\n<li>Provide exactly the needed capacity for StringBuilder.</li>\n<li><code>sb.append(' ')</code> is faster than for <code>\" \"</code>.</li>\n<li><code>end - 1</code> not needed.</li>\n</ul>\n\n<p>So:</p>\n\n<pre><code>public String reverseWords(String s) {\n int length = s.length();\n if (length <= 1) {\n return s;\n }\n StringBuilder sb = new StringBuilder(length);\n int start = 0;\n int end = 0;\n while (start < length) {\n while (end < length && s.charAt(end) != ' ') {\n ++end;\n }\n doReverse(s, start, end, sb);\n start = ++end;\n }\n return sb.toString();\n}\n\nprivate void doReverse(String s, int start, int end, StringBuilder sb) {\n if (start > 0)\n sb.append(' ');\n while (end > start){\n --end;\n sb.append(s.charAt(end));\n }\n}\n</code></pre>\n\n<p>In general using toCharArray could be faster:</p>\n\n<pre><code>public String reverseWords(String str) {\n char[] s = s.toCharArray();\n int length = s.length;\n if (length <= 1) {\n return s;\n }\n int start = 0;\n int end = 0;\n while (start < length) {\n while (end < length && s.charAt(end) != ' ') {\n ++end;\n }\n doReverse(s, start, end);\n start = ++end;\n }\n return new String(s);\n}\n\nprivate void doReverse(char[] s, int start, int end) {\n while (--end > start){\n char ch = s[start];\n s[start] = s[end];\n s[end] = ch;\n ++start;\n }\n}\n</code></pre>\n\n<p>If you would <em>inline</em> doReverse for extra speed, you would need a copy of the changing parameters.</p>\n\n<pre><code> // doReverse(char[] s, int start, int end)\n int end2 = end;\n while (--end2 > start){\n char ch = s[start];\n s[start] = s[end2];\n s[end2] = ch;\n ++start;\n }\n</code></pre>\n\n<p>Now we should be twice as fast (wild guess).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T15:52:19.433",
"Id": "446144",
"Score": "0",
"body": "thank your for your answer, lot of learning."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T14:56:50.637",
"Id": "229384",
"ParentId": "229370",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229384",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T12:06:26.920",
"Id": "229370",
"Score": "3",
"Tags": [
"java",
"algorithm",
"strings",
"reinventing-the-wheel"
],
"Title": "LeetCode Reverse Words in a String without using any java library"
}
|
229370
|
<p>I'm learning C#, I programmed some things in java, and I would like to have a feedback on my C# code. <br>The exercise is from <code>codility</code>.</p>
<blockquote>
<p>The goal is to rotate array A K times; that is, each element of A will
be shifted to the right K times.</p>
<p>Write a function:</p>
<p>class Solution { public int[] solution(int[] A, int K); }</p>
<p>that, given an array A consisting of N integers and an integer K,
returns the array A rotated K times.</p>
<p>For example, given</p>
<pre><code>A = [3, 8, 9, 7, 6]
K = 3 the function should return [9, 7, 6, 3, 8]. Three rotations were made:
[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8] For another example, given
A = [0, 0, 0]
K = 1 the function should return [0, 0, 0]
</code></pre>
<p>Given</p>
<pre><code>A = [1, 2, 3, 4]
K = 4 the function should return [1, 2, 3, 4]
</code></pre>
</blockquote>
<p><br>And this is my code. It gives 100% but maybe something can be improved.Thanks in advice.</p>
<pre><code>using System;
// you can also use other imports, for example:
// using System.Collections.Generic;
// you can write to stdout for debugging purposes, e.g.
// Console.WriteLine("this is a debug message");
class Solution {
public int[] solution(int[] A, int K) {
int len = A.Length;
int[] B = new int[len];
if(len > 0 && K % len != 0 )
{
for ( int i = 0; i < len; i++)
{
B[(K + i) % len] = A[i];
}
}
else
{
return A;
}
return B;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T12:34:13.183",
"Id": "446105",
"Score": "0",
"body": "Now that I'm looking at it, I believe B could be created inside the if... so if no cyclic rotation is needed computer could save the creation of a potentially large array"
}
] |
[
{
"body": "<h3>Good Practices</h3>\n\n<ul>\n<li>✔ I like the fact you don't rotate if the array's length is a multiplication of <code>K</code>.</li>\n<li>✔ As you stated in the comments, the second array <code>B</code> gets created too early, since in some occasions it would be created in vain.</li>\n</ul>\n\n<h3>Review</h3>\n\n<ul>\n<li>The challenge is clearly written for Java:<code>class Solution { public int[] solution(int[] A, int K); }</code>. The provided signature deserves its own review (casing conventions, static members, meaningful member names). However, if you 'cannot' change the signature given to you, I would be consistent and use <code>N</code> instead of <code>len</code> for the array's length.</li>\n<li>You sometimes return the provided array and sometimes create a new one. I would make this very clear in the specification. A consumer should know whether or when a copy is returned. This affects further usage of the object.</li>\n<li>You should guard against the source array being null.</li>\n<li>How would you handle a negative value of <code>K</code>? If you think about it, a left rotation is just the inverse of a right rotation.</li>\n<li>Nested statements could have been prevented by inverting the if-statement and exiting early. Less nested statements generally increase readability.</li>\n<li>For bigger arrays you should check <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.buffer.blockcopy?view=netframework-4.8\" rel=\"nofollow noreferrer\">Buffer.BlockCopy</a> to optimize copying sections of an array to another array. You could see a rotation as copying 2 sections from one array to another given a pivot. Check out <a href=\"https://jorgecandeias.github.io/2019/02/23/algorithm-cyclic-rotation-in-csharp/\" rel=\"nofollow noreferrer\">this article</a> about the subject.</li>\n<li>If you can change the signature, make a static class with static method, use a meaningful method name <code>RotateRight</code> with arguments <code>array</code> and <code>count</code> and make it clear whether in-place rotation is performed or a new array is created.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T14:19:47.993",
"Id": "229382",
"ParentId": "229371",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229382",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T12:31:33.543",
"Id": "229371",
"Score": "2",
"Tags": [
"c#",
"algorithm",
"array"
],
"Title": "Codility Cyclic rotation in C#"
}
|
229371
|
<p><a href="https://leetcode.com/problems/house-robber/" rel="nofollow noreferrer">https://leetcode.com/problems/house-robber/</a></p>
<blockquote>
<p>You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed, the only constraint
stopping you from robbing each of them is that adjacent houses have
security system connected and it will automatically contact the police
if two adjacent houses were broken into on the same night.</p>
<p>Given a list of non-negative integers representing the amount of money
of each house, determine the maximum amount of money you can rob
tonight without alerting the police.</p>
<p>Example 1:</p>
</blockquote>
<pre><code> Input: [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and
then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4. Example 2:
</code></pre>
<p><br></p>
<blockquote>
<p>Example 2: <br>
Input: [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2),
rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.</p>
</blockquote>
<pre><code>using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ArrayQuestions
{
/// <summary>
/// https://leetcode.com/explore/interview/card/top-interview-questions-easy/97/dynamic-programming/576/
/// </summary>
[TestClass]
public class HouseRobber
{
[TestMethod]
public void HouseRobberTest()
{
int[] nums = {1, 2, 3, 1};
HouseRobberClass robber = new HouseRobberClass();
Assert.AreEqual(4, robber.Rob(nums));
}
[TestMethod]
public void HouseRobber2Test()
{
int[] nums = { 1, 2, 3, 1 };
HouseRobberClass robber = new HouseRobberClass();
Assert.AreEqual(4, robber.Rob2(nums));
}
}
public class HouseRobberClass
{
private int[] _mem;
//option 1 for a solution - this is easier for me to think this way
public int Rob(int[] nums)
{
_mem = Enumerable.Repeat(-1, nums.Length).ToArray();
return Helper(nums, 0);
}
private int Helper(int[] nums, int index)
{
if (index >= nums.Length)
{
return 0;
}
if (_mem[index] >= 0)
{
return _mem[index];
}
_mem[index] = Math.Max(Helper(nums, index + 2) + nums[index], Helper(nums, index + 1));
return _mem[index];
}
// option 2 for a solution
public int Rob2(int[] nums)
{
if (nums.Length == 0)
{
return 0;
}
int[] memo = new int[nums.Length + 1];
memo[0] = 0;
memo[1] = nums[0];
for (int i = 1; i < nums.Length; i++)
{
int val = nums[i];
memo[i + 1] = Math.Max(memo[i], memo[i - 1] + val);
}
return memo[nums.Length];
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your first solution's time complexity is non-trivial to determine, and it won't work for long lists because it'll run out of stack, while your second solution obviously needs linear time (optimal) and is unlikely to run out of memory, so I would scrap the first one right away.</p>\n\n<p>The first solution is also inferior because of the <code>_mem</code> member. There is no reason to create this in <code>Rob</code>, and there is no reason to make it a member. Making it a member means:\n - this code can't be called concurrently\n - it leaves memory hanging around once the method exists\n - it is susceptible to interference by other members\n - it is hard to reason about than a variable because it is removed from the method that use it</p>\n\n<p>One nice solution would be to make <code>_mem</code> a local variable, and <code>Helper</code> a local function in <code>Rob</code>: that way you don't have to pass <code>nums</code> and <code>_mem</code> around, and there is no way to mis-use the code. Then you can make all these methods <code>static</code>.</p>\n\n<h2>Naming</h2>\n\n<p>The naming could be better:</p>\n\n<ul>\n<li><code>_mem</code> and <code>memo</code> are both cryptic (<code>_mem</code> is providing memoisation, and <code>memo</code> is arguably not)</li>\n<li><code>Rob</code> and <code>Rob2</code> convey almost nothing</li>\n<li><code>Helper</code> says <em>nothing at all</em> (what is it helping? what does it do?)</li>\n</ul>\n\n<h2>Documentation</h2>\n\n<ul>\n<li>Please take the time to add documentation. It doesn't matter if you are practising for an interview: real code needs documentation (so that it can be consumed and maintained), writing it is a skill worth practising, and doing so helps you to better reason about your code and solidify edge-case behaviour.</li>\n</ul>\n\n<h2>Tests</h2>\n\n<p>The tests are limited and not very good. They do not test the case where you need to 'skip' a pair (e.g. <code>9, 1, 1, 9</code>) and do not cover any edge cases.</p>\n\n<p>Both methods will throw on a <code>NullReferenceException</code> on <code>null</code> input, when they should probably throw a nice <code>ArgumentException</code> so that the caller knows immediately what they did wrong: ideally this would be tested.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T13:58:59.870",
"Id": "446122",
"Score": "0",
"body": "I hope OP takes advice to heart and starts documenting a bit better next challenge. This is a recurring issue :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T14:21:36.903",
"Id": "446131",
"Score": "1",
"body": "@dfhwze It's not like OP is under any obligation to to listen to all advices in the review, especially when it comes to documentation in a coding challenge. I know I wouldn't do it :p"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T13:53:28.343",
"Id": "229379",
"ParentId": "229372",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229379",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T12:34:24.543",
"Id": "229372",
"Score": "1",
"Tags": [
"c#",
"programming-challenge",
"comparative-review"
],
"Title": "LeetCode: House Robber I C#"
}
|
229372
|
<p>I have this code where I want to go trough 3 levels and it doesn't seem to work if there are only 2 or 1 levels! What's wrong with my query? </p>
<pre><code>select lvl1.category_id AS l1, lvl1.parent_id AS l1, lvl1.title AS l1,
lvl2.category_id AS l2, lvl2.parent_id AS l2, lvl2.title AS l2
,
lvl3.category_id AS l3, lvl3.parent_id AS l3, lvl3.title AS l3
from category AS lvl1
LEFT JOIN category AS lvl2
ON lvl2.parent_id=lvl1.category_id
LEFT JOIN category AS lvl3
ON lvl2.category_id=lvl3.parent_id
WHERE CASE WHEN lvl3.category_id='84'
THEN lvl3.category_id='84' ELSE (
CASE WHEN lvl3.category_id!='84'
AND lvl2.category_id='84'
THEN lvl2.category_id='84'
ELSE (
CASE WHEN lvl2.category_id!='84'
AND lvl1.category_id='84'
THEN lvl1.category_id='84'
END
)
END
)
END
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T12:51:36.393",
"Id": "446107",
"Score": "2",
"body": "Not working code is off topic here, move it to stack overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T13:08:01.803",
"Id": "446110",
"Score": "0",
"body": "What do you mean by levels"
}
] |
[
{
"body": "<p>As i got -1 already and it still will hit my stats will post answer that worked for me:</p>\n\n<pre><code>SELECT L1.category_id AS step1, L2.category_id AS step2, L3.category_id AS step3 , L1.title AS title1, L2.title AS title2, L3.title AS title3\n\nFROM nordigen_category AS L1\n\nLEFT JOIN nordigen_category AS L2\nON L2.category_id=L1.parent_id\n\nLEFT JOIN nordigen_category AS L3\nON L2.parent_id=L3.category_id\n\nWHERE L1.category_id='84'\n</code></pre>\n\n<p>Less code and does what i want on every LVL.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T13:53:08.070",
"Id": "446118",
"Score": "2",
"body": "Good for you that you found it out. For next questions, if your code is not working correctly, it is off-topic for this site. You might try [Stack Overflow](https://stackoverflow.com/help/how-to-ask) if you can word the question in a way that fits the criteria on that page. Once your code works correctly, you're welcome to ask a new question here and we can then help you improve it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T14:03:37.767",
"Id": "446123",
"Score": "0",
"body": "I know Stack Overflow. .. Just i m banned for questions. .. Also i thought this is for review code that works but `not works as planned`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T14:04:43.970",
"Id": "446124",
"Score": "3",
"body": "When in doubt, read through our help center: https://codereview.stackexchange.com/help/on-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T05:21:14.973",
"Id": "446391",
"Score": "0",
"body": "I do not need it. .."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T05:26:35.867",
"Id": "446392",
"Score": "1",
"body": "You might not need it, but it can he helpful nonetheless."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T13:47:08.107",
"Id": "229378",
"ParentId": "229373",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "229378",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T12:44:06.803",
"Id": "229373",
"Score": "-3",
"Tags": [
"sql",
"mysql"
],
"Title": "Find items in 3 or less levels CASE WHEN"
}
|
229373
|
<p>Recently I did an exercise to understand Akka FSM. I implemented a Traffic light system with Akka FSM which changes its state every 30 seconds.</p>
<p>My code is like:</p>
<p><code>LightColour</code>: Enum to encapsulate the traffic light colors.</p>
<pre><code>public enum LightColour {
RED,
YELLOW,
GREEN
}
</code></pre>
<p><code>Light</code>: Class to depict the actual light.</p>
<pre><code>public class Light {
private LightColour lightColourNow;
private long lightStartedAt;
private long numberOfChanges;
public Light(LightColour lightColourNow) {
this.lightColourNow = lightColourNow;
this.lightStartedAt = System.currentTimeMillis();
this.numberOfChanges = 0;
}
public LightColour getLightColourNow() {
return lightColourNow;
}
public long getLightStartedAt() {
return lightStartedAt;
}
public long getNumberOfChanges() {
return numberOfChanges;
}
public long changeLightColor(LightColour lightColourNow) {
System.out.println(String.format("Changing Light colour from %s to %s. Change Number: %d", this.lightColourNow, lightColourNow, this.numberOfChanges));
this.lightColourNow = lightColourNow;
this.numberOfChanges++;
return numberOfChanges;
}
@Override
public String toString() {
return "LightTimeout{" +
"lightColourNow=" + lightColourNow +
", lightStartedAt=" + lightStartedAt +
", numberOfChanges=" + numberOfChanges +
'}';
}
}
</code></pre>
<p><code>LightTimeout</code>: An empty class to denote the event for changing the light.</p>
<pre><code>public class LightTimeout {
}
</code></pre>
<p>Finally, the <code>TrafficLight</code> class, which is an FSM to depict the behavior of a Traffic Light, changing colors every 30 seconds.</p>
<pre><code>import akka.actor.AbstractFSM;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import java.io.IOException;
import java.time.Duration;
public class TrafficLight extends AbstractFSM<LightColour, Light> {
private final int LIGHT_TIME = 30;
public static Props props() {
return Props.create(TrafficLight.class);
}
{
startWith(LightColour.RED, new Light(LightColour.RED));
when(LightColour.RED, matchEvent(LightTimeout.class, ((timeOut, data) -> {
data.changeLightColor(LightColour.YELLOW);
scheduleTimeoutEvent();
return goTo(LightColour.YELLOW);
})));
when(LightColour.YELLOW, matchEvent(LightTimeout.class, (timeOut, data) -> {
data.changeLightColor(LightColour.GREEN);
scheduleTimeoutEvent();
return goTo(LightColour.GREEN);
}));
when(LightColour.GREEN, matchEvent(LightTimeout.class, (timeOut, data) -> {
data.changeLightColor(LightColour.RED);
scheduleTimeoutEvent();
return goTo(LightColour.RED);
}));
scheduleTimeoutEvent();
initialize();
}
private void scheduleTimeoutEvent() {
context().system().scheduler().scheduleOnce(Duration.ofSeconds(LIGHT_TIME), getSelf(), new LightTimeout(), context().dispatcher(), getSelf());
}
public static void main(String[] args) throws IOException {
ActorSystem actorSystem = ActorSystem.create("traffic-light-system");
ActorRef actorRef = actorSystem.actorOf(TrafficLight.props());
System.out.println("Press any key to exit");
System.in.read();
actorSystem.stop(actorRef);
actorSystem.terminate();
}
}
</code></pre>
<p>I am looking for a review of the solution from Java as well as Akka's perspective. Is my solution ok considering the way I have used Akka FSM or can I improve the solution?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T13:57:52.160",
"Id": "229380",
"Score": "1",
"Tags": [
"java",
"akka"
],
"Title": "Akka FSM: Traffic Light Implementation"
}
|
229380
|
<p>This is just a simple counter, i was able to code it in two different ways but i want to know which way is more efficient and which way is more readable.
and which set of code is more "correct" in broad-manner of speaking.
and if there is another entirely different set of code that does the same function ?</p>
<h1>Game Rules</h1>
<blockquote>
<p>This is a simple game , at first it asks the user if they want to go
right or left . if the user picks left ; the program ends and it
displays the "You Win!" message. however if the user picks anything
else other than left ( for example : right ) the program will start a
counter 'z' and it will display a different message for each time the
user chooses the wrong direction or input. i have set it to 4
different messages and then one last message that keeps playing on
repeat until the user picks the correct direction.</p>
</blockquote>
<p>however i feel like that there must be better code to do this.
can you please help?</p>
<p>the first set of code :</p>
<pre><code>#This is a simple game where if you pick left you win,
#but if you pick right you keep going through 4 different levels of
#'you lose' messages and then a last one keeps repeating in a loop.
z = 0
n = input ( "Go left or right? \n" )
while n not in ["left", "Left"]:
if z == 0 :
print ("You lose * 0 ")
z = z+1
n = input ( "Go left or right? \n" )
elif z == 1 :
print ("You lose * 1 ")
z = z+1
n = input ( "Go left or right? \n" )
elif z == 2 :
print ("You lose * 2 ")
z = z+1
n = input ( "Go left or right? \n" )
elif z == 3 :
print ("You lose * 3 ")
z = " "
n = input ( "Go left or right? \n" )
else :
while n not in ["left", "Left" ] :
print ( "You Lose * Infinite" )
n = input ( "Go left or right? \n" )
print ( "\nYou Win!" )
</code></pre>
<p>Second set of code :</p>
<pre><code>#This is a simple game where if you pick left you win,
#but if you pick right you keep going through 4 diffrent levels of
#'you lose' messegses and then a last one keeps repeating on a loop.
v = 0
z = 0
u = 0
x = 0
n = 0
while x == 0 :
n = input ("Go Left or Right?")
while n not in ["left", "Left"] and u == 0 :
if z == 0:
print ( " You lose * 0 ")
elif z == 1:
print ( " You lose * 1 ")
elif z == 2:
print ( " You lose * 2 ")
elif z == 3:
print ( " You lose * 3 ")
else :
print ( " You lose * Infinite " )
u = " "
while z < 4 and v == 0 :
z = z + 1
v = " "
u = 0
v = 0
if n == "left" or n == "Left":
x=" "
print ( " You Win! ")
</code></pre>
<p>final set of code :</p>
<pre><code>user = input ("Go left or right?")
counter = 0
while user not in ["left", "Left"] :
if counter == 0 :
print ("You lose * 0")
elif counter == 1 :
print ("You lose * 1")
elif counter == 2 :
print ("You lose * 2")
elif counter == 3 :
print ("You lose * 3")
else :
print ("You lose * Infinite")
counter = counter + 1
user = input ("Go left or right?")
print ("You Win!")
</code></pre>
|
[] |
[
{
"body": "<p>You're doing some weird things with the scripts. I consider the first to be better, since especially in the second one, you're doing a lot of things with variables which we have better ways to do. I'll point those out separately - lets first have a look at your first script. </p>\n\n<h2>Your first script</h2>\n\n<h3>Code Duplication</h3>\n\n<p>If you find yourself typing the same thing a lot, you're probably doing something wrong. Examples of this are incrementing z and printing the message. </p>\n\n<h3>Variable Names</h3>\n\n<p>Variables should have short but meaningful names. That means that if you find yourself using variables like z or n, you're probably doing something wrong somewhere.</p>\n\n<h3>Loops and termination</h3>\n\n<p>We have a really nice command named <code>break</code> in python. It will terminate the inner-most loop. Using this will obsolete all nested loops your currently have. </p>\n\n<p>I'll keep using while loops here, but you might also want to try the following instead:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import count\n\nfor iteration in count(1):\n # do stuff...\n if we_are_done():\n break\n</code></pre>\n\n<p>this function is basically an infinity list - it's doing exactly the same as:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>iteration = 0\nwhile True:\n iteration += 1\n # do stuff....\n if we_are_done():\n break\n</code></pre>\n\n<p>Which we'll be doing all the time here.</p>\n\n<h3>Keeping that all in mind....</h3>\n\n<pre class=\"lang-py prettyprint-override\"><code>iteration = 0\nwhile True:\n command = input(\"Go Left or Right?\")\n if \"left\" in command.lower(): # Transforms the input to all lowercase. This makes it case-insensitive.\n # We also use \"in\" as membership test, so that whitespace is ignored, and even an command like\n # \"go left\" will be considered valid. \n break # Terminates the loop.\n iteration += 1\n print(f\"You lose * {iteration if iteration < 4 else 'infinity'}\")\nprint(\"\\nYou Win!\")\n</code></pre>\n\n<p>This will do the same as your first script. In the loop, we get the input. We decide if we have won yet, and if we do, we break out. Then we increment the iteration variable. Then we print how often we've moved wrong before, or if it's more than 3 times, we instead print we lost * infinity.</p>\n\n<p>If you're confused by the way we put our variable in that string, you should read up on <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">f-strings</a>. If you're confused by how we print that number, read up on <a href=\"https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator\">ternary expressions</a>. A good python programmer will know both. If the python version allows it, (s)he'll probably also use both. </p>\n\n<h2>Now lets dissect your second function...</h2>\n\n<p>I'll ignore everything I've already said something about regarding the first script.</p>\n\n<h3>Variable instantiation - don't do it unless you have to</h3>\n\n<pre class=\"lang-py prettyprint-override\"><code>v = 0\nz = 0\nu = 0\nx = 0 \nn = 0\n</code></pre>\n\n<p>If you find yourself writing something like this, you should ask yourself if you really need all those. Generally, you'll only instantiate variables in python when you need them, and leave them undefined as long as you don't. IF, and this is a big if, you really need them, you'd write it like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>v = z = u = x = n = 0\n</code></pre>\n\n<h3>How not to loop</h3>\n\n<p>Your outer loop should of course be either with <code>count()</code> or <code>while True:</code>. But the first inner loop is just obsolete alltogether. It cannot run more than once, since there's an <code>u == 0</code> requirement for it to run, and at the end of the loop you unconditionally set it to <code>\" \"</code>, which is a totally different something. Your second inner loop does the exact same thing, but with <code>v</code>. </p>\n\n<p>For both of these, you should at the least change the loops to <code>if</code> statements. However, if you also do the following paragraph, you can just remove them and unindent your code instead.</p>\n\n<h3>Do it just once if you can.</h3>\n\n<p>You check for <code>n not in [\"left\", \"Left\"]</code> twice. Of course, the first time is to guard against the printing, and the second is to <code>break</code> out of your loop. If you just <code>break</code> at the top, you'll have avoided having to do it twice. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T06:31:52.183",
"Id": "446241",
"Score": "1",
"body": "\"In both cases, you can just delete your loops and unindent your code\" - This does not seem correct to me. It would be correct if the u==0 was the only condition of the loop, but since there is an additional condition he needs to replace the while with an if."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T06:35:45.147",
"Id": "446242",
"Score": "0",
"body": "thanks you both for your precious feedback. i did forget to mention that both code sets are functional and work without any errors. i also forgot to mention that i started working learning python 2 days ago so this was the best i could do with what i currently know, however i did try to improve my code. i'll add the new code to my question . if you think it's an improvement on the previous two, please say so !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T06:41:43.350",
"Id": "446243",
"Score": "0",
"body": "As is, yes you'd need to put in if statements. However, if the loop termination is moved up as I suggested, that wouldn't be neccesary. I'll try and make that more clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T06:47:48.403",
"Id": "446244",
"Score": "0",
"body": "New one is better, but you're still having a lot of code duplication, especially in your switch statements. Compare it to the smaller script I have after my header \"keeping that all in mind\". It's good to get in the habit to avoid code duplication, since it will make bug-fixing much easier later on, since you'll only have to fix bugs in one place."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T17:02:10.700",
"Id": "229394",
"ParentId": "229381",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "229394",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T14:15:34.123",
"Id": "229381",
"Score": "7",
"Tags": [
"python",
"game",
"comparative-review"
],
"Title": "A simple game that keeps track of the number of questions asked"
}
|
229381
|
<p>Due to the tightened Youtube API daily quota (that allows to use only ~ 98 search requests per project daily) I've implemented a multi-project system. For this to work you need to create a project/projects, download JSON with client secrets and put it in the credentials directory in the script's folder.</p>
<p>I'm aware that some lines > than 79 symbols, one line even 102 symbols. Just wasn't sure I've needed to adjust every line to PEP recommendation in this case. </p>
<pre><code>import datetime
import json
import os
import random
import webbrowser
from itertools import chain
from pathlib import Path
import furl
import googleapiclient.discovery
import googleapiclient.errors
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from googleapiclient.errors import HttpError
from oauth2client import client
from oauth2client.file import Storage
from tqdm import tqdm
from players.models import Goalie, Skater
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'
SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
BASE_YT_URL = 'https://www.youtube.com/embed/'
SEARCH_PARAMS = {
'part': 'snippet',
'content_type': 'video',
'fields': 'items/id/videoId',
'relevance_language': 'en',
'region_code': 'us',
'video_embeddable': 'true',
'max_results': 1,
}
CREDENTIALS_FOLDER = 'credentials'
CLIENT_SECRETS_FILES = [
'client_secret-1.json',
'client_secret-2.json',
'client_secret-3.json',
'client_secret-4.json',
'client_secret-5.json',
]
CREDENTIALS_FILES = [
'credentials-1.json',
'credentials-2.json',
'credentials-3.json',
'credentials-4.json',
'credentials-5.json',
]
DAILY_LIMIT = ['dailyLimitExceeded', 'quotaExceeded']
REDIRECT_URI = 'http://127.0.0.1:8000/auth_callback/'
TIME_AGO = {
'months': 6,
}
LINK_UPDATE_TIME = 30
ZULU_TIMEZONE = 'Z'
class Command(BaseCommand):
""" """
def handle(self, *args, **options):
players = list(chain(Goalie.objects.all(), Skater.objects.all()))
for player in tqdm(players):
if link_old_or_missing(player):
updated = False
while CREDENTIALS_FILES and not updated:
link = get_link(player.name)
if link:
player.relevant_video = link
player.video_link_updated_at = datetime.datetime.now()
player.save(update_fields=['relevant_video', 'video_link_updated_at'])
updated = True
print(f'{player.name} link is updated!')
else:
print(f'{player.name} link could not be updated with these credentials!')
else:
print(f'{player.name} link is up do date!')
def link_old_or_missing(player):
if player.relevant_video:
return((datetime.date.today() - player.video_link_updated_at).days > LINK_UPDATE_TIME)
else:
return True
def get_storage(*index):
if index:
credentials_file = CREDENTIALS_FILES[index[0]]
else:
credentials_file = random.choice(CREDENTIALS_FILES)
index = CREDENTIALS_FILES.index(credentials_file)
credential_path = os.path.join(get_current_folder(), CREDENTIALS_FOLDER, credentials_file)
return (Storage(credential_path), index)
def credentials_not_valid(credentials):
return not credentials or credentials.invalid
def get_current_folder():
return Path(__file__).parent.absolute()
def get_new_credentials(index):
secrets_file = os.path.join(get_current_folder(), CREDENTIALS_FOLDER, CLIENT_SECRETS_FILES[index])
flow = client.flow_from_clientsecrets(secrets_file, SCOPES, redirect_uri=REDIRECT_URI)
auth_url = flow.step1_get_authorize_url()
webbrowser.open(auth_url)
url = input('Insert URL with code:\n')
code = furl.furl(url).args.get('code', '')
return flow.step2_exchange(code)
def get_link(full_name):
credentials, index = get_storage()
credentials = credentials.get()
if credentials_not_valid(credentials):
credentials = get_new_credentials(index)
get_storage(index)[0].put(credentials)
youtube = googleapiclient.discovery.build(
API_SERVICE_NAME, API_VERSION, credentials=credentials)
request = youtube.search().list(
part=SEARCH_PARAMS['part'],
fields=SEARCH_PARAMS['fields'],
q=full_name,
type=SEARCH_PARAMS['content_type'],
maxResults=SEARCH_PARAMS['max_results'],
publishedAfter=published_after(),
videoEmbeddable=SEARCH_PARAMS['video_embeddable'],
relevanceLanguage=SEARCH_PARAMS['relevance_language'],
regionCode=SEARCH_PARAMS['region_code'],
)
try:
response = request.execute()
print(BASE_YT_URL + response['items'][0]['id']['videoId'])
print(f'{CREDENTIALS_FILES[index]} used successfullly!')
return BASE_YT_URL + response['items'][0]['id']['videoId']
except HttpError:
data = json.loads(HttpError.content.decode('utf-8'))
reason = data['error']['errors'][0]['reason']
if reason in DAILY_LIMIT:
print(f'{CREDENTIALS_FILES[index]} quota is exceeded!')
del CREDENTIALS_FILES[index]
del CLIENT_SECRETS_FILES[index]
return None
def published_after():
date_now = datetime.datetime.now()
return (date_now - relativedelta(**TIME_AGO)).isoformat() + ZULU_TIMEZONE
</code></pre>
|
[] |
[
{
"body": "<h2>Don't repeat yourself</h2>\n\n<p>This:</p>\n\n<pre><code>CLIENT_SECRETS_FILES = [\n 'client_secret-1.json',\n 'client_secret-2.json',\n 'client_secret-3.json',\n 'client_secret-4.json',\n 'client_secret-5.json',\n ]\nCREDENTIALS_FILES = [\n 'credentials-1.json',\n 'credentials-2.json',\n 'credentials-3.json',\n 'credentials-4.json',\n 'credentials-5.json',\n ]\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>CLIENT_SECRET_FILES = [f'client_secret-{i}' for i in range(1, 6)]\nCREDENTIAL_FILES = [f'credentials-{i}' for i in range(1, 6)]\n</code></pre>\n\n<p>Also note that you shouldn't double-pluralize your variable names.</p>\n\n<h2>Empty comments</h2>\n\n<p>For this:</p>\n\n<pre><code>\"\"\" \"\"\"\n</code></pre>\n\n<p>Fill it out, or delete it.</p>\n\n<h2>Generator mutability</h2>\n\n<p>This:</p>\n\n<pre><code> players = list(chain(Goalie.objects.all(), Skater.objects.all()))\n for player in tqdm(players):\n</code></pre>\n\n<p>should not use <code>list</code>, because you never change the contents. Use <code>tuple</code> instead.</p>\n\n<h2>Just <code>break</code></h2>\n\n<p>This:</p>\n\n<pre><code> updated = False\n while CREDENTIALS_FILES and not updated:\n link = get_link(player.name)\n if link:\n player.relevant_video = link\n player.video_link_updated_at = datetime.datetime.now()\n player.save(update_fields=['relevant_video', 'video_link_updated_at'])\n updated = True\n</code></pre>\n\n<p>should not use a flag to break out of the loop. Instead, just issue <code>break</code>.</p>\n\n<h2>Do the simpler thing first</h2>\n\n<p>This:</p>\n\n<pre><code>if player.relevant_video:\n return((datetime.date.today() - player.video_link_updated_at).days > LINK_UPDATE_TIME)\nelse:\n return True\n</code></pre>\n\n<p>is more legible as:</p>\n\n<pre><code>if not player.relevant_video:\n return True\n\ndiff = datetime.date.today() - player.video_link_updated_at\nreturn diff.days > LINK_UPDATE_TIME\n</code></pre>\n\n<h2>Positive logic</h2>\n\n<p>This:</p>\n\n<pre><code>def credentials_not_valid(credentials):\n</code></pre>\n\n<p>can lend itself to confusing logic by the caller. Try to avoid negative predicates, and instead make this a positive predicate (<code>credentials_valid</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T01:41:59.010",
"Id": "229411",
"ParentId": "229383",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229411",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T14:24:07.197",
"Id": "229383",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"django",
"youtube",
"oauth"
],
"Title": "Script that saving most relevant Youtube video for each database object"
}
|
229383
|
<p>I have written a simple RC Filter approximation in python that I have a feeling could be more concise. Are there any obvious improvements?</p>
<pre><code>class EWMA:
def __init__(self, coeff: list, initialValue: float):
##
# ewma3 states for coefficient optimization
##
self.last_ewma3 = [0.0, 0.0, 0.0]
##
# ewma6 states for coefficient optimization
##
self.last_ewma6 = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
##
# default coefficients to 1.0 so the order can be from 0 - 6
# since cascade elements will pass input signal to output with a=1
##
self.coeff = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
for c in range(0, len(coeff)):
if(c >= len(self.coeff)):
print(f'EWMA Coefficients Length Mismatch! len(coeff) = {len(coeff)}, max is 6')
break
self.coeff[c] = coeff[c]
##
# realtime filter states
##
self.states = [0, 0, 0, 0, 0, 0, 0]
self.states[0] = initialValue
self.states[1] = initialValue
self.states[2] = initialValue
self.states[3] = initialValue
self.states[4] = initialValue
self.states[5] = initialValue
self.states[6] = initialValue
def preload(self, value: float):
self.states[0] = value
self.states[1] = value
self.states[2] = value
self.states[3] = value
self.states[4] = value
self.states[5] = value
self.states[6] = value
##
# @brief calculate single EWMA element
##
# @param self The object
# @param alpha filter coefficient
# @param this current input sample
# @param last last output sample from this stage (feedback)
##
# @return EWMA result
##
def ewma(self, alpha: float, this: float, last: float) -> float:
return (float(alpha)*float(this)) + ((1.0-float(alpha))*float(last))
##
# @brief calculate 6th order cascade ewma
##
# @param self The object
# @param inputValue Raw input sample
##
# @return output of 6th cascade element
##
def calculate(self, inputValue: float) -> float:
result = 0.0
self.states[0] = float(inputValue)
self.states[1] = self.ewma(float(self.coeff[0]), self.states[0], self.states[1])
self.states[2] = self.ewma(float(self.coeff[1]), self.states[1], self.states[2])
self.states[3] = self.ewma(float(self.coeff[2]), self.states[2], self.states[3])
self.states[4] = self.ewma(float(self.coeff[3]), self.states[3], self.states[4])
self.states[5] = self.ewma(float(self.coeff[4]), self.states[4], self.states[5])
self.states[6] = self.ewma(float(self.coeff[5]), self.states[5], self.states[6])
return self.states[6]
def get_last_output(self) -> float:
return self.states[6]
def model_ewma3_preload(self, v: float):
self.last_ewma3[0] = v
self.last_ewma3[1] = v
self.last_ewma3[2] = v
##
# @brief ewma 3rd order for IIR Model Fitting via SciPy Optimize
##
# @param self The object
# @param y0 The input value
# @param a coeff a
# @param b coeff b
# @param c coeff c
##
# @return IIR output
##
def model_ewma3(self, y0, a, b, c):
y1 = self.ewma(a, y0, self.last_ewma3[0])
y2 = self.ewma(b, y1, self.last_ewma3[1])
y3 = self.ewma(c, y2, self.last_ewma3[2])
self.last_ewma3[0] = y1
self.last_ewma3[1] = y2
self.last_ewma3[2] = y3
return y3
def model_ewma6_preload(self, v):
self.last_ewma6[0] = v
self.last_ewma6[1] = v
self.last_ewma6[2] = v
self.last_ewma6[3] = v
self.last_ewma6[4] = v
self.last_ewma6[5] = v
##
# @brief ewma 6th order for IIR Model Fitting via SciPy Optimize
##
# @param self The object
# @param y0 The Input Value
# @param a coeff a
# @param b coeff b
# @param c coeff c
# @param d coeff d
# @param e coeff e
# @param f coeff f
##
# @return { description_of_the_return_value }
##
def model_ewma6(self, y0, a, b, c, d, e, f):
y1 = self.ewma(a, y0, self.last_ewma3[0])
y2 = self.ewma(b, y1, self.last_ewma3[1])
y3 = self.ewma(c, y2, self.last_ewma3[2])
y4 = self.ewma(d, y3, self.last_ewma3[3])
y5 = self.ewma(e, y4, self.last_ewma3[4])
y6 = self.ewma(f, y5, self.last_ewma3[5])
self.last_ewma6[0] = y1
self.last_ewma6[1] = y2
self.last_ewma6[2] = y3
self.last_ewma6[3] = y4
self.last_ewma6[4] = y5
self.last_ewma6[5] = y6
return y6
def get_cutoff(self, Fs: float=1.0) -> float:
x = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
try:
x[0] = (Fs/2*math.pi)*math.acos(1.0 - (math.pow(self.coeff[0], 2)/(2.0*(1.0 - self.coeff[0]))))
print(f"Tap 1 {x[0]}")
except:
print("filter tap 1 not initialized")
try:
x[1] = (Fs/2*math.pi)*math.acos(1.0 - (math.pow(self.coeff[1], 2)/(2.0*(1.0 - self.coeff[1]))))
print(f"Tap 2 {x[1]}")
except:
print("filter tap 2 not initialized")
try:
x[2] = (Fs/2*math.pi)*math.acos(1.0 - (math.pow(self.coeff[2], 2)/(2.0*(1.0 - self.coeff[2]))))
print(f"Tap 3 {x[2]}")
except:
print("filter tap 3 not initialized")
try:
x[3] = (Fs/2*math.pi)*math.acos(1.0 - (math.pow(self.coeff[3], 2)/(2.0*(1.0 - self.coeff[3]))))
print(f"Tap 4 {x[3]}")
except:
print("filter tap 4 not initialized")
try:
x[4] = (Fs/2*math.pi)*math.acos(1.0 - (math.pow(self.coeff[4], 2)/(2.0*(1.0 - self.coeff[4]))))
print(f"Tap 5 {x[4]}")
except:
print("filter tap 5 not initialized")
try:
x[5] = (Fs/2*math.pi)*math.acos(1.0 - (math.pow(self.coeff[5], 2)/(2.0*(1.0 - self.coeff[5]))))
print(f"Tap 6 {x[5]}")
except:
print("filter tap 6 not initialized")
return x
def apply_to_data(self, data: list) -> list:
output = []
for d in data:
output.append(self.calculate(d))
return output
</code></pre>
<p>it is worth it to note that the following class functions are only used when optimizing the filter coefficients for system identification purposes, so its not the end of the world if they are sloppy to me. The remaining functions will be used in real-time:</p>
<pre><code>def model_ewma3_preload(self, v: float):
def model_ewma3(self, y0, a, b, c):
def model_ewma6_preload(self, v):
def model_ewma6(self, y0, a, b, c, d, e, f):
def get_cutoff(self, Fs: float = 1.0) -> float:
</code></pre>
<p>usage is akin to this:</p>
<pre><code># called on a timer at ~100Hz
sensor_reading = sensor.read()
system_approximation = filter.calculate(sensor_reading)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T16:13:05.993",
"Id": "446147",
"Score": "0",
"body": "Welcome to Code Review! Your indentation was broken, probably when pasting the code here. The easiest way to avoid that is to paste the code directly from your editor, select all of it and then either click the `{}` button at the top or press Ctrl+k."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T16:19:59.557",
"Id": "446150",
"Score": "0",
"body": "Great, Thank you for the corrections! I will remember next time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T16:36:06.060",
"Id": "446159",
"Score": "1",
"body": "For this and future questions, it'll be important to mention that this is not standard Python, but in fact MicroPython."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T16:42:54.807",
"Id": "446163",
"Score": "1",
"body": "Fixed, That is reasonable"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T17:19:35.167",
"Id": "446173",
"Score": "0",
"body": "Can you share some code that exercises this class in an application-typical way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T17:35:24.427",
"Id": "446177",
"Score": "0",
"body": "not at the moment. But the pseudo-code has been added"
}
] |
[
{
"body": "<h2>Copy a list into a slice</h2>\n\n<p>This code:</p>\n\n<pre><code>for c in range(0, len(coeff)):\n if(c >= len(self.coeff)):\n print(f'EWMA Coefficients Length Mismatch! len(coeff) = {len(coeff)}, max is 6')\n break\n self.coeff[c] = coeff[c]\n</code></pre>\n\n<p>has a couple of problems. It's fine to validate the length of <code>coeff</code>, but it shouldn't be done like this. Also, don't do an element-by-element copy. Instead:</p>\n\n<pre><code>N = 6\nself.coeff = [1]*N\n\nif len(coeff) > N:\n raise ValueError(f'EWMA Coefficients Length Mismatch! {len(coeff)} > {N}')\nself.coeff[:len(coeff)] = coeff\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>\n self.states = [0, 0, 0, 0, 0, 0, 0]\n self.states[0] = initialValue\n self.states[1] = initialValue\n self.states[2] = initialValue\n self.states[3] = initialValue\n self.states[4] = initialValue\n self.states[5] = initialValue\n self.states[6] = initialValue\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>self.states = [initialValue] * (N+1)\n</code></pre>\n\n<p>And so on.</p>\n\n<h2>Docstrings</h2>\n\n<p>Move your function documentation into <code>\"\"\"triple quotes\"\"\"</code> at the first line inside of your function.</p>\n\n<h2>Never <code>try/except</code></h2>\n\n<p>This breaks Ctrl+C quit, and is too broad to be useful. Narrow your caught exception type.</p>\n\n<h2>Don't repeat yourself</h2>\n\n<p><code>get_cutoff</code> needs to be rewritten as a loop over <code>N</code> values.</p>\n\n<h2>Don't cast unnecessarily</h2>\n\n<p>This:</p>\n\n<pre><code>def ewma(self, alpha: float, this: float, last: float) -> float:\n return (float(alpha)*float(this)) + ((1.0-float(alpha))*float(last))\n</code></pre>\n\n<p>already assumes that the inputs are floats - so don't call <code>float</code> again. Drop all of your casts.</p>\n\n<h2>Probable bug</h2>\n\n<pre><code>def model_ewma6(self, y0, a, b, c, d, e, f):\n y1 = self.ewma(a, y0, self.last_ewma3[0])\n</code></pre>\n\n<p>Seems that you're using the wrong array here. Also - why are you hard-coding for 3rd- or 6th-order filters? Can you not just accept N as a parameter?</p>\n\n<h2>General</h2>\n\n<p>Once you've cleaned up your usage of lists, you should really consider moving to <s>numpy</s> the <a href=\"https://docs.python.org/3/library/array.html\" rel=\"nofollow noreferrer\">array</a> module. It'll execute more quickly.</p>\n\n<h2>Suggested</h2>\n\n<p>This comes with a lot of caveats. Since you don't have test usage, I haven't been able to test it, so I don't know whether it's valid. You're going to want to develop a numerical test suite to ensure that it's calculating the right thing. I also assumed that there's no need to hard-code for 3rd- or 6th-order filters, so just added an <code>n</code>. Finally: I don't have micropython, so this is written naively, assuming that standard Python usage is valid.</p>\n\n<pre><code>from array import array\nfrom math import pi, acos\nfrom typing import Sequence, Iterable\n\n\nclass EWMA:\n def __init__(self, coeff: Sequence[float], initial_value: float, n: int = None):\n nc = len(coeff)\n if n:\n self.n = n\n if nc > n:\n raise ValueError(f'len(coeff)={nc} > n={n}')\n else:\n self.n = nc # default to the length of the coefficients\n\n # ewma states for coefficient optimization\n self.last_ewma = array('f', (0 for _ in range(self.n)))\n\n # default coefficients to 1.0 so the order can be from 0 - n\n # since cascade elements will pass input signal to output with a=1\n self.coeff = array('f', (1 for _ in range(self.n)))\n self.coeff[:nc] = coeff\n\n self.states = array('f', (0 for _ in range(1 + self.n)))\n\n def preload(self, value: float):\n self.states[:] = value\n\n @staticmethod\n def ewma(alpha: float, this: float, last: float) -> float:\n \"\"\"\n calculate single EWMA element\n :param alpha: filter coefficient\n :param this: current input sample\n :param last: last output sample from this stage (feedback)\n :return: EWMA result\n \"\"\"\n return alpha*this + (1 - alpha)*last\n\n def calculate(self, input_value: float) -> float:\n \"\"\"\n calculate nth order cascade ewma\n :param input_value: Raw input sample\n :return: output of nth cascade element\n \"\"\"\n self.states[0] = input_value\n for i, (c, s) in enumerate(zip(self.coeff, self.states[:-1])):\n self.states[i + 1] = self.ewma(c, s, self.states[i + 1])\n\n return self.get_last_output()\n\n def get_last_output(self) -> float:\n return self.states[-1]\n\n def model_ewma_preload(self, v: float):\n self.last_ewma[:] = v\n\n def model_ewma(self, y0: float, coeffs: Sequence[float]) -> float:\n \"\"\"\n ewma nth order for IIR Model Fitting via SciPy Optimize\n :param y0: The input value\n :param coeffs: Sequence of coefficients\n :return: IIR output\n \"\"\"\n prev = y0\n for i, (c, e) in enumerate(zip(coeffs, self.last_ewma)):\n new = self.ewma(c, prev, e)\n self.last_ewma[i] = new\n prev = new\n return prev\n\n def get_cutoff(self, fs: float = 1) -> array:\n return array(\n 'f',\n (\n fs*pi/2 * acos(1 - c**2/2/(1 - c))\n for c in self.coeff\n )\n )\n\n def apply_to_data(self, data: Iterable[float]) -> array:\n return array('f', (self.calculate(d) for d in data))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T16:21:32.807",
"Id": "446151",
"Score": "0",
"body": "Thank you! I will make these edits and give it a shot. I am intentionally trying to stay away from numpy as I would like to run this on micropython (which does not support numpy)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T16:22:17.027",
"Id": "446152",
"Score": "0",
"body": "Fair enough. Does micropython support https://docs.python.org/3/library/array.html ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T16:23:54.107",
"Id": "446153",
"Score": "0",
"body": "Looks like this is the case!\nhttps://docs.micropython.org/en/latest/library/array.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T16:33:00.820",
"Id": "446158",
"Score": "1",
"body": "OK, great. I think particularly in an embedded environment it'll be important to efficiently represent your data, so `array` will probably improve your memory usage, and may (?) improve your runtime performance. I encourage you to attempt an implementation using it, and post a new question with your updated code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T17:30:58.457",
"Id": "446175",
"Score": "0",
"body": "do we require a new tag for micropython?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T17:33:10.320",
"Id": "446176",
"Score": "0",
"body": "@dfhwze Based on the very small blurb at https://stackoverflow.com/help/privileges/create-tags , the answer seems to be yes."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T16:19:57.957",
"Id": "229390",
"ParentId": "229388",
"Score": "4"
}
},
{
"body": "<h1>Style</h1>\n\n<p>Python comes with an \"official\" <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> (often just called PEP8). Among others, it lists conventions regarding function documentation. In Python they're usually called <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">docstrings</a> (further detailed in <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP257</a>) and written in <code>\"\"\"triple quotes\"\"\"</code> <em>after</em> the function definition with <code>def</code>. For example:</p>\n\n<pre><code>def ewma(self, alpha: float, this: float, last: float) -> float:\n \"\"\"Calculate single EWMA element\n\n Calculate EWMA with alpha being the filter coefficient, this the current\n input sample, and last the previous output value\n \"\"\"\n</code></pre>\n\n<p>Of course this is only, if you don't have other conventions to follow. Seems like your code has some kind of doxygen-like syntax, but IIRC doxygen support for Python is not terribly well. If you're looking for a more structured approach that is better supported, <a href=\"https://numpydoc.readthedocs.io/en/latest/format.html\" rel=\"nofollow noreferrer\">numpydoc</a> in conjunction with Sphinx might be an option to consider. The same example using numpydoc:</p>\n\n<pre><code>def ewma(self, alpha: float, this: float, last: float) -> float:\n \"\"\"Calculate single EWMA element\n\n Parameters\n ----------\n alpha : float\n filter coefficient\n this : float\n current sample\n last : float\n the previous sample\n\n Returns\n -------\n ewma_result : float\n the result of the EMWA computation\n \"\"\"\n</code></pre>\n\n<p>This combination is especially used in the \"scientific Python stack\" (numpy, scipy, ...).</p>\n\n<h1>The code itself</h1>\n\n<p>Use <strike><a href=\"https://numpy.org/\" rel=\"nofollow noreferrer\">numpy</a></strike> (seems like you don't want to AND <a href=\"https://codereview.stackexchange.com/users/25834/\">@Reinderien</a> has beaten me ;-))! It would make your code a lot easier to read, and is also likely faster. But let's focus on what you have already written:</p>\n\n<p>Also you're doing a lot of work repeatedly. Python is a little bit \"dumb\", i.e. it will happily compute whatever you write (very likely) without realizing that the same computation happened just a few lines ago. An example of this would be <code>(Fs/2*math.pi) in</code>get_cutoff`. Compute it once, put it into a variable and reuse it.</p>\n\n<p>Python also has some tricks up its sleeves that make working with lists a little bit easier, e.g. where you have:</p>\n\n<pre><code>def apply_to_data(self, data: list) -> list:\n output = []\n for d in data:\n output.append(self.calculate(d))\n return output\n</code></pre>\n\n<p>You could instead write</p>\n\n<pre><code>def apply_to_data(self, data: list) -> list:\n return [self.calculate(d) for d in data]\n</code></pre>\n\n<p>Depending on the actual implementation, list comprehensions <a href=\"https://stackoverflow.com/a/30245465/5682996\">might also be faster than manually appending</a>.</p>\n\n<p>Lists can also be built by \"multiplication\" which allows you to write something like <code>self.states = [value] * 7</code>.</p>\n\n<p>Using <code>try: ... catch: ...</code> without specifying an exception will likely give you some headache, because it will simply catch all exceptions, including that triggered by pressing Ctrl+C. So you will never know for sure whether the error was something that you expected or not.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T18:20:23.707",
"Id": "446185",
"Score": "0",
"body": "In terms of performance, `[func(d) for d in data]` is less efficient than `[*map(func, data)]`, if `func` is a defined function. However, the former may be a bit more readable for some people. Also note that if `func(d)` is a simple expression like `d*d`, using an explicit `for`-loop is normally faster than the `map` counterpart where the expression needs to be wrapped into a lambda expression."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T19:18:52.540",
"Id": "446202",
"Score": "0",
"body": "@GZ0: In the end it boils down to \"it depends\" and the code should be carefully profiled to find out if that part is the actual bottleneck."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T16:50:10.090",
"Id": "229393",
"ParentId": "229388",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229393",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T15:54:39.987",
"Id": "229388",
"Score": "6",
"Tags": [
"python",
"signal-processing"
],
"Title": "Basic digital RC approximation filter in python (Micropython)"
}
|
229388
|
<p>I have a mapping application and the marker I'm using is based on the field rep assigned to that visit. My code is just a Select Case based on the rep's name and then it sets the bitmap for that person. </p>
<p>My code works fine, but there are 19 different field reps and I feel there must be a better way.</p>
<p>The code loops through a CSV file and grabs the Field Rep's name. Based on who it is, a System Resource image for that person is assigned to the image.</p>
<pre><code>Select Case CurrentRecord(iAssignedToCol)
Case "Al B. Connor"
If CurrentRecord(iStatusCol) = "Scheduled" Then
MapIcon = New Bitmap(My.Resources.Scheduled_ABC)
ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
MapIcon = New Bitmap(My.Resources.Tentative_ABC)
End If
Case "Donald E. Firestone"
If CurrentRecord(iStatusCol) = "Scheduled" Then
MapIcon = New Bitmap(My.Resources.Scheduled_DEF)
ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
MapIcon = New Bitmap(My.Resources.Tentative_DEF)
End If
Case "3rd name"
If CurrentRecord(iStatusCol) = "Scheduled" Then
MapIcon = New Bitmap(My.Resources.Scheduled_GHI)
ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
MapIcon = New Bitmap(My.Resources.Tentative_GHI)
End If
Case "4th name"
If CurrentRecord(iStatusCol) = "Scheduled" Then
MapIcon = New Bitmap(My.Resources.Scheduled_JKL)
ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
MapIcon = New Bitmap(My.Resources.Tentative_JKL)
End If
Case "5th name"
If CurrentRecord(iStatusCol) = "Scheduled" Then
MapIcon = New Bitmap(My.Resources.Scheduled_MNO)
ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
MapIcon = New Bitmap(My.Resources.Tentative_MNO)
End If
Case "6th name"
If CurrentRecord(iStatusCol) = "Scheduled" Then
MapIcon = New Bitmap(My.Resources.Scheduled_PQR)
ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
MapIcon = New Bitmap(My.Resources.Tentative_PQR)
End If
Case "7th name"
If CurrentRecord(iStatusCol) = "Scheduled" Then
MapIcon = New Bitmap(My.Resources.Scheduled_STU)
ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
MapIcon = New Bitmap(My.Resources.Tentative_STU)
End If
Case "8th name"
If CurrentRecord(iStatusCol) = "Scheduled" Then
MapIcon = New Bitmap(My.Resources.Scheduled_VWX)
ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
MapIcon = New Bitmap(My.Resources.Tentative_VWX)
End If
Case "9th name"
If CurrentRecord(iStatusCol) = "Scheduled" Then
MapIcon = New Bitmap(My.Resources.Scheduled_YZA)
ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
MapIcon = New Bitmap(My.Resources.Tentative_YZA)
End If
End Select
marker = New GMarkerGoogle(New PointLatLng(sSearchLat, sSearchLong), MapIcon)
</code></pre>
<p>Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T14:20:38.253",
"Id": "446267",
"Score": "1",
"body": "Welcome to Code Review! Please add the full code (where's currently \"Etc...\") so there's enough context to properly evaluate the code. At the moment your post is going to be closed due to lack of this. Hope you get some good answers once that's fixed. Enjoy your stay!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T14:11:53.140",
"Id": "446437",
"Score": "0",
"body": "The etc. etc. is just 18 more names and 18 more images names. It's not needed to explain the context."
}
] |
[
{
"body": "<p>this should be written once like this:</p>\n\n<pre><code>private sub whatever(byref res As Bitmap)\n If CurrentRecord(iStatusCol) = \"Scheduled\" Then\n MapIcon = New Bitmap(res)\n ElseIf CurrentRecord(iStatusCol) = \"Tentatively Scheduled\" Then\n MapIcon = New Bitmap(res)\n End If\nend sub\n</code></pre>\n\n<p>and </p>\n\n<pre><code>Select Case CurrentRecord(iAssignedToCol)\n Case \"Al B. Connor\"\n whatever(My.Resources.Scheduled_ABC)\n Case \"Donald E. Firestone\"\n whatever(My.Resources.Scheduled_DEF)\n Case....\n</code></pre>\n\n<p>Hope you get my point..</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T12:12:22.790",
"Id": "230543",
"ParentId": "229389",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230543",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T15:54:56.700",
"Id": "229389",
"Score": "1",
"Tags": [
"vb.net"
],
"Title": "Assigned a System resource to an image based on variable"
}
|
229389
|
<p>This has been asked a couple of times but here is my implementation in C++. I have 11/12 solutions completed. The 6th test case which has 200000 intial scores and Alice has even more scores causes my program to timeout. Below is the problem statement and the code. My question is, am I missing something in code complexity, or is this a more of a C++ optimization I need to add to get the last test data set through?</p>
<blockquote>
<p><strong>Problem</strong> </p>
<p>Alice is playing an arcade game and wants to climb to the top of the leaderboard and wants to track her ranking. The game uses
Dense Ranking, so its leaderboard works like this:</p>
<p>The player with the highest score is ranked number 1 on the
leaderboard. Players who have equal scores receive the same ranking
number, and the next player(s) receive the immediately following
ranking number. For example, the four players on the leaderboard have
high scores of , , , and . Those players will have ranks 100, 90, 90,
and 80, respectively. If Alice's scores are 70, 80 and 105, her
rankings after each game are 4th, 3rd and 1st.</p>
<p><strong>Function Description</strong> </p>
<p>Complete the climbingLeaderboard function in the editor below. It should return an integer array where each element
<code>res[j]</code> represents Alice's rank after the <code>j</code>-th game.</p>
<p>climbingLeaderboard has the following parameter(s):</p>
<ul>
<li><code>scores</code>: an array of integers that represent leaderboard scores<br></li>
<li><code>alice</code>: an array of integers that represent Alice's scores</li>
</ul>
<p><strong>Input Format</strong> </p>
<p>The first line contains an integer <code>n</code>, the number of players on the leaderboard. The next line contains <code>n</code> space-separated
integers <code>scores[i]</code>, the leaderboard scores in decreasing order. The
next line contains an integer, <code>m</code>, denoting the number games Alice
plays. The last line contains <code>m</code> space-separated integers <code>alice[j]</code>, the
game scores.</p>
<p><strong>Constraints</strong> </p>
<p>The existing leaderboard, scores, is in descending order. Alice's scores, alice, are in ascending order.</p>
<p><strong>Output Format</strong> </p>
<p>Print <code>m</code> integers. The <code>j</code>-th integer should indicate Alice's rank after playing the <code>j</code>-th game.</p>
</blockquote>
<p><strong>Code</strong></p>
<pre><code>std::vector<int>::iterator m_binary_search(std::vector<int>::iterator begin,
std::vector<int>::iterator end, int score)
{
std::vector<int>::iterator ret;
if (score > (*begin)) {
return begin;
} else if (score < (*(end - 1))) {
return end - 1;
}
if (*begin == score) {
ret = begin;
} else if (*(end - 1) == score) {
ret = end - 1;
} else if (begin + 1 == end) {
ret = begin;
} else {
std::ptrdiff_t middle = std::distance(begin, end) / 2;
if (*(begin + middle) == score) {
ret = begin + middle;
} else if ((score < (*begin)) && (score > * (begin + middle))) {
ret = m_binary_search(begin, begin + middle, score);
} else {
ret = m_binary_search(begin + middle, end, score);
}
}
return ret;
}
// Complete the climbingLeaderboard function below.
std::vector<int> climbingLeaderboard(
const std::vector<int> &scores,
const std::vector<int> &alice)
{
std::vector<int> rankBuckets;
for (std::size_t s = 0; s < scores.size();) {
int curr = scores[s];
while (s < scores.size() && scores[s] == curr) {
++s;
}
rankBuckets.push_back(curr);
}
typedef std::vector<int>::iterator VectIt_t;
std::vector<int> ranks;
for (int score : alice) {
VectIt_t cit = m_binary_search(
rankBuckets.begin(),
rankBuckets.end(),
score);
VectIt_t nit = cit;
++nit;
std::ptrdiff_t rank = std::distance(rankBuckets.begin(), cit);
if (nit == rankBuckets.end()) {
if (*cit != score) {
rankBuckets.push_back(score);
rank += 2;
} else {
rank += 1;
}
ranks.push_back(rank);
continue;
}
int crank = *cit;
int nrank = *nit;
if (score > crank) {
rankBuckets.insert(cit, score);
rank += 1;
} else if (score == crank) {
rank += 1;
} else if (score < crank && score > nrank) {
rankBuckets.insert(nit, score);
rank += 2;
}
ranks.push_back(rank);
}
return ranks;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T16:46:00.483",
"Id": "446164",
"Score": "1",
"body": "Could you please copy the text of the programming challenge into this question. Links often go bad over time. I know you didn't write main, but some reviewers may want to see it to show how the code gets used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T17:07:45.467",
"Id": "446170",
"Score": "0",
"body": "Unlike stackoverflow you don't have to worry about a duplicate question in this case because everyone codes differently and as you pointed out the other times this question was posted it was in different languages."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T17:11:11.600",
"Id": "446171",
"Score": "1",
"body": "@pacmaninbw question updated as per your request."
}
] |
[
{
"body": "<p>(Adapted from my <a href=\"https://codereview.stackexchange.com/a/226309\">answer to <em>How can I make my solution to “Climbing the Leaderboard” not time out?</em></a>)</p>\n\n<p>It is nice that you used <code>size_t</code> and <code>ptrdiff_t</code>. However, <code>int</code> is still directly used for the score. I would prefer an alias:</p>\n\n<pre><code>using score_t = long;\nusing rank_t = long;\n</code></pre>\n\n<p>(Note that <code>int</code> is not guaranteed to have <span class=\"math-container\">\\$10^9\\$</span>.)</p>\n\n<p>The <code>m_binary_search</code> function is redundant because we have <code>std::lower_bound</code> which should be optimized better.</p>\n\n<p>The <code>climbingLeaderboard</code> is <em>way</em> too long. The function is illogical. It should handle one Alice-score at a time. Also, <code>climbingLeaderboard</code> isn't really a good function name. (I know HackerRank forces you to code sub-optimally sometimes, but you should be aware.)</p>\n\n<p>The problem is very simple and can be finished in several lines without sacrificing readability:</p>\n\n<pre><code>using score_t = long;\nusing rank_t = long;\n\n// scores is passed by value to take advantage of possible optimization.\nrank_t get_rank(std::vector<score_t> scores, score_t alice_score)\n{\n scores.erase(std::unique(scores.begin(), scores.end()), scores.end());\n\n auto it = std::lower_bound(scores.begin(), scores.end(), alice_score, std::greater<>{});\n return it - scores.begin() + 1;\n}\n</code></pre>\n\n<p>The code is <span class=\"math-container\">\\$O(n)\\$</span> and I don't think you can do better in terms of asymptotic analysis. Note that each score of Alice's is independent, so it makes no sense to process them together in a function. I used <code>long</code> because the problem seems to require numbers as large as <span class=\"math-container\">\\$10^9\\$</span>. <code>scores</code> will be modified in the function, so instead of making a copy manually, we let the compiler do so for us in the parameter list. This enables possible optimization opportunities.</p>\n\n<p>Here, we used two standard algorithms:</p>\n\n<ul>\n<li><p><code>std::unique</code>, which \"removes\" adjacent equal elements. Standard algorithms cannot change the size of <code>scores</code> via iterators, so <code>std::unique</code> makes sure that the first <span class=\"math-container\">\\$N\\$</span> elements are the result, where <span class=\"math-container\">\\$N\\$</span> is the number of elements in the result. The rest of the elements are placed in a valid but otherwise unspecified state. Then, we call erase to erase these garbage elements. This is also known as the <a href=\"https://stackoverflow.com/q/799314\">remove-erase idiom</a>.</p></li>\n<li><p><code>std::lower_bound</code>, which performs a binary search and returns the first element that compares not \"less\" than the provided value. By default, \"less\" is defined by <code><</code>, thus operating on an ascending sequence. In this case, we use <code>std::greater<></code> to define \"less\" by <code>></code>, so that <code>std::lower_bound</code> is adapted to work on a descending sequence.</p></li>\n</ul>\n\n<p>Of course, you will need to adapt to HackerRank's strange interface, but that should be trivial.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T12:00:13.043",
"Id": "446254",
"Score": "0",
"body": "I see your point about `int` versus `long` even though most computers today would default to a 64 bit int rather than a 32 bit int, but why `alias long`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T12:30:25.897",
"Id": "446259",
"Score": "0",
"body": "@pacmaninbw I don't really like directly seeing `long` ... IMO, \"This number represents a score\" is better than \"This number represents a long\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T12:33:56.300",
"Id": "446261",
"Score": "0",
"body": "I understand, I read declarations different then you, \"This long represents a score\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T12:37:19.023",
"Id": "446262",
"Score": "1",
"body": "@pacmaninbw I get your point. Anyway, sometimes it is inconvenient to introduce a declarator (e.g., `std::pair<score_t, rank_t>`), so I prefer encoding this information in the type specifier. But I'd say it's a matter of style"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T12:44:59.690",
"Id": "446264",
"Score": "0",
"body": "I can see where that might make the code more readable, also easier to modify."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T19:50:39.220",
"Id": "447176",
"Score": "0",
"body": "@L.F. I implemented your suggestions and then profiled the code. After get_rank is called. You have to update scores if alice's score is not found in leader board. Due to the fact that they provide a vector and `std::lower_bound` only works on `RandomAccessIterators` I am taking a performance hit in the insertion. Insertion into a vector is O(n) because you have to copy all the data. Any suggestions there?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T03:08:37.100",
"Id": "447197",
"Score": "0",
"body": "@MatthewHoggan Insertion? As far as I can see, all Alice-scores are independent of each other. You don't need to insert anything."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T05:31:17.250",
"Id": "229414",
"ParentId": "229391",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T16:20:10.650",
"Id": "229391",
"Score": "4",
"Tags": [
"c++",
"programming-challenge",
"time-limit-exceeded",
"complexity"
],
"Title": "Hacker Rank Climbing The Leaderboard"
}
|
229391
|
<p>I've written a C# <code>struct</code> in order to encapsulate the idea of a <code>string</code> being neither <code>null</code> nor white space.</p>
<p>I was basically tired of writing and unit testing checks like the following: </p>
<pre><code>public class Person
{
public string Name { get; }
public Person(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException(
"A person name cannot be null or white space",
nameof(name)
);
}
this.Name = name;
}
}
</code></pre>
<p>The idea is creating a type, let's call it <code>NonEmptyString</code> which is auto safe, so that I can use this type everywhere avoiding these annoying string checks.</p>
<p>I came up with the following (full source is available <a href="https://github.com/deltatre-webplu/deltatre.utils/blob/master/src/Deltatre.Utils/Types/NonEmptyString.cs" rel="nofollow noreferrer">here</a>):</p>
<pre><code>using System;
namespace Deltatre.Utils.Types
{
/// <summary>
/// This type wraps a string which is guaranteed to be neither null nor white space
/// </summary>
public struct NonEmptyString
{
/// <summary>
/// Implicit conversion from <see cref="NonEmptyString"/> to <see cref="string"/>
/// </summary>
/// <param name="nonEmptyString">The instance of <see cref="NonEmptyString"/> to be converted</param>
public static implicit operator string(NonEmptyString nonEmptyString)
{
return nonEmptyString.Value;
}
/// <summary>
/// Explicit conversion from <see cref="string"/> to <see cref="NonEmptyString"/>
/// </summary>
/// <param name="value">The instance of <see cref="string"/> to be converted</param>
/// <exception cref="InvalidCastException">Throws <see cref="InvalidCastException"/> when <paramref name="value"/> is null or white space</exception>
public static explicit operator NonEmptyString(string value)
{
try
{
return new NonEmptyString(value);
}
catch (ArgumentException ex)
{
throw new InvalidCastException($"Unable to convert the provided string to {typeof(NonEmptyString).Name}", ex);
}
}
/// <summary>
/// Creates new instance of <see cref="NonEmptyString"/>
/// </summary>
/// <param name="value">The string to be wrapped</param>
/// <exception cref="ArgumentException">Throws <see cref="ArgumentException"/> when parameter <paramref name="value"/> is null or white space</exception>
public NonEmptyString(string value)
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException($"Parameter {nameof(value)} cannot be null or white space", nameof(value));
this.Value = value;
}
/// <summary>
/// Gets the wrapped string
/// </summary>
public string Value { get; }
/// <summary>Indicates whether this instance and a specified object are equal.</summary>
/// <param name="obj">The object to compare with the current instance. </param>
/// <returns>
/// <see langword="true" /> if <paramref name="obj" /> and this instance are the same type and represent the same value; otherwise, <see langword="false" />. </returns>
public override bool Equals(object obj)
{
if (!(obj is NonEmptyString))
{
return false;
}
var other = (NonEmptyString)obj;
return this.Value == other.Value;
}
/// <summary>Returns the hash code for this instance.</summary>
/// <returns>A 32-bit signed integer that is the hash code for this instance.</returns>
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = (hash * 23) + (this.Value == null ? 0 : this.Value.GetHashCode());
return hash;
}
}
/// <summary>
/// Compares two instances of <see cref="NonEmptyString"/> for equality
/// </summary>
/// <param name="left">An instance of <see cref="NonEmptyString"/></param>
/// <param name="right">An instance of <see cref="NonEmptyString"/></param>
/// <returns></returns>
public static bool operator ==(NonEmptyString left, NonEmptyString right)
{
return left.Equals(right);
}
/// <summary>
/// Compares two instances of <see cref="NonEmptyString"/> for inequality
/// </summary>
/// <param name="left">An instance of <see cref="NonEmptyString"/></param>
/// <param name="right">An instance of <see cref="NonEmptyString"/></param>
/// <returns></returns>
public static bool operator !=(NonEmptyString left, NonEmptyString right)
{
return !(left == right);
}
}
}
</code></pre>
<p>Unfortunately in C# it is not possible to hide or editing the default constructor of a <code>struct</code>, so it is entirely possible to write the following code:</p>
<pre><code>var myNonEmptyString = new NonEmptyString(); // default constructor is always available
string value = myNonEmptyString; // value is actually null
</code></pre>
<p>I thought of two ways of improving this type in order to handle this scenario:</p>
<ul>
<li>use a default value, such as <code>"N.A."</code>, for the <code>Value</code> property. Doing
so, even when an instance of <code>NonEmptyString</code> is created via the
default constructor the wrapped string is actually a non empty string</li>
<li>add a private readonly field <code>isInitialized</code>, whose default value is <code>false</code>, in order to track whether the right constructor has been called (the field is set to <code>true</code> only in the constructor overload having the <code>string</code> parameter). Doing so it is possible to add a check at the beginning of each type member, so that an <code>InvalidOperationException</code> is raised each time the programmer creates an instance via the default constructor and tries to use it in his code.</li>
</ul>
<p>Is there any other way to better handle the inevitable presence of the default constructor? What approach do you suggest?</p>
<p>For the ones asking themselves "why didn't he chose a class, in order to avoid this mess with the default constructor from the beginning", the reason for avoiding a class is simple: in C# (at least before C# 8) a reference type value is allowed to contain a null reference (and by default each reference type variable contains a null reference, unless properly initialized).</p>
<p>If <code>NonEmptyString</code> were be defined as a class it would be useless, because each piece of code receiving an instance of <code>NonEmptyString</code> would have to check whether the instance contains a null reference.
Instead, I would like to get a type giving the guarantee that each possible instance contains an actual string (that is a string other than <strong>null</strong>, the empty string and a sequence of spaces).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T18:13:36.520",
"Id": "446183",
"Score": "0",
"body": "@t3chb0t is this the same concept as your SoftString?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T18:21:39.730",
"Id": "446186",
"Score": "0",
"body": "@dfhwze the values I want to avoid are `null`, `string.Empty` and strings like `\" \"` (I mean strings composed only of white spaces). The type models the idea of a string containing at least one character other than `' '`. Intuitively these are the strings \"having an actual value\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T18:23:27.373",
"Id": "446187",
"Score": "0",
"body": "Ok now I see _IsNullOrWhiteSpace_. I don't think a default value makes sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T18:29:36.757",
"Id": "446189",
"Score": "0",
"body": "@dfhwze me too, my idea is going with the second solution I proposed (the runtime check over the `isInitialized` flag). The point with the default value is that whichever default value you chose, it probably doesn't make any sense for the programmer using the type. It's not meaningful and it's just a trick to avoid a null."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T19:18:20.990",
"Id": "446201",
"Score": "1",
"body": "@EnricoMassone I would go with a reference type (class), you can not get performance and safety the same time in this case. There should be a type without default constructor. I would define a base type like `String<TValidator, TComparer>` and inherit it in a situation like `class ProductName : String<NotEmptyValidator, IgnoreCaseComparer> {}`. I wish .NET had something like this ready to be used..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T21:39:23.073",
"Id": "446212",
"Score": "0",
"body": "@DmitryNogin check my edits for the argument of defining NonEmptyString as a class instead of a struct"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T21:48:57.743",
"Id": "446213",
"Score": "0",
"body": "@EnricoMassone Upcoming C# allows non-nullable reference types, so you could see a light at the end of the tunnel :) There is no much we can do for now otherwise but report more work hours, which is definitely a design goal in the enterprise world :) :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T20:55:54.890",
"Id": "447181",
"Score": "0",
"body": "I have rolled back the last edit. 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": "2019-10-03T18:40:07.010",
"Id": "447991",
"Score": "0",
"body": "@dfhwze nope, my `SoftString` works similar to a string and it allows `null` and empty strings, otherwise it trims the value and uses a case-insensitive comparer."
}
] |
[
{
"body": "<p>Since an empty string is not allowed, I cannot see any good alternative for an <code>Empty</code> value. I would move the check to the getter of <code>Value</code>. This way, the exception is thrown on demand rather than on construction of an object. C# structs are required to have a default value <code>Activator.CreateInstance(typeof(NotEmptyString));</code>.</p>\n\n<pre><code>public string Value \n{\n get\n {\n if (string.IsNullOrWhiteSpace(value))\n throw new ArgumentException(\n $\"Parameter {nameof(value)} cannot be null or white space\", nameof(value));\n\n return value; // backing-field\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T19:00:51.550",
"Id": "446278",
"Score": "1",
"body": "Throwing in a getter?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T19:44:04.633",
"Id": "446279",
"Score": "1",
"body": "@MathieuGuindon oh boy, what do I have a feeling I'm violating something important here? :p"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T18:34:09.993",
"Id": "229396",
"ParentId": "229395",
"Score": "3"
}
},
{
"body": "<p><a href=\"https://github.com/dmitrynogin/x-utils\" rel=\"nofollow noreferrer\">GitHub</a>, <a href=\"https://www.nuget.org/packages/X.ComponentModel/\" rel=\"nofollow noreferrer\">NuGet</a></p>\n\n<p>Let’s hope for a non-nullable references in the upcoming version of C#. As for now on I would say that the easiest way is just to check for null reference with <code>?? throw new ArgumentNullException()</code>. </p>\n\n<p>Here is what I use to check for white spaces in my DTO/models - at the end of the day it allows to save on typing:</p>\n\n<pre><code>public class Dto \n{\n public Dto(ProductName name)\n {\n Name = name ?? throw new System.ArgumentNullException(nameof(name));\n }\n\n public ProductName Name { get; }\n}\n</code></pre>\n\n<p>Json.NET will properly serialize read-only properties in both ways.\nMy <code>ProductName</code> like classes are defined as:</p>\n\n<pre><code>public class ProductName : String<ProductName>\n{\n public ProductName(string text)\n : base(text, NotNullOrWhitespace, Trim)\n {\n }\n}\n</code></pre>\n\n<p>Where:</p>\n\n<pre><code>[JsonConverter(typeof(StringJsonConverter))]\npublic abstract class String<T> : ValueObject<T>\n where T: String<T>\n{\n protected static string Trim(string text) => text?.Trim();\n protected static string EmptyIfNull(string text) => text ?? Empty;\n protected static string Upper(string text) => text?.ToUpper();\n protected static string Lower(string text) => text?.ToLower();\n\n protected static string NotNull(string text) => \n text != null ? text : throw new ArgumentNullException(nameof(text));\n protected static string NotNullOrWhitespace(string text) => \n !IsNullOrWhiteSpace(text) ? text : throw new ArgumentException(\"Text is required.\", nameof(text));\n protected static string NotNullOrEmpty(string text) =>\n !IsNullOrEmpty(text) ? text : throw new ArgumentException(\"Text is required.\", nameof(text));\n\n public static implicit operator string(String<T> s) => s?.Text;\n\n protected String(string text, params Func<string, string>[] actions) => \n Text = actions.Aggregate(text, (acc, f) => f(acc));\n\n public string Text { get; set; }\n\n public override string ToString() => Text;\n\n protected override IEnumerable<object> EqualityCheckAttributes => \n new[] { Text };\n}\n</code></pre>\n\n<p>Where:</p>\n\n<pre><code>public abstract class ValueObject<T> : IEquatable<ValueObject<T>>\n where T : ValueObject<T>\n{\n protected abstract IEnumerable<object> EqualityCheckAttributes { get; }\n\n public override int GetHashCode() =>\n EqualityCheckAttributes\n .Aggregate(0, (hash, a) => unchecked(hash * 31 + (a?.GetHashCode() ?? 0)));\n\n public override bool Equals(object obj) =>\n Equals(obj as ValueObject<T>);\n\n public virtual bool Equals(ValueObject<T> other) =>\n other != null &&\n GetType() == other.GetType() &&\n EqualityCheckAttributes.SequenceEqual(other.EqualityCheckAttributes);\n\n public static bool operator ==(ValueObject<T> left, ValueObject<T> right) =>\n Equals(left, right);\n\n public static bool operator !=(ValueObject<T> left, ValueObject<T> right) =>\n !Equals(left, right);\n}\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>class StringJsonConverter : JsonConverter\n{\n public override bool CanConvert(Type objectType) =>\n objectType == typeof(object) ? false :\n objectType.IsConstructedGenericType && objectType.GetGenericTypeDefinition() == typeof(String<>) ? true :\n CanConvert(objectType.BaseType);\n\n public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) =>\n Activator.CreateInstance(objectType, reader.Value);\n\n public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) =>\n writer.WriteValue(value.ToString());\n}\n</code></pre>\n\n<p>It is easy to extend the list of available operations:</p>\n\n<pre><code>public class Slug : String<Slug>\n{\n protected static string Dash(string text) => text.Replace(\" \", \"-\");\n public Slug(string text) \n : base(text, NotNullOrWhitespace, Trim, Lower, Dash)\n {\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T18:49:02.853",
"Id": "447992",
"Score": "0",
"body": "I'm wondering whether there is a cleaner way for handling `ToUpper/Lower` and make it case-insensitive without actually altering the original value. It would either require a copy of the input or an `IEqualityComparer` - probably a better choice. While `Trim` could be considered neutral, changing the case is an issue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T18:53:19.027",
"Id": "447993",
"Score": "0",
"body": "I have one more idea. What do you think about making `ValueObject<T>` an `IEnumerable<object>` as a replacement for `EqualityCheckAttributes`? This could be useful in other scenarios too."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T06:44:29.397",
"Id": "229416",
"ParentId": "229395",
"Score": "3"
}
},
{
"body": "<blockquote>\n<pre><code>public static explicit operator NonEmptyString(string value)\n{\n try\n {\n return new NonEmptyString(value);\n }\n catch (ArgumentException ex)\n {\n throw new InvalidCastException($\"Unable to convert the provided string to {typeof(NonEmptyString).Name}\", ex);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>The <code>try/catch</code> is superfluous, a guard clause should be throwing before the constructor is even invoked IMO; the exception could be an <code>ArgumentNullException</code>, but that would be confusing if <code>value</code> was actually <code>string.Empty</code>. Perhaps derive a custom exception from <code>ArgumentException</code>:</p>\n\n<pre><code>if (!string.IsNullOrEmpty(value))\n{\n throw new NullOrEmptyStringArgumentException()\n}\n</code></pre>\n\n<p>The problem is that it makes the <code>if (!string.IsNullOrEmpty(value))</code> validation logic (<em>and</em> the conditional throw) show up in two places... unless we pulled it out of local scope:</p>\n\n<pre><code>private static void ThrowIfInvalid(string value)\n{\n if(string.IsNullOrEmpty(value))\n {\n throw new NullOrEmptyStringArgumentException(...);\n }\n}\n</code></pre>\n\n<p>So we get:</p>\n\n<pre><code>public static explicit operator NonEmptyString(string value)\n{\n ThrowIfInvalid(value);\n return new NonEmptyString(value);\n}\n</code></pre>\n\n<p>And the constructor can <code>ThrowIfInvalid</code> as well:</p>\n\n<pre><code>public NonEmptyString(string value)\n{\n ThrowIfInvalid(value);\n this.Value = value;\n}\n</code></pre>\n\n<p>Much simpler everywhere! Except... that doesn't solve the default constructor problem, and <a href=\"https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1065-do-not-raise-exceptions-in-unexpected-locations?view=vs-2019\" rel=\"nofollow noreferrer\">throwing in a getter violates CA1065</a>. I would probably have these:</p>\n\n<pre><code>public static NonEmptyString Invalid { get; } = default;\npublic bool IsValid => this != Invalid;\n</code></pre>\n\n<p>The <code>obj is NonEmptyString</code> check in the <code>Equals</code> override works in non-obvious ways given a <code>string</code> argument, ...is the implicit cast involved? Would an explicit <code>obj as NonEmptyString</code> soft-cast seem more obviously correct here? Gotta love implicit operators! Let's refer to the docs!</p>\n\n<blockquote>\n <p>User-defined conversions are not considered by the <code>is</code> and <code>as</code> operators.</p>\n \n <p><sub><a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/user-defined-conversion-operators\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/user-defined-conversion-operators</a></sub></p>\n</blockquote>\n\n<p>So, it appears the implicit cast operator isn't involved: my understanding is that this means <code>Equals</code> is returning <code>false</code> if you give it a <code>string</code>, and I'd consider that a bug, <em>given</em> the implicit cast operator's <em>intent</em> is likely to make strings and non-empty strings seamlessly equate.</p>\n\n<p>The <code>==</code>, <code>!=</code> operators should probably have an overload for <code>string</code> too, and <code>+</code> should be expected to work as well, and should even be expected to accept a <code>NullOrEmpty</code> string (and then you get <code>+=</code> for free).</p>\n\n<p>Could be just me, but depending on context I think I might prefer an extension method on <code>string</code>, over an implicit (or explicit) cast operator:</p>\n\n<pre><code>var foo = \"hi\".AsNonEmptyString();\n</code></pre>\n\n<p>The struct should probably also implement <code>IEquatable</code> and <code>IComparable</code> (+their generic counterparts, for <code>string</code> and <code>NonEmptyString</code> both), and <code>IEnumerable</code>+<code>IEnumerable<char></code> too, for almost-complete parity with a <code>string</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T20:26:38.443",
"Id": "446280",
"Score": "3",
"body": "Ah, CA1065, got ya ;-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T20:20:10.707",
"Id": "229431",
"ParentId": "229395",
"Score": "5"
}
},
{
"body": "<p>Well, you could do what you want with some relatively \"grey\" magic, although I have not done this specific thing myself in the past. By the way, you still have to decide what code you will replace the default constructor with. If I understand well what you are trying to do, you would want the default constructor throwing an <code>ArgumentException</code>, is that right?</p>\n\n<p>If you have some patience and a bit of spare time (not too much, really), the <a href=\"https://en.wikipedia.org/wiki/ILAsm\" rel=\"nofollow noreferrer\">IL Assembler</a> does not appear to have any problem with an explicit default parameterless constructor. As <a href=\"https://codeblog.jonskeet.uk/2008/12/10/value-types-and-parameterless-constructors/\" rel=\"nofollow noreferrer\">Guess Who</a>* \"successfully\" (ok, no serious customization was performed anyway) poked around a long time ago, it appears to be feasible to do whatever you want inside an empty constructor for a custom type extending <code>ValueType</code>. You can use the article for a bit of guidance.</p>\n\n<p>So, what I would try is:</p>\n\n<ul>\n<li>Create an additional constructor in your almost-done type, receiving a dummy parameter (say, an <code>int</code>) and throwing an <code>ArgumentException</code> with the text informing that the the default empty constructor is not intended to be called directly (or any other exception you see fit).</li>\n<li>\"Bake\" the almost-done type in a class library alone.</li>\n<li><a href=\"https://docs.microsoft.com/en-us/dotnet/framework/tools/ildasm-exe-il-disassembler\" rel=\"nofollow noreferrer\">Disassemble</a> the library back to CIL.</li>\n<li>Read and <strong>understand</strong> a few basics of CIL so that I can...</li>\n<li>...remove the dummy <code>int</code> parameter from my constructor without causing other side effects in the code, so it would become the empty constructor.</li>\n<li>Reassemble back using the ILAssembler directly from the disassembled, tampered IL code.</li>\n</ul>\n\n<p>Then, <strong>boom</strong>, magically, I can never create an empty array of pre-initialized NonEmptyStrings anymore (for example <code>NonEmptyString[] strings = new NonEmptyString[100]</code>).</p>\n\n<p>I assume this is grey area and you could feel better going with your <code>bool</code> solution anyway, but <strong>if</strong> you decide to give this a shot, I would very much like to know how this worked out.</p>\n\n<p>*Also known as <strong>Jon Skeet</strong>!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T04:45:05.847",
"Id": "446301",
"Score": "0",
"body": "+1 for an interesting approach. Not sure though if it works, I thought that default constructor is always being invoked from the custom one for all value types..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T23:49:06.143",
"Id": "229435",
"ParentId": "229395",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T18:11:37.873",
"Id": "229395",
"Score": "6",
"Tags": [
"c#",
"object-oriented",
"strings",
"validation"
],
"Title": "A C# struct representing a string that can be neither null nor white space"
}
|
229395
|
<p>I have a dataset on which I need to do entity resolution. Hence in this dataset some records have links some records have address. I need to build a logic for it to identify each record and put the acronym as a unique identifier.</p>
<h2>Example Dataset</h2>
<pre><code>ID LINK acronym address
1 google NAN a
2 google NAN a
3 NAN NAN a
4 google NAN b
5 google NAN b
6 NAN NAN b
</code></pre>
<h2>Output</h2>
<pre><code> ID LINK acronym address
1 google google a
2 google google a
3 NAN google a
4 google google b
5 google google b
6 NAN google b
</code></pre>
<h2>Algorithm</h2>
<ol>
<li>I have a list of unique links/urls and I split it using <code>.</code> as a delimeter and assign this to <code>acronym</code>. As an example, <code>www.google.com</code> would convert into <code>google</code>.</li>
<li>Update dataframe acronym column where a unique link exists.</li>
<li>Find all unique addresses corresponding to the unique link and update the acronym with these addresses I found.</li>
</ol>
<p>Now I think my code needs some optimization.</p>
<h2>Code</h2>
<pre><code> for link in list_of_unique_links:
if( len(link.split('.')) >1):
acronym = link.split('.')[-2]
else :
acronym = link
print(acronym)
test_df.loc[test_df['links'] == link ,'acronyms'] =acronym
#Get all associated address with this link and also add
for address in test_df[test_df['links'] == link ].address.values:
test_df.loc[test_df['address'] == address ,'acronyms'] =acronym
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T01:27:11.077",
"Id": "446227",
"Score": "1",
"body": "Hello and welcome to CodeReview. I did a simple editing pass for formatting and spelling, but this question still does not meet our standards. There is not enough code for this to be reviewable - the code sample you've shown is too small to understand the context of the program as a whole. Also, please describe what the purpose of the application is, and what you'd like to get out of a review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T01:38:20.887",
"Id": "446229",
"Score": "0",
"body": "Hey I am implementing rulebased entity resolution in python. So It is a chunk of code for building training dataset. I need to make a column from which I can identify the address and link belongs to same entity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T01:39:58.467",
"Id": "446230",
"Score": "0",
"body": "I would like from community to review my logic and tell me If I can increase it performance"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T04:52:10.407",
"Id": "446240",
"Score": "2",
"body": "I cannot run this code. Please read/understand the rules for Code Review verses Stack Overflow."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T19:18:34.710",
"Id": "229399",
"Score": "3",
"Tags": [
"python",
"pandas"
],
"Title": "Python Dataframe column value updates in for loop"
}
|
229399
|
<p><a href="https://leetcode.com/problems/house-robber-ii/" rel="nofollow noreferrer">https://leetcode.com/problems/house-robber-ii/</a></p>
<blockquote>
<p>You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed. All houses at this
place are arranged in a circle. That means the first house is the
neighbor of the last one. Meanwhile, adjacent houses have security
system connected and it will automatically contact the police if two
adjacent houses were broken into on the same night.</p>
<p>Given a list of non-negative integers representing the amount of money
of each house, determine the maximum amount of money you can rob
tonight without alerting the police.</p>
<pre><code>Example 1:
Input: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
because they are adjacent houses.
Example 2:
Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
</code></pre>
</blockquote>
<pre><code>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CirucularArray
{
/// <summary>
/// google interview
/// https://www.geeksforgeeks.org/maximum-sum-in-circular-array-such-that-no-two-elements-are-adjacent/
/// https://leetcode.com/problems/house-robber-ii/
/// </summary>
[TestClass]
public class MaximumSumCircularArrayNo2ElementsAreAdjacent
{
[TestMethod]
public void RobberTestEvenArray()
{
int[] arr = {1, 2, 3, 4, 5, 1};
int result = Rob(arr);
Assert.AreEqual(9, result);
}
[TestMethod]
public void RobberTestOddArray()
{
int[] arr = { 5, 1, 2, 10 ,5 };
int result = Rob(arr);
Assert.AreEqual(15, result);
}
[TestMethod]
public void TestMethodOneItem()
{
int[] arr = {1 };
int result = Rob(arr);
Assert.AreEqual(1, result);
}
public int Rob(int[] nums)
{
if (nums == null || nums.Length == 0)
{
return 0;
}
if (nums.Length == 1)
{
return nums[0];
}
return Math.Max(Helper(0, nums.Length - 2,nums), Helper(1, nums.Length - 1,nums));
}
private int Helper(int start, int end, int[] nums)
{
int prevMax = 0;
int currMax = 0;
for (int i = start; i <= end; i++)
{
int temp = currMax;
currMax = Math.Max(prevMax + nums[i], currMax);
prevMax = temp;
}
return currMax;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T18:38:37.967",
"Id": "446365",
"Score": "0",
"body": "But your solution is not correct; try this: 11 1 2 4 1 10 1. The right result is 11 + 4 + 10 = 25. Your code would output 11 + 2 + 1 = 14."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T19:17:28.220",
"Id": "446366",
"Score": "0",
"body": "It passed all of leetcode tests. But let me check what you are saying."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T17:15:15.073",
"Id": "446464",
"Score": "0",
"body": "@Ilkhd you are wrong my friend my code returns 25"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T21:21:07.963",
"Id": "446516",
"Score": "0",
"body": "Sorry, my fault. The code is a bit trickier than I thought."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T14:17:46.477",
"Id": "447009",
"Score": "0",
"body": "What happens if the input is int[] arr = {5, 5, 5, 5, 5, 5};"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T21:21:24.803",
"Id": "447728",
"Score": "0",
"body": "@AlexLeo result would be 15"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T19:45:33.077",
"Id": "229400",
"Score": "2",
"Tags": [
"c#",
"programming-challenge",
"array"
],
"Title": "LeetCode: House Robber II C#"
}
|
229400
|
<p>Below is my code for the Comma Code problem from <a href="https://automatetheboringstuff.com/chapter4/" rel="noreferrer">Chapter 4 of Automate the Boring Stuff with Python</a>. Is there anything I can do to make it cleaner?</p>
<blockquote>
<p><strong>Comma Code</strong></p>
<p>Say you have a list value like this:</p>
<p>spam = ['apples', 'bananas', 'tofu', 'cats']</p>
<p>Write a function that takes a list of values as an argument and returns a string with all the items separated by a comma and a space, with 'and' inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list passed to it.</p>
<p><strong>The output of this program could look something like this:</strong>
apples, bananas, tofu, and cats</p>
</blockquote>
<pre class="lang-py prettyprint-override"><code>import sys
spam = ['apples', 'bananas', 'tofu', 'cats']
def print_list(list):
for item in list:
if len(list) == 1:
print(list[0])
elif item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
print_list(spam)
</code></pre>
|
[] |
[
{
"body": "<p>You've got an odd bug with your code.</p>\n\n<p>Given the 8th menu item from the <a href=\"https://en.wikipedia.org/wiki/Spam_(Monty_Python)#Menu\" rel=\"noreferrer\">greasy spoon café</a>:</p>\n\n<pre><code>spam = [\"Spam\", \"Spam\", \"Spam\", \"egg\", \"Spam\"]\n</code></pre>\n\n<p>You will get:</p>\n\n<blockquote>\n <p>and Spam<br>\n and Spam<br>\n and Spam<br>\n egg, and Spam</p>\n</blockquote>\n\n<p>since you are not testing whether you are at the last item in your list, but rather if the current item is the same as the last item in the list.</p>\n\n<hr>\n\n<p>Testing for a length 1 list should not be done inside the loop of all items; it should be done exactly once, outside the loop. Ie (but still with the above bug):</p>\n\n<pre><code>if len(list) == 1: # Test outside of loop\n print(list[0]) \nelse:\n for item in list:\n if item != list[-1]:\n print(item + ', ', end='')\n else:\n print('and ' + list[-1])\n</code></pre>\n\n<hr>\n\n<p>Want you really want to do is print all but the last item in the list one way, and the last item a different way:</p>\n\n<pre><code># If there are more than 1 items in the list...\nif len(list) > 1:\n\n # Print all but the last item, with a comma & space after each\n for item in list[:-1]:\n print(item + ', ', end='')\n\n # with \"and \" printed at the very end, just before ...\n print(\"and \", end='')\n\n# print the last (or only) item in the list.\nprint(list[-1])\n</code></pre>\n\n<p>although this still assumes at least one item in the list.</p>\n\n<hr>\n\n<p>Alternately, you could <code>join()</code> all but the last item, and then add <code>\", and \"</code> along with the final item.</p>\n\n<pre><code>msg = list[-1]\nif len(list) > 1:\n msg = \", \".join(list[:-1]) + \", and \" + msg\nprint(msg)\n</code></pre>\n\n<hr>\n\n<p>You are doing <code>import sys</code>, but not using <code>sys</code> anywhere. You can remove the import.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T22:35:35.077",
"Id": "446220",
"Score": "0",
"body": "Why is it better to test for a length of zero in the outside loop? Thanks for your help :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T22:38:09.420",
"Id": "446221",
"Score": "0",
"body": "Also, just a question I have had for a while. Why does the iterator not have to be defined before being called? For example \"item\" in your loop? `for item in list[:-1]:`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T00:15:45.587",
"Id": "446223",
"Score": "0",
"body": "The test is more efficient outside the loop, because it is done only once, instead of dozens or possibly hundreds of times, if you are looping over dozens or hundreds of entries."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T00:19:10.357",
"Id": "446224",
"Score": "1",
"body": "Python doesn’t declare any variables. You can assign `x = 5` without previously declaring that `x` exists. The `for` statement just repeatedly assigns new values to the loop variable. It doesn’t care if the variable existed before the loop. It doesn’t even care if the variable is deleted inside the loop; it will just recreate it on the next iteration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T11:58:32.800",
"Id": "446253",
"Score": "1",
"body": ":trollface: `\" ,\".join(list[::-1]).replace(',', 'dna ', 1)[::-1]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T01:30:39.453",
"Id": "446291",
"Score": "0",
"body": "This one liner works as well. \", \".join(list[:-1]) + (\", and \" if len(list) > 1 else '') + list[-1]"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T22:12:24.203",
"Id": "229405",
"ParentId": "229404",
"Score": "16"
}
},
{
"body": "<p><strong>Unused import statement:</strong> that should be cleaned up. </p>\n\n<pre><code>import sys\n</code></pre>\n\n<p><strong>Bad parameter name:</strong> <code>def print_list(list):</code> The keyword <code>list()</code> is a built-in function, you don't want your variable/parameter/function/method/class named like built-ins because later when you start relying on such keywords, this will create problems. </p>\n\n<p><strong>Example: (run this interactively)</strong></p>\n\n<pre><code>>>> word = 'mouse'\n>>> letters = list(word)\n>>> letters\n['m', 'o', 'u', 's', 'e']\n>>> list = 5\n>>> new_letters = list(word)\n</code></pre>\n\n<p><strong>Troubles ...</strong></p>\n\n<pre><code>Traceback (most recent call last):\nFile \"<pyshell#3>\", line 1, in <module>\nlist(word)\nTypeError: 'int' object is not callable\n</code></pre>\n\n<p>I think the example is self-explanatory why you shouldn't use built-ins in your naming.</p>\n\n<pre><code>def print_list(list):\n</code></pre>\n\n<p><strong>Docstrings:</strong> Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. ... A docstring is simply a multi-line string, that is not assigned to anything. It is specified in source code that is used to document a specific segment of code. You should include a docstring to your public functions indicating what they do and type hints if necessary. </p>\n\n<p><strong>This is a bit complicated</strong></p>\n\n<pre><code>for item in list:\n if len(list) == 1:\n print(list[0]) \n elif item != list[-1]:\n print(item + ', ', end='')\n else:\n print('and ' + list[-1])\n</code></pre>\n\n<p><strong>The whole function can be simplified and written properly:</strong></p>\n\n<pre><code>def separate(items: list):\n \"\"\"Return a string of the words in items separated by a comma.\"\"\"\n if len(items) > 1:\n return ', '.join(items[:-1]) + ', and ' + items[-1]\n if len(items) == 1:\n return items[0]\n if not items:\n raise ValueError('Empty list')\n</code></pre>\n\n<p>then use <code>if __name__ == '__main__':</code> guard at the end of your script which allows it to be imported by other modules without running the whole script.</p>\n\n<pre><code>if __name__ == '__main__':\n spam = ['apples', 'bananas', 'tofu', 'cats']\n print(separate(spam))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T22:29:52.657",
"Id": "446218",
"Score": "0",
"body": "@EmadBoctor Thanks for your answer. How does the if __name__ == '__main__': work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T22:44:31.143",
"Id": "446222",
"Score": "2",
"body": "You place the main guard at the end of your script and call your functions from there. And there are many cases where your module is imported by outside modules, for simplicity suppose you want to use that word separator from another script that let's say that organizes text or whatever, you will import your_script_name and use it accordingly."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T22:15:19.767",
"Id": "229406",
"ParentId": "229404",
"Score": "4"
}
},
{
"body": "<p>The problem statement says (<strong>bold</strong> emphasis mine):</p>\n\n<blockquote>\n <p>Write a function that takes a list of values as an argument and <strong>returns a string</strong> with all the items separated by a comma and a space, with 'and' inserted before the last item. For example, passing the previous spam list to the function would <strong>return</strong> 'apples, bananas, tofu, and cats'. But your function should be able to work with any list passed to it.</p>\n</blockquote>\n\n<p>Your function doesn't return anything, it just prints. So, what do I do if I want to display a list of groceries on a website? Or store it in a database? Or write it to a file? Or send it as an email? Or pipe it into a text-to-speech synthesizer?</p>\n\n<p>I'll have to write the exact same code over and over again!</p>\n\n<p>Instead, you should separate computation from input/output. (Not just because the problem statement says so, but as a general rule.)</p>\n\n<p>The immediate benefit is that you can easily test your code. If you print the result, in order to test the code, you would have to somehow intercept the standard output stream or re-direct the stream to a file and then read back and parse the file, or something similarly convoluted. If you separate constructing the string from printing the string, testing becomes much easier, you just write something like:</p>\n\n<pre><code>spam = ['apples', 'bananas', 'tofu', 'cats']\nresult = 'apples, bananas, tofu, and cats'\n\nassert result == commatize(spam)\n</code></pre>\n\n<p>See <a href=\"https://codereview.stackexchange.com/a/229406/1581\">Emad's answer</a> for an example of returning the result instead of printing it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T17:06:54.453",
"Id": "446272",
"Score": "0",
"body": "Thank you. Returning the result is one of the main things I need to remember to do."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T07:18:26.943",
"Id": "229417",
"ParentId": "229404",
"Score": "7"
}
},
{
"body": "<p>In real-life, we'd do it like this:</p>\n\n<pre><code>def print_list(list):\n if len(list) > 1:\n return ', '.join(list[:-1]) + ', and ' + list[-1]\n elif len(list) == 1:\n return list[0]\n else:\n return \"\"\n</code></pre>\n\n<p>(However, it's an excellent learning exercise to do it without the <code>.join</code> builtin.)</p>\n\n<p>When you use a negative number to access a list index, it tells Python to get the element from the back of the list. In this case, <code>-1</code> means the last element of the list.</p>\n\n<p><code>list[:-1]</code> grabs a slice of all the elements of the list except for the last.</p>\n\n<p><code>', '.join</code> inserts <code>', '</code> <em>between</em> all the elements in the list</p>\n\n<p>and</p>\n\n<p><code>list[-1]</code> grabs the last element of the list.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T19:58:59.987",
"Id": "229430",
"ParentId": "229404",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229405",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T21:30:25.000",
"Id": "229404",
"Score": "12",
"Tags": [
"python",
"beginner",
"python-3.x",
"strings",
"formatting"
],
"Title": "Comma Code - Automate the Boring Stuff with Python"
}
|
229404
|
<p>I am starting to learn network programming. I have implemented a very simple chat server based upon TCP, where the users only need to provide username.
The assumption is that the server makes use of no additional threads and the sockets are not blocking. The code:</p>
<pre class="lang-py prettyprint-override"><code>
import sys
import time
import socket
import select
class User:
def __init__(self, name, sock):
self.name = name
self.sock = sock
class Server:
def __init__(self, host, port):
self.users = []
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind((host, port))
def accept_usr(self):
usock, _ = self.sock.accept()
usock.send(b"Please, choose your username: ")
uname = usock.recv(1024)
self.users.append(User(uname, usock))
_, writes, _ = select.select([], self._usocks(), [])
for w in writes:
w.send(bytes(f"{uname} has joined us!", encoding="ascii"))
def handlerr(self, errs):
for s in errs:
s.close()
def update(self):
reads, writes, errs = select.select([*self._usocks(), self.sock], self._usocks(), self._usocks())
for r in reads:
if r is self.sock:
self.accept_usr()
else:
uname = [u for u in self.users if u.sock is u.sock][0].name
msg = r.recv(1024)
for w in writes:
w.send(bytes(f"{uname}: {msg}", encoding="ascii"))
self.handlerr(errs)
def run(self):
self.sock.listen(5)
while 1:
self.update()
time.sleep(0.1)
def _usocks(self):
return [u.sock for u in self.users]
if __name__ == "__main__":
s = Server("localhost", int(sys.argv[1]))
s.run()
</code></pre>
<p>I would be grateful for any hints and comments.</p>
<p>EDIT:
An obvious improvement that comes to my mind is to store the mapping of socket->User in a dict so that I'll be able to quickly determine the author of the message being sent.</p>
|
[] |
[
{
"body": "<h2>Packet fragmentation</h2>\n\n<p>Have a read through this: <a href=\"https://stackoverflow.com/a/17668009/313768\">https://stackoverflow.com/a/17668009/313768</a></p>\n\n<p><code>usock.recv(1024)</code> is fragile, and under many circumstances simply won't work for a handful of reasons. You'll need to do some reading about the fundamentals of TCP/IP to understand why that is, but basically, you can't assume that you'll get the data you want all in one chunk.</p>\n\n<h2>Context manager</h2>\n\n<p>You hold onto some sockets, which are resources that should be closed when you're done with them even if something goes wrong. This is a job for a context manager. You can make your class a context manager so that calling code can be sure that your resources are closed off, regardless of what else happens.</p>\n\n<p>Have a read through this: <a href=\"https://docs.python.org/3/library/stdtypes.html#typecontextmanager\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/stdtypes.html#typecontextmanager</a></p>\n\n<h2>Presentation versus logic</h2>\n\n<pre><code> usock.send(b\"Please, choose your username: \")\n</code></pre>\n\n<p>Typically, this is not done, and instead a pre-chosen number is sent over the wire, leaving the client to choose how to ask the user a particular thing. This becomes especially important when graphics get involved, or when you need to do translation/internationalization.</p>\n\n<h2>The first thing</h2>\n\n<pre><code>[u for u in self.users if u.sock is u.sock][0].name\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>next(u for u in self.users if u.sock is u.sock).name\n</code></pre>\n\n<p>That said... what on earth is this doing? When would that condition ever evaluate to <code>False</code>?</p>\n\n<h2>Type hints</h2>\n\n<p>PEP484 type hints, such as <code>host: str, port: int</code>, will clarify your function arguments.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T01:12:57.077",
"Id": "229410",
"ParentId": "229407",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T22:23:12.277",
"Id": "229407",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"networking"
],
"Title": "Network programming - asynchronous, single-threaded, nickname-only chat server"
}
|
229407
|
<h1>Background</h1>
<p>In my development of a game engine, I realized the need to be able to construct processing units in a serializable way (code below does not show serialization, just the wiring).</p>
<p>I broke the problem down into nodes and connectors. A Node is the processing unit. A Node may have zero or more connectors, for transmitting signals, and zero or more functions, for receiving transmitted signals.</p>
<p>This is written as a library, so trying to follow the additional steps of explicit access modifiers and return types.</p>
<p>A NodeConnector has two components, a transmitter, and a receiver. The transmitter should stay within the walls of the node</p>
<p>The code is also written so that it's focused on dependencies only. I'm trying to make this as reactive and stateless as possible. So the nodes should specify the things that they can be "attached to", and the way other nodes can be "attached to" them, but not all of the things attached to them. </p>
<h2>Source</h2>
<h3>Node Connector</h3>
<pre><code>/* NodeConnector.kt
* Copyright (C) 2019 Zymus
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package organicode
public interface NodeConnector<T : Any> {
public val transmitter: NodeSignalTransmitter<T>
public val receiver: NodeSignalReceiver<T>
}
public interface NodeSignalTransmitter<T : Any> {
public fun transmit(signal: T): Unit
}
public interface NodeSignalReceiver<T : Any> {
public fun onSignal(onSignal: (signal: T) -> Unit): Unit
}
public fun <T : Any> nodeConnector(): NodeConnector<T> {
return object : NodeConnector<T>, NodeSignalTransmitter<T>, NodeSignalReceiver<T> {
public override val transmitter: NodeSignalTransmitter<T>
get() = this
public override val receiver: NodeSignalReceiver<T>
get() = this
private var _onSignal: (T) -> Unit = {}
public override fun onSignal(onSignal: (signal: T) -> Unit): Unit {
_onSignal = onSignal
}
public override fun transmit(signal: T): Unit {
_onSignal(signal)
}
}
}
</code></pre>
<h3>Value Transmitter Node</h3>
<pre><code>/* ValueTransmitterNode.kt
* Copyright (C) 2019 Zymus
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package organicode
public interface ValueTransmitterNode<T : Any> {
public val value: NodeSignalReceiver<T>
public fun transmit()
}
public fun <T : Any> valueTransmitter(value: T): ValueTransmitterNode<T> {
return object : ValueTransmitterNode<T> {
public override val value: NodeSignalReceiver<T>
get() = valueTransmitter.receiver
private val valueTransmitter: NodeConnector<T> = nodeConnector()
public override fun transmit(): Unit {
valueTransmitter.transmitter.transmit(value)
}
}
}
</code></pre>
<h3>Transform Node</h3>
<pre><code>/* TransformNode.kt
* Copyright (C) 2019 Zymus
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package organicode
public interface TransformNode<T : Any, R : Any> {
public val transformedValue: NodeSignalReceiver<R>
public fun transformValueFrom(receiver: NodeSignalReceiver<T>): Unit
}
public fun <T : Any, R : Any> transformNode(transform: (T) -> R): TransformNode<T, R> {
return object : TransformNode<T, R> {
public override val transformedValue: NodeSignalReceiver<R>
get() = transformedValueConnector.receiver
private val transformedValueConnector: NodeConnector<R> = nodeConnector()
public override fun transformValueFrom(receiver: NodeSignalReceiver<T>): Unit {
receiver.onSignal {
transformedValueConnector.transmitter.transmit(transform(it))
}
}
}
}
</code></pre>
<h3>Predicate Node</h3>
<pre><code>/* PredicateNode.kt
* Copyright (C) 2019 Zymus
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package organicode
public interface PredicateNode<T : Any> {
public val onTrue: NodeSignalReceiver<T>
public fun testSignalFrom(receiver: NodeSignalReceiver<T>): Unit
}
public fun <T : Any> predicateNode(predicate: (T) -> Boolean): PredicateNode<T> {
return object : PredicateNode<T> {
public override val onTrue: NodeSignalReceiver<T>
get() = onTrueConnector.receiver
private val onTrueConnector: NodeConnector<T> = nodeConnector()
public override fun testSignalFrom(receiver: NodeSignalReceiver<T>) {
receiver.onSignal {
if (predicate(it)) {
onTrueConnector.transmitter.transmit(it)
}
}
}
}
}
</code></pre>
<h2>Print Node</h2>
<pre><code>/* PrintNode.kt
* Copyright (C) 2019 Zymus
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package organicode
public interface PrintNode<T : Any> {
public fun printMessageFrom(receiver: NodeSignalReceiver<T>, messageSupplier: (signal: T) -> String = { it.toString() }): Unit
}
public fun <T : Any> printNode(): PrintNode<T> {
return object : PrintNode<T> {
public override fun printMessageFrom(receiver: NodeSignalReceiver<T>, messageSupplier: (signal: T) -> String): Unit {
receiver.onSignal { println(messageSupplier(it)) }
}
}
}
</code></pre>
<h2>Test</h2>
<pre><code>/* NodeTests.kt
* Copyright (C) 2019 Zymus
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package organicode
import org.junit.Assert.assertEquals
import org.junit.Test
public class NodeTests {
@Test
fun `transform value and print if match`() {
val nameTransmitter: ValueTransmitterNode<String> = valueTransmitter("Reno")
val transformNode: TransformNode<String, String> = transformNode(String::toUpperCase)
val predicateNode: PredicateNode<String> = predicateNode("RENO"::equals)
val printNode: PrintNode<String> = printNode()
transformNode.transformValueFrom(nameTransmitter.value)
predicateNode.testSignalFrom(transformNode.transformedValue)
var printNodeHit: Boolean = false
printNode.printMessageFrom(predicateNode.onTrue) {
printNodeHit = true
"name: $it"
}
nameTransmitter.transmit()
assertTrue(printNodeHit)
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T22:37:46.353",
"Id": "229408",
"Score": "3",
"Tags": [
"functional-programming",
"api",
"kotlin"
],
"Title": "Node Based Code Flow Builder"
}
|
229408
|
<p>I have a graph represented using a dict of sets, e.g.</p>
<pre><code>graph = {
0: {1, 2, 3}, # neighbors of node "0"
1: {0, 2},
2: {0, 1},
3: {0, 4, 5},
4: {3, 5},
5: {3, 4, 7},
6: {8},
7: {5},
8: {9, 6},
9: {8}
}
</code></pre>
<p>I use the following code to find connected components in the graph:</p>
<pre><code>def get_connected_components(graph):
seen = set()
components = []
for node in graph:
if node not in seen:
component = []
nodes = {node}
while nodes:
node = nodes.pop()
seen.add(node)
component.append(node)
nodes.update(graph[node].difference(seen))
components.append(component)
return components
print(get_connected_components(graph)) # [[0, 1, 2, 3, 4, 5, 7], [6, 8, 9]]
</code></pre>
<p>Is there a better way to do this (e.g. a better representation of the graph or an algorithm) ?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T09:33:38.147",
"Id": "229418",
"Score": "3",
"Tags": [
"python",
"graph"
],
"Title": "Finding connected components of a graph"
}
|
229418
|
<p>This app loads application specific global configs and starts http server so that it is ready to serve API requests.</p>
<p>While structuring and coding, I've followed some "best" practises either from the official <a href="https://github.com/golang/go/wiki/CodeReviewComments" rel="nofollow noreferrer">docs</a>, widely followed <a href="https://github.com/golang-standards/project-layout" rel="nofollow noreferrer">resources</a> and some others. Given that the app below works, I have a feeling that it could be improved hence reason I am asking questions below. My aim is to make it more of a Go-like app than my own invention with bad practises. Just a side note, I've cut things sorter to keep the post short but if you want to see full picture <a href="https://github.com/BentCoder/auth" rel="nofollow noreferrer">this is</a> the GitHub page.</p>
<ol>
<li><p>Is the way I am bootstraping the app correct? The <code>main.go</code> prepares things and passes to <code>api.go</code> who starts the server so <code>main.go</code> is responsible for bootstraping things and <code>api.go</code> starts things.</p></li>
<li><p>The <code>config.go</code> has global vars but I am not directly accessing them in where they are needed. Instead, I am injecting them to functions that depend on them. Am I currently over engineering it or is it ok?</p></li>
<li><p>Shall I create/bootstrap <code>http.handler</code> with <code>New()</code> in <code>main.go</code> and inject into <code>app.go</code> as I do for the config? Or is it fine to keep it as is just because both <code>server.go</code> and <code>handler.go</code> files are under same directory?</p></li>
</ol>
<pre class="lang-bsh prettyprint-override"><code>.
├── bin
│ └── api
├── cmd
│ └── api
│ └── main.go
└── internal
├── app
│ └── api.go
├── config
│ └── config.go
├── controller
│ └── index
└── http
├── handler.go
└── server.go
</code></pre>
<p><strong>cmd/api/main.go</strong></p>
<pre class="lang-golang prettyprint-override"><code># This is also boots logger but removed to keep it short for now
package main
import (
"github.com/myself/api/internal/app"
"github.com/myself/api/internal/config"
)
func main() {
config.Load()
app.Run(config.Srv.Address)
}
</code></pre>
<p><strong>internal/config/config.go</strong></p>
<pre class="lang-golang prettyprint-override"><code># This has more stuff in it
package config
import "sync"
var (
App application
Srv server
o sync.Once
)
type application struct {
Env string
}
type server struct {
Address string
}
func Load() {
o.Do(func() {
App = application{Env:"dev"}
Srv = server{Address:"0.0.0.0:8080"}
})
}
</code></pre>
<p><strong>internal/app/api.go</strong></p>
<pre class="lang-golang prettyprint-override"><code># This is as simple as this
package app
import "github.com/myself/api/internal/http"
func Run(addr string) {
http.Start(addr)
}
</code></pre>
<p><strong>internal/http/server.go</strong></p>
<pre class="lang-golang prettyprint-override"><code># This actually handles signals and shutdown
package http
import (
"log"
"net/http"
)
func Start(addr string) {
if err := http.ListenAndServe(addr, handler()); err != nil {
log.Fatalf("couldn't start http server")
}
}
</code></pre>
<p><strong>internal/http/handler.go</strong></p>
<pre class="lang-golang prettyprint-override"><code># This has little bit stuff in it
package http
import (
"github.com/myself/api/internal/controller/index"
"github.com/julienschmidt/httprouter"
)
func handler() *httprouter.Router {
rtr := httprouter.New()
rtr.GET("/", index.Index)
return rtr
}
</code></pre>
<p><strong>internal/controller/index/index.go</strong></p>
<pre class="lang-golang prettyprint-override"><code>package index
import (
"github.com/julienschmidt/httprouter"
"net/http"
)
func Index(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T12:16:26.187",
"Id": "446257",
"Score": "0",
"body": "At least the title should contain what the code does, what is the function of the program. It might be good if there was a paragraph of text about what the code does as well. Currently the question can be closed as off-topic due to Lack of Concrete Context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T12:37:38.800",
"Id": "446263",
"Score": "2",
"body": "@pacmaninbw Updated as per your request. I hope it is much clearer now."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T10:57:37.020",
"Id": "229421",
"Score": "2",
"Tags": [
"go",
"http"
],
"Title": "Refactoring the Go HTTP API code/flow/structure"
}
|
229421
|
<p>I’m in the process of learning C++ and this was an assignment for a class. It is a simple hangman game. The instructor gives no feedback, only a pass/fail remark. While this works, I would like to know where I can improve. Thank you very much in advance for your help.</p>
<pre class="lang-cpp prettyprint-override"><code>/*************************************************************************
* Title: Hangman Game
*
* Write a program that plays the game of Hangman. The program should pick a
* word (which is either coded directly into the program or read from a text
* file) and display the following:
* Guess the word: XXXXXX
* Each X represents a letter. The user tries to guess the letters in the
* word. The appropriate response yes or no should be displayed after each
* guess. After each incorrect guess, display the diagram with another body
* part filled. After seven incorrect guesses, the user should be hanged. The
* display should look as follows:
* O
* /|\
* |
* / \
* After each guess, display all user guesses. If the user guesses the word
* correctly, display
* Congratulations!!! You guessed my word. Play again? yes/no
*************************************************************************/
#include <iostream> // std::cin/std::cout/endl
#include <string> // std::string
#include <vector> // vector
#include <ctime> // time for random seed
#include <random> // random
#include <cctype> // isalpha/tolower
#include <algorithm> // transform/count
// Get single character user input.
char getCharInput(const std::string prompt)
{
char input;
std::cout << prompt;
// Input from user.
std::cin.get(input);
if (std::cin.peek() != '\n')
// More than a single char input.
input = 0;
// Eat any remaining chars and LF.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return tolower(input);
}
// Check if character is already stored in list of guesses.
bool checkLetter(std::vector<char>& ltrs, const char c, const std::string response)
{
if (find(ltrs.begin(), ltrs.end(), c) == ltrs.end())
{
std::cout << response;
ltrs.push_back(c);
return true;
}
else
std::cout << "You already guessed \"" << c << "\"\n";
return false;
}
int main()
{
constexpr unsigned numWords{ 15 }, TOP{ 8 }, BASE{ 9 };
// Lambda random number generator [0...numWords].
auto rng = [=]() -> unsigned { return int(numWords * rand() / (RAND_MAX + 1.0)); };
// Seed the rng.
srand(static_cast<unsigned>(time(0))); rng();
do {
// Sample list of words to guess (five each 5, 6 & 7 character long).
std::string words[numWords] = {
"blimp", "inuit", "roach", "ankle", "could", "visual", "quartz", "studio",
"jockey", "hijack", "located", "alcohol", "crochet", "polymer", "humidor"
};
// Characters making up the gallows.
std::string gallows[] =
{
" | O\n | /|\\\n | |\n | / \\", // right leg (complete)
" | O\n | /|\\\n | |\n | /", // left leg
" | O\n | /|\\\n | |\n |", // torso
" | O\n | /|\\\n |\n |", // right arm
" | O\n | /|\n |\n |", // body
" | O\n | /\n |\n |", // left arm
" | O\n |\n |\n |", // head
" |\n |\n |\n |", // empty gallows
" ____\n | |\n", // gallows top
"\n _|_____\n" // gallows base
};
std::vector<char> guessedLetters; // List of guessed letters.
guessedLetters.clear(); // Empty the list.
unsigned remainingGuesses{ 7 }; // Number of guesses remianing.
unsigned rn{ rng() }; // Get a random number.
size_t remainingLetters{ words[rn].size() }; // Number un-guessed letters remaining in word.
std::string clue = { std::string(words[rn].size(), 'X') }; // Display word clue.
// Display program purpose.
std::cout << "Let's play a game of Hangman!\n\n";
// Loop until word is guessed or user is hung.
while (remainingLetters && remainingGuesses) {
// Display clue and get a user guess.
char g = getCharInput("Guess the word: " + clue + "\n");
if (isalpha(g)) {
// Replace 'X' with matching character.
transform(words[rn].cbegin(), words[rn].cend(), clue.begin(), clue.begin(),
[=](char s, char d) { if (s == g) { return g; } else return d; });
}
// Check if guessed character had any matches in word.
if (int matchedLetters = count(clue.cbegin(), clue.cend(), g))
// Correct guess, decrement remaining letters by proper amount.
remainingLetters -= (checkLetter(guessedLetters, g, "Good guess!\n") ? matchedLetters : 0);
else
// Wrong guess, decrement number of remaining guesses.
remainingGuesses -= (checkLetter(guessedLetters, g, "Wrong guess!\n") ? 1 : 0);
// Display results of guess.
std::cout << gallows[TOP] << gallows[remainingGuesses] << gallows[BASE];
std::cout << "Letters guessed: ";
for (char c : guessedLetters)
std::cout << c << " ";
std::cout << "\n\n";
}
// Display result of game.
if (!remainingLetters)
{
std::cout << "Congratulations!!! You guessed my word \"" << clue;
std::cout << "\" with " << guessedLetters.size() << " guesses!\n";
}
else
std::cout << "You've been hung!!!\n";
} while (tolower(getCharInput("Play again? yes/no ")) == 'y');
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T01:26:38.457",
"Id": "446288",
"Score": "0",
"body": "Just curious, what does \"YAHG\" stand for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T02:29:07.047",
"Id": "446297",
"Score": "1",
"body": "@L.F. I think \"YAHG\" stands for \"Yet Another Hangman Game\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T12:52:01.860",
"Id": "446325",
"Score": "0",
"body": "Just like YACC stands for \"Yet Another Compiler Compiler\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T22:16:45.663",
"Id": "446374",
"Score": "1",
"body": "Not a code review, but the proper past participle of hang (in the legal sense of execute) is \"hanged\" not \"hung\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T22:24:34.727",
"Id": "446375",
"Score": "1",
"body": "@James K Only if its to death... https://www.merriam-webster.com/words-at-play/hung-or-hanged"
}
] |
[
{
"body": "<h3>1. Use classes to separate concerns</h3>\n<p>One improvement could be to introduce your own classes to separate the hangman drawing, from the main game loop.</p>\n<p>Something like</p>\n<pre><code>class Gallow {\nprivate:\n static std::string gallows[] =\n {\n " | O\\n | /|\\\\\\n | |\\n | / \\\\", // right leg (complete)\n " | O\\n | /|\\\\\\n | |\\n | /", // left leg\n " | O\\n | /|\\\\\\n | |\\n |", // torso\n " | O\\n | /|\\\\\\n |\\n |", // right arm\n " | O\\n | /|\\n |\\n |", // body\n " | O\\n | /\\n |\\n |", // left arm\n " | O\\n |\\n |\\n |", // head\n " |\\n |\\n |\\n |", // empty gallows\n " ____\\n | |\\n", // gallows top\n "\\n _|_____\\n" // gallows base\n };\n int stage;\npublic:\n Gallow() : stage(sizeof(gallows)) {}\n void printNextFailedStage() {\n if(stage >= 0) {\n std::cout gallows[stage];\n stage--;\n }\n }\n bool isCompleted() {\n return stage <= 0;\n }\n};\n</code></pre>\n<p>Also separating the given words to guess into a class would make the overall designe more flexible.</p>\n<h3>2. Don't use c-style <code>srand()</code> and <code>rand()</code> functions with c++</h3>\n<p>Using <code>srand()</code> and <code>rand()</code> functions should be replaced with the <a href=\"https://en.cppreference.com/w/cpp/numeric/random\" rel=\"noreferrer\">Pseudo-random number generation</a> facilities of the current standard.</p>\n<h3>3. Use specific <code>using</code> statements to reduce namespace references</h3>\n<p>You can use</p>\n<pre><code>using std::cout;\n</code></pre>\n<p>for example to avoid the need to write out <code>std::cout</code> everytime.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T12:32:03.777",
"Id": "446260",
"Score": "0",
"body": "Might be a little early in the class for classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T13:05:57.000",
"Id": "446265",
"Score": "6",
"body": "@pacmaninbw It's never too early for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T13:50:17.057",
"Id": "446330",
"Score": "0",
"body": "@ πάντα ῥεῖ Thanks for the answer. Exactly what I was looking for. I'm exploring your suggestions."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T11:50:21.277",
"Id": "229423",
"ParentId": "229422",
"Score": "8"
}
},
{
"body": "<p>Welcome to Code Review! On my first scan through the code I was impressed. I learned a new C++ STL library function, std::transform(). I was really glad to see that there was no <code>using namespace std;</code> statement in the code. Keep up the good work!</p>\n\n<p>Upon executing the program I found one problem:</p>\n\n<p>It might be better to change the prompt at the end of the game to</p>\n\n<pre><code> } while (tolower(getCharInput(\"Play again? (y)es/no \")) == 'y');\n</code></pre>\n\n<p>or accept <code>yes</code> as well as <code>y</code>. I entered <code>yes</code> and the game quit.</p>\n\n<p><strong>Complexity</strong><br>\nWhile he function <code>main()</code> already calls 2 functions, it is still too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n\n<p>There is also a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">Single Responsibility Principle</a> that applies here. The Single Responsibility Principle states:</p>\n\n<blockquote>\n <p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<p>One of the ideas behind this principle is that the smaller a function is, the easier it is to write, debug, read and maintain.</p>\n\n<p>The outer <code>do while</code> loop could be a function. The inner <code>while</code> loop should be a function. The inner while loop could also add a couple of functions where the comments <code>Replace 'X' with matching character.</code> and <code>// Check if guessed character had any matches in word.</code> are.</p>\n\n<p>In the outer loop I would have created a variable <code>word</code> to simplify the code in the inner loop.</p>\n\n<pre><code> std::string word = words[rn];\n</code></pre>\n\n<p><strong>Use of C Style Arrays</strong><br>\nThere are 2 <code>C style arrays</code> in use, <code>words</code> and <code>gallows</code>. It might be better if these were implemented using a C++ container class such as <code>std::vector</code> or <code>std::array</code>. My choice would be <code>std::vector</code>, at least for <code>words</code> because that would allow the replacement of the symbolic constant <code>numWords</code> with <code>words.size()</code>. Implementing <code>words</code> as a vector also allows additional words to be added to the game easily. If you stick with the current implementation <code>numWords</code> should be declared as <code>std::size_t</code> rather than unsigned, std::size_t is the preferred variable type for array indexes.</p>\n\n<p>The declaration of these 2 arrays should be outside the <code>do while</code> loop because these arrays never change within the scope of the loop. A second reason to move them out of the loop, at least for <code>words</code> is that at some point in the future the contents of <code>words</code> might come from a text file which you would only want to read once.</p>\n\n<p><strong>Declaration of Symbolic Constants</strong><br>\nThis is a personal style comment. I would define all the symbolic constants outside of any function so that they could be used by all functions, to limit the scope they might be defined as <code>static</code>.</p>\n\n<pre><code>static constexpr std::size_t numWords{ 15 };\nstatic constexpr std::size_t TOP{ 8 };\nstatic constexpr std::size_t BASE{ 9 };\n</code></pre>\n\n<p>It is considered a good programming practice to define each constant or variable on it's own line to make maintenance and readability easier. It becomes difficult to find declarations defined on one line in large programs.</p>\n\n<p><strong>Variable Names</strong><br>\nIn the game while loop:\n - <code>guess</code> might be a better choice than <code>g</code>, single character variable names are not very descriptive.<br>\n - <code>rn</code> can only be determined by reading all the code, I'm guessing it means <code>random number</code>. </p>\n\n<p>In the function <code>bool checkLetter(std::vector<char>& ltrs, const char c, const std::string response)</code> it might be easier to understand <code>guessedLetters</code> than <code>ltrs</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T13:55:22.110",
"Id": "446331",
"Score": "1",
"body": "Thanks for the answer. Everything taken to heart. SRP is so obvious that in retrospect, I'm embarrassed by my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T14:35:15.080",
"Id": "446345",
"Score": "0",
"body": "Don't be embarrassed, the code was well written. It only took a half hour for me to break it up into functions after I wrote the answer as an exercise."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T15:04:49.853",
"Id": "229426",
"ParentId": "229422",
"Score": "7"
}
},
{
"body": "<p>You use <code>transform</code> instead of fully qualifying you mean the one from std <code>std::transform</code> leading me to believe there's a user-defined <code>transform</code> function. Try to be specific with the functions you call.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T21:58:50.573",
"Id": "229434",
"ParentId": "229422",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T11:26:34.580",
"Id": "229422",
"Score": "9",
"Tags": [
"c++",
"beginner",
"game",
"hangman"
],
"Title": "Hangman Game (YAHG)"
}
|
229422
|
<p>Here is my parent component: App.vue. I was wondering what improvements I could make to the code here. </p>
<p><strong>Application Description</strong></p>
<blockquote>
<p>This application was built off the Vue.js framework and utilizes a
Laravel REST API I created to fetch custom data. It stores and tracks
your ‘health score’, which is determined by the answers you submit in
the test. Each answer has a value. So, the unhealthiest answer has a
value of 0, the second-least healthiest 1, second-most healthiest 2,
and the healthiest answer 3. The values of the answers you submit are
aggregated throughout the test via local storage. After the final
question has been answered, your total health score is returned. Your
final score will determine the message you receive.</p>
</blockquote>
<pre><code><template>
<div id="app">
<div id="nav">
<!--once the testData array has received its first element, then render the test data
(this prevents error in dev tools)-->
<router-view
v-if="testData.length"
:currentTestData = testData[testDataIndex]
:testDataIndex = testDataIndex
:nextAndResetIndices="nextAndResetIndices"
:selectAnswer="selectAnswer"
:selectedIndex="selectedIndex"
:submitAnswer="submitAnswer"
:submittedIndex="submittedIndex"
:healthScore="healthScore"
:setStorage="setStorage"
:getStorage="getStorage"
:resetStorage="resetStorage"
:message="message"
:returnMessage="returnMessage"
/>
</div>
</div>
</template>
<script>
export default {
data() {
return {
testData: [],
testDataIndex: 0,
selectedIndex: null,
submittedIndex: null,
healthScore: 0,
message: ''
}
},
methods: {
nextAndResetIndices() {
this.testDataIndex++
this.selectedIndex = null
this.submittedIndex = null
// takes user to health score page
if (this.testDataIndex > 6) {
window.location.href = '/hs'
}
},
selectAnswer(index) {
this.selectedIndex = index
console.log(index)
},
submitAnswer(selectedIndex) {
this.submittedIndex = this.selectedIndex
console.log(this.submittedIndex)
// health score increments by the submitted index
this.healthScore += this.submittedIndex
},
resetStorage() {
localStorage.setItem('SavedHealthScore', 0)
}
},
computed: {
setStorage() {
// prevents the stored health score from mimicing the original and reverting back to 0
if (this.healthScore !== 0) {
localStorage.setItem('SavedHealthScore', this.healthScore)
}
},
getStorage() {
this.healthScore = parseInt(localStorage.getItem('SavedHealthScore'))
},
toZero() {
// returns the health score back to 0
this.healthScore = 0
},
returnMessage() {
if (this.healthScore < 8)
this.message = 'Get to the hospital now! '
else if (this.healthScore >= 8 && this.healthScore < 15)
this.message = "Not bad. You'll probably live! ♂️"
else
this.message = "You're very healthy. Congrats! ⚕️"
}
},
mounted() {
fetch('http://127.0.0.1:8000/api/testdata', {
method: 'get'
})
.then((response) => {
return response.json()
})
// 'jsonData' refers to the json parsed response
.then((jsonData) => {
this.testData = jsonData.data
})
}}
</script>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T13:11:49.367",
"Id": "446266",
"Score": "1",
"body": "@pacmaninbw I've included a more specific description. I didn't want to phrase the question that way, I wanted to include the word 'improve' but the algorithms wouldn't let me. I hope it's a little clearer now. I'm mainly concerned about which functions should be under methods and which functions should be under computed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T14:25:16.757",
"Id": "446268",
"Score": "2",
"body": "Everyone wants their code to be better, that's why you don't really have to include it, it's implied for this page. However, you could make it easier for reviewers by perhaps making the example fully runnable, or maybe include a link to the full, runnable version. As it is, there's a lot missing (where and how are questions answered, etc.) and that makes it hard or impossible to suggest meaningful improvements."
}
] |
[
{
"body": "<p>If you wish to keep your implementation scheme, I only have one large critique:</p>\n\n<p>Names are important</p>\n\n<p>Your naming scheme should allow a 3rd party to understand your code from a cursory glance. You have a lot of sneaky implementations tucked into your functions that aren't expressed in your naming convention.</p>\n\n<p>All of your operations are stateful, which is technically ok but you use a lot of verbage that makes it sound like they're functional operations with actual <code>return</code> values. All of your functions act on stateful variables. Your naming convention should reflect this through the use of verb phrases, as opposed to nouns.</p>\n\n<p><code>resetStorage</code>: A good variable name. It is a verb that acts on <code>localStorage</code></p>\n\n<p><code>getStorage</code>: Misleading. The traditional usage of the verb <code>get</code> is to retrieve a value or perform a computation (and <code>return</code> it). You are assigning <code>this.healthScore</code>. <code>getStorage</code> doesn't even have a <code>return</code> value. A more apt name would be something more like <code>setHealthScoreFromLocalStorage</code>.</p>\n\n<p><code>toZero</code>: What exactly is being set to zero? From the rest of your code (looking at <code>resetStorage</code>) I can infer that the value of <code>0</code> is the default value. It should be more along the lines of <code>resetHealthScore</code> or <code>clearHealthScore</code>.</p>\n\n<p><code>returnMessage</code>: It is updating <code>this.message</code>. So something more like <code>updateHealthMessage</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T06:19:44.677",
"Id": "447898",
"Score": "0",
"body": "I've renamed 'getStorage' to 'setHealthScoreFromLocalStorage' like you suggested. I know what you mean about 'toZero' being misleading, especially when compared to 'resetStorage'. So, I renamed 'toZero' to 'resetHealthScore' and 'resetStorage' to 'resetHealthScoreInLocalStorage'. And yes, I'm gonna change 'returnMessage' to updateHealthScoreMessage'. Thanks for the feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T19:07:00.427",
"Id": "447994",
"Score": "0",
"body": "I've just deployed the project and everything works fine. Except, instead of the app returning the health score it returns NaN. But this only happens during the browser's first time. After that, it works normally. Is there anything in my logic to suggest that this would be an issue after deployment, but not locally?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T19:57:52.043",
"Id": "447996",
"Score": "1",
"body": "@HarrisonGreeves The only thing I see that might be an issue is this line: `this.healthScore += this.submittedIndex`. `submittedIndex` starts off as `null`. You might not be seeing the issue in local because your local call is very fast, while in production it is far slower. Try slowing down your network speed (in the dev console) and seeing if you can replicate that behavior"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T05:28:02.723",
"Id": "448043",
"Score": "0",
"body": "Yep, I've slowed down the network in my dev tools to 'slow 3G' and I'm seeing the same issue. May make this a habit from now on. Thanks. I have no idea what submittedIndex could be if not null. It can't start off as 0 because that would be the index of the first answer for every question."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T22:11:30.587",
"Id": "229538",
"ParentId": "229424",
"Score": "2"
}
},
{
"body": "<h2>General feedback</h2>\n\n<p>This code looks decent, though as <a href=\"https://codereview.stackexchange.com/a/229538/120114\">Andrew's answer points out</a> many of the names are misleading. My biggest complaint is that semi-colons aren't used to terminate lines. While they are only required <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion\" rel=\"nofollow noreferrer\">after a handful of statements</a>, it could lead to errors if somehow whitespace got removed. It is a good habit to default to terminating lines with them.</p>\n\n<h2>Suggestions</h2>\n\n<h3>method <code>nextAndResetIndices()</code></h3>\n\n<p>There is a conditional block at the end of the method:</p>\n\n<blockquote>\n<pre><code>if (this.testDataIndex > 6) {\n window.location.href = '/hs'\n}\n</code></pre>\n</blockquote>\n\n<p>Perhaps that check should be moved to the beginning of the method, otherwise the line above it (except for the line to increment <code>this.testDataIndex</code>) become useless. The line to increment <code>this.testDataIndex</code> could be combined into the conditional check if it is converted to a prefix increment operation:</p>\n\n<pre><code>if (++this.testDataIndex > 6) {\n window.location.href = '/hs'\n}\n</code></pre>\n\n<h3>Arrow function Simplification</h3>\n\n<p>The promise callbacks in <code>mounted()</code> can be simplified because arrow functions with a single statement don't need to have braces. Bear in mind that this means that the return value of the statement is always returned but for this purpose that wouldn't lead to any adverse affects for the last callback. Also, parentheses are not required around a single parameter.</p>\n\n<p>This block:</p>\n\n<blockquote>\n<pre><code>fetch('http://127.0.0.1:8000/api/testdata', {\nmethod: 'get'\n})\n.then((response) => {\nreturn response.json()\n})\n// 'jsonData' refers to the json parsed response\n.then((jsonData) => {\n this.testData = jsonData.data\n})\n</code></pre>\n</blockquote>\n\n<p>Can be simplified to the following:</p>\n\n<pre><code>fetch('http://127.0.0.1:8000/api/testdata', {\n method: 'get'\n})\n.then(response => response.json())\n// 'jsonData' refers to the json parsed response\n.then(jsonData => this.testData = jsonData.data);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T13:14:20.907",
"Id": "447940",
"Score": "0",
"body": "I've implemented all the changes you suggested. Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T23:13:24.973",
"Id": "229936",
"ParentId": "229424",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T12:01:38.493",
"Id": "229424",
"Score": "3",
"Tags": [
"javascript",
"ecmascript-6",
"ajax",
"promise",
"vue.js"
],
"Title": "Health Test App, It Returns a Score Based on the Answers Given"
}
|
229424
|
<p>Github for project: <a href="https://github.com/wrpd/portfolio" rel="nofollow noreferrer">https://github.com/wrpd/portfolio</a></p>
<p>I have a very general understanding of MVC but haven't ever implemented it. In an effort to improve my understanding and get back into a little bit of web development I started watching and reading some tutorials and started to implement a basic MVC to redesign my personal website on.</p>
<p>I'm looking for critique on my current code. How can I make it more elegant?
What am I misunderstanding about MVC basics? Can I make things functionally more concise (In the code itself. For variable names and such I'm keeping it purposely verbose to aid in understanding for myself)?</p>
<p>Specifically, I'm wondering if my project structure is okay and how to better handle routing and initializing? My routes are currently set with a routing class like so:</p>
<pre><code><?php
router::set_route('/', function(){
index_controller::create_view('index');
});
router::set_route('/about', function(){
about_controller::create_view('about');
});
router::set_route('/projects', function(){
projects_controller::create_view('projects');
});
router::set_route('/contact', function(){
contact_controller::create_view('contact');
});
?>
</code></pre>
<p>Is this an optimal way of routing to my pages? </p>
<p>My init is currently autoloading my classes and requiring my routes. Like so:</p>
<pre><code><?php
function autoload($class_name){
if (file_exists('./app/core/classes/'. $class_name . '.php')){
include './app/core/classes/'. $class_name . '.php';
} else if (file_exists('./app/controllers/' . $class_name . '.php')){
include './app/controllers/' . $class_name . '.php';
} else if (file_exists('./app/models/' . $class_name . '.php')){
include './app/models/' . $class_name . '.php';
}
}
spl_autoload_register(autoload);
require_once './app/core/routes/routes.php';
?>
</code></pre>
<p>Should it be a class that I instantiate in index.php or is that sufficient? I like that index.php can just contain </p>
<pre><code>require_once '/path/to/init.php'
</code></pre>
<p>but I don't know if that's the best practice. </p>
<p>Essentially, I'd like to make the foundation for my personal site as solid as I can while following best practice. I've seen a lot of code examples and samples but some are quite dated and my depth of knowledge isn't deep enough to know if I'm doing things the best way that I can. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T18:25:34.263",
"Id": "446471",
"Score": "1",
"body": "Right now you have very little code in your question; what are you actually asking us to review? The MVC framework you made? Your routing scheme? Something else? Can you please [edit](https://codereview.stackexchange.com/posts/229429/edit) your question to include what specifically you are looking for review of, and then make sure there is enough code to provide a reasonable review?"
}
] |
[
{
"body": "<p>If you want to learn best practices in MVC, I would suggest you to have <a href=\"http://www.slimframework.com/docs/v4/concepts/life-cycle.html\" rel=\"nofollow noreferrer\">Slim framework</a>. If you don't want to use an existing framework and develop your own, still, I would recommend to install it on your local and understand how they are doing. Laravel is another best, but it would be overkill for a personal site. </p>\n\n<p>Check their Routing example. You are almost close in your routing, but if you want to know the best practices, they have it: <a href=\"http://www.slimframework.com/docs/v4/objects/routing.html\" rel=\"nofollow noreferrer\">http://www.slimframework.com/docs/v4/objects/routing.html</a></p>\n\n<p>In your example, I would include init.php and routes.php inside of index.php to keep it clean and declarative. Your init may eventually grow and it would become clumsy. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T16:41:26.430",
"Id": "446359",
"Score": "0",
"body": "Thank you for the feedback. I'll check out the Slim framework to get a better understanding!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T01:48:36.870",
"Id": "229438",
"ParentId": "229429",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T19:41:44.140",
"Id": "229429",
"Score": "0",
"Tags": [
"php",
"mvc",
"url-routing"
],
"Title": "Improving PHP MVC code for personal website"
}
|
229429
|
<p>So after watching week 5 of the machine learning course on Coursera by Andrew Ng, I decided to write a simple neural net from scratch using Python. Here's my code:</p>
<pre><code>import numpy as np
import csv
global e
global epsilon
global a
global lam
global itr
e = 2.718281828
epsilon = 0.12
a = 1
lam = 1
itr = 1000
# The sigmoid function(and its derivative)
def sigmoid(x, derivative=False):
if derivative:
return sigmoid(x) * (1 - sigmoid(x))
return 1 / (1 + e**-x)
# The cost function
def J(X, theta1, theta2, y, lam, m):
j = 0
for i in range(m):
# The current case
currX = X[i].reshape(X[i].shape[0], 1)
z2 = theta1 @ currX
a2 = sigmoid(z2)
a2 = np.append([1], a2).reshape(a2.shape[0] + 1, 1)
z3 = theta2 @ a2
a3 = sigmoid(z3)
j += sum(-y[i] * np.log(a3) - (1 - y[i]) * np.log(1 - a3)) / m + (lam / (2 * m)) * (sum(sum(theta1[:, 1:] ** 2)) + sum(sum(theta2[:, 1:] ** 2)))
return j
# The gradients
def gradient(X, theta1, theta2, y, lam, m):
theta1Grad = np.zeros(theta1.shape)
theta2Grad = np.zeros(theta2.shape)
Delta1 = np.zeros(theta1.shape)
Delta2 = np.zeros(theta2.shape)
for i in range(m):
# The current case
currX = X[i].reshape(X[i].shape[0], 1)
z2 = theta1 @ currX
a2 = sigmoid(z2)
a2 = np.append([1], a2).reshape(a2.shape[0] + 1, 1)
z3 = theta2 @ a2
a3 = sigmoid(z3)
delta3 = a3 - y[i]
delta2 = theta2[:, 1:].T @ delta3 * sigmoid(z2, derivative=True)
Delta1 += delta2 @ currX.reshape(1, -1)
Delta2 += delta3 * a2.reshape(1, -1)
theta1Grad = Delta1 / m
theta2Grad = Delta2 / m
theta1Grad[:, 1:] += (lam / m) * theta1[:, 1:]
theta2Grad[:, 1:] += (lam / m) * theta2[:, 1:]
thetaGrad = np.append(theta1Grad.reshape(theta1Grad.shape[0] * theta1Grad.shape[1], 1), theta2Grad.reshape(theta2Grad.shape[0] * theta2Grad.shape[1], 1))
thetaGrad = thetaGrad.reshape(thetaGrad.shape[0], 1)
return thetaGrad
# Gradient descent
def gradientDescent(X, theta1, theta2, y, lam, m):
for i in range(itr):
grad = gradient(X, theta1, theta2, y, lam, m)
theta1Grad = grad[0:theta1.shape[0] * theta1.shape[1]].reshape(theta1.shape)
theta2Grad = grad[theta1.shape[0] * theta1.shape[1]:].reshape(theta2.shape)
theta1 = theta1 - a * theta1Grad
theta2 = theta2 - a * theta2Grad
return (theta1, theta2)
with open('data.csv', 'r') as f:
data = csv.reader(f)
d = []
c = 0
# Read the data
for row in data:
# Don't add the first line(it's our features' labels)
if c == 0:
c += 1
continue
curr_row = []
k = 0
for j in row:
if j != '':
if k == 1:
# Add a 1 between the y and x values(for the bias)
curr_row.append(1)
curr_row.append(float(j))
k += 1
d.append(curr_row)
d = np.array(d)
x = d[:, 1:]
y = d[:, 0]
# Split the data into training cases(80%) and test cases(20%)
x_train = x[0:(d.shape[0]//5) * 4, :]
y_train = y[0:(d.shape[0]//5) * 4]
x_test = x[(d.shape[0]//5) * 4 : d.shape[0], :]
y_test = y[(d.shape[0]//5) * 4 : d.shape[0]]
# Initialize theta(s)
theta1 = np.random.rand(5, x[0].shape[0]) * 2 * epsilon - epsilon
theta2 = np.random.rand(1, 6) * 2 * epsilon - epsilon
print(J(x_train, theta1, theta2, y_train, lam, x_train.shape[0]))
theta1, theta2 = gradientDescent(x_train, theta1, theta2, y_train, lam, x_train.shape[0])
</code></pre>
<p>Please note a that my data only has 2 possible outputs so no need for one-vs-all classification.</p>
<p>Thanks in advance!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T00:44:38.490",
"Id": "446284",
"Score": "0",
"body": "What is this code supposed to do? what is its use?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T02:29:50.677",
"Id": "446298",
"Score": "1",
"body": "You don't need to declare `global var` in global scope. This only needs to be done inside a function that might need to modify a global variable"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T11:09:08.030",
"Id": "446314",
"Score": "0",
"body": "@EmadBoctor This is a neural network(classifier)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T21:16:33.300",
"Id": "229432",
"Score": "1",
"Tags": [
"python",
"machine-learning",
"neural-network"
],
"Title": "Neural network from scratch in Python"
}
|
229432
|
<p>My attempt at a fixed framerate using SDL2 without using VSync. Just using <code>SDL_Delay</code> left the fps a bit slower or faster due to the fact <code>SDL_Delay</code> only works with milliseconds. So the solution I came up with is after using <code>SDL_Delay</code> the remainder of the "extra" time is elapsed through a loop. The solution seems a little bit cluttered to me and my experience with programming in general is very limited so any pointers would be much appreciated.</p>
<pre><code>float frame_cap{ 60 };
float ms_per_frame{ 1000.0f / frame_cap };
float fps{ 0 };
uint64_t start_counter;
uint64_t end_counter;
bool quit{ false };
while( quit != true )
{
start_counter = SDL_GetPerformanceCounter();
//HANDLE INPUT
//UPDATE
//RENDER
end_counter = SDL_GetPerformanceCounter();
//multiplying by 1000.0f to convert to ms
float elapsed_ms = ((end_counter - start_counter) / (float)SDL_GetPerformanceFrequency()) * 1000.0f;
if( elapsed_ms < ms_per_frame )
{
float ms_left = ms_per_frame - elapsed_ms;
SDL_Delay( floor(ms_left) );
//loop for the amount of time that could not be delayed with SDL_Delay
float missed_ms = ms_left - floor(ms_left);
start_counter = SDL_GetPerformanceCounter();
float delayed_ms { 0 };
while(delayed_ms < missed_ms)
{
end_counter = SDL_GetPerformanceCounter();
delayed_ms = ((end_counter - start_counter) / (float)SDL_GetPerformanceFrequency()) * 1000.0f;
}
//adding time delayed to elapsed time of frame for fps calculation
elapsed_ms += floor(ms_left) + delayed_ms;
/*floor(ms_left) is time delayed using SDL_Delay
this has a chance to be inaccurate if SDL_Delay
delays more then floor(ms_left) due to OS scheduling*/
}
//dividing by 1000.0f to convert to seconds
fps = 1.0f / (elapsed_ms / 1000.0f);
}
</code></pre>
|
[] |
[
{
"body": "<p>Why you <strong>exactly</strong> need the framerate to be constant?</p>\n<p>You can use <code>SDL_GetTicks()</code> this way:</p>\n<pre><code>const int ms_frame = 1000 / 60;\nUint32 initial_ticks, elapsed_ms;\nwhile(true){\n initial_ticks = SDL_GetTicks();\n\n //do things\n\n elapsed_ms = SDL_GetTicks() - elapsed_ms;\n if(elapsed_ms < ms_frame) SDL_Delay(ms_frame - elapsed_ms);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T09:27:46.540",
"Id": "525387",
"Score": "0",
"body": "`elapsed_ms = SDL_GetTicks() - initial_ticks;`?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T22:03:02.180",
"Id": "250618",
"ParentId": "229436",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T00:55:46.983",
"Id": "229436",
"Score": "2",
"Tags": [
"c++",
"sdl"
],
"Title": "SDL2 fixed framerate without VSync"
}
|
229436
|
<p>I had a friend ask me to write this up for her as she discovered her logs were saving private bank information in plain text. This is used to parse a few hundred gigs of text files. I've never worked with python for anything other then pet projects so i'd like to send my friend a nice piece of code since this is my first time helping her. I'm not looking to make this multi-threaded however.</p>
<p>Any suggestions on improvements or lessons to be learned from this? Thank you in advance!</p>
<pre class="lang-py prettyprint-override"><code>import os
scan1_location=6
scan2_location=3
scan3_location_a=38
scan3_location_b=60
scan1="bankAccount: "
scan2="bankAccount,"
scan3=" accountNumber="
input_directory="/home/ubuntu/CCTech_Dev/Stories/S-68080/logFiles/"
output_directory="/home/ubuntu/CCTech_Dev/Stories/S-68080/newLogs/"
found=0
count=0
# 1. Parse the given line for the number to be masked
# 2. Mask the number
# 3. Insert masked number back into line
def maskLine(line, scan):
# Depending on the scan, the number is in a different location in the line
if scan == 1:
number = line[scan1_location]
number = maskNumber(number)
line[scan1_location] = number
elif scan == 2:
subLine = line[scan2_location].split(",")
subLine[3] = maskNumber(subLine[3])
line[scan2_location] = ",".join(subLine)
elif scan == 3:
# The number in this scan can either occur once in a short line
# or twice in a long line.
if len(line) < 50:
subLine = line[len(line) - 4].split("=")
subLine[1] = maskNumber(subLine[1])
line[len(line) - 4] = "=".join(subLine)
else:
subLine = line[scan3_location_a].split("=")
subLine[1] = maskNumber(subLine[1])
line[scan3_location_a] = "=".join(subLine)
line[scan3_location_b] = "=".join(subLine)
else:
raise Exception("Location Error")
return " ".join(line)
# Example 1: Input -> 123, Output -> *****
# Example 2: Input -> 123456789, Output -> *****6789
def maskNumber(number):
if len(number) > 0 and len(number) < 5:
number = "*****"
else:
number = "*" * (len(number) - 4) + number[-4:]
return number
# Run through each line of every file to mask every bank account number found
# Iterate over every file in directory
for filename in os.listdir(input_directory):
print(input_directory + filename)
# Output file may be in the same location as input depending on
# output_directory but will always have a different file name
file = open(input_directory + filename, 'r')
output = open(output_directory + filename + "-new", 'w+')
# Initial read of file
line = file.readline()
length = len(line)
# Read until the end of the file
# Ensures any erroneous reads are not parsed
while length > 0:
# Check if line contains a number that needs to be masked
size = line.find(scan1, 0, length)
location=scan1_location
scan=1
if size == -1:
size = line.find(scan2, 0, length)
scan=2
if size == -1:
size = line.find(scan3, 0, length)
scan=3
if size > -1:
# Count the number of numbers masked (because I like numbers)
found+=1
line = line.split(" ")
line = maskLine(line, scan)
# Newline is removed during the parsing process
output.write(line + "\n")
else:
output.write(line)
# Count total number of lines (because I like numbers)
count+=1
# Read next line
line = file.readline()
length = len(line)
file.close()
print(count)
print(found)
output.close()
</code></pre>
<p>Update: Per RootTwo's request, here are a few sample strings that I would be editing. And to answer their question, out of 2,000,000+ lines in my test run, I only captured 17,000 lines with protected information. So they are very interspersed. But all numbers I need to mask all come after three cases:</p>
<ol>
<li><p>"bankAccount: "</p></li>
<li><p>",bankAccount,"</p></li>
<li><p>" accountNumber="</p></li>
</ol>
<p>scanX_location were supposed to be the static array locations in "line" that the numbers were located but I recently discovered the size of "line" is dynamic in a few cases. So I need to rework the way I find where the numbers are in each line. Here are a few sample cases.</p>
<p>(The fifth one is an example of a line that doesn't require masking.)</p>
<ol>
<li><p>11.11.11.11.1111111111111.111111.IVR,09/16/2019 00:46:24.190,Make Checking Payment,custom,FYI,Inputs - bankAccount: 111111111111 routingNumber: 111111111</p></li>
<li><p>11.11.11.11.1111111111111.111111.IVR,09/16/2019 00:49:54.992,Make Checking Payment,custom,bankAccount,******3060</p></li>
<li><p>11.11.11.11.111111111111.111111.IVR,09/16/2019 00:49:54.992,Make Checking Payment,custom,ivrUser,IvrUser{environment=prod accountId=111111111 primaryPerson=1111111111 personIdList=[1111111111] houseNumber=11111 streetName=N Main St N Unit 11 zipCode=11111 phoneNumber=1111111111 phoneNumberFormatted=(111) 111-1111 customerClass=Normal numberOfAccounts=11 accountBalance=11.11 accountDueDate=2019-09-10 isEligible=true isEligibleReason=null amountDue=AmountDue{currentAmount=11.11 latestPayment=11 latestpaymentDate=2019-08-15} cashOnlyEligible=true cashOnlyScore=0 checkPaymentAmountDue=11.12 accountSearchCount=0 savedBankInfo=[BankInfo{routingNumber=111111111 accountNumber=1111111111 encrAccountNumber= eligibleForOneTimePayment=false personPaymentOptionId=null} BankInfo{routingNumber=111111111 accountNumber=1111111111 encrAccountNumber= eligibleForOneTimePayment=false personPaymentOptionId=null}] payPlan=PayPlan{hasPayPlan=false payPlanId=null nextAmount=null nextDate=null} hasPendingPayment=false pendingDisconnect=false payOption=null payPlanConfirmation=null debugSteps=[Starting: MakePayment: getSavedBankInfo personCount: 1 call MakePayment: listBankInfo.add: BankInfo{routingNumber=111111111 accountNumber=1111111111 encrAccountNumber= eligibleForOneTimePayment=false personPaymentOptionId=null}; listBankInfo.add: BankInfo{routingNumber=111111111 accountNumber=1111111111 encrAccountNumber= eligibleForOneTimePayment=false personPaymentOptionId=null}; setHasPendingPayment: false; setSavedBankInfo and return;] Report=null phonePersonDetails=[1111111111]}</p></li>
<li><p>11.11.11.11.1111111111111.111111.IVR,09/16/2019 18:37:35.857,Make Checking Payment,custom,FYI,Starting Delete of Saved Payment Info for: Person{personId=1111111111 personOrBusiness=P version=11 paymentOptionId=null bankInfoList=[BankInfo{routingNumber=111111111 accountNumber=111111111111 encrAccountNumber=null eligibleForOneTimePayment=false personPaymentOptionId=111111111111} BankInfo{routingNumber=111111111 accountNumber=1111111111 encrAccountNumber=null eligibleForOneTimePayment=false personPaymentOptionId=111111111111} BankInfo{routingNumber=111111111 accountNumber=1111111111 encrAccountNumber=null eligibleForOneTimePayment=false personPaymentOptionId=111111111111}]}</p></li>
<li><p>11.11.11.11.1111111111111.111111.IVR,09/16/2019 18:37:36.904,Make Checking Payment,custom,FYI,Starting Delete of Saved Payment Info for: Person{personId=1111111111 personOrBusiness=P version=3 paymentOptionId=null bankInfoList=[]}</p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T06:35:16.843",
"Id": "446305",
"Score": "0",
"body": "Are the different kinds of lines intermixed within a file, or does a file only have one kind of line in it? Can you provide example lines (with made up data obviously)?"
}
] |
[
{
"body": "<h3>Document everything</h3>\n\n<p>You will now be on the hook to maintain this code (which is fine). So, document everything very well. What does <code>scan1_location</code> mean and why is it equal to <code>6</code>, but <code>scan2_location = 3</code>. Will you remember why a year from now when your friend asks you to update the code to handle a new kind of line, or when one of the line format changes?</p>\n\n<p>Include a top level docstring explaining what the file does any why. Include a sample of every kind of line.</p>\n\n<h3>proper command line program</h3>\n\n<p>It looks like this is to be a command line program. So make it a proper command line program. Take a look at the 'click' library. At a minimum, it should have a way to get help with proper usage of the program. I would add a way to turn on logging, to help with tracking down the inevitable bug.</p>\n\n<h3>separate output directory</h3>\n\n<p>Presumably, the account numbers are being masked in the files, so the files can be seen or used by people that aren't allowed to see the account numbers. Intermixing the masked and unmasked files in the same directory is asking for someone to accidentally send a wrong file. </p>\n\n<h3><code>open()</code> can be used as a context manager</h3>\n\n<p>It looks like <code>output.close()</code> if misplaced. A new output file is opened whenever a new input filed is opened, and they should probably be closed be together too. The easiest way to ensure files are closed when you are done with them is to use a <code>with</code> statement:</p>\n\n<pre><code>with open(...) as input_file, open(...) as output_file:\n\n ... process the files in this block of code ...\n\n... the files automatically get closed here ...\n</code></pre>\n\n<h3>open files are iterable</h3>\n\n<p>To iterate over the lines in a file use:</p>\n\n<pre><code>for line in input_file:\n ... process the lines ...\n</code></pre>\n\n<h3>str.find(substring, start, end)</h3>\n\n<p>start and end default to 0 and the length of the string, so it is not necessary to provide them.</p>\n\n<p>That's all for now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T21:05:23.530",
"Id": "446371",
"Score": "0",
"body": "I completely reorganized my program to use regex and your recommendation on context management and its now much more readable (though now bottlenecked by CPU instead of I/O). Thank you for the wonderful suggestions. This was my first CodeReview post and it was exactly what I needed. I'll be sure to utilize CodeReview more from now on!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T22:04:06.613",
"Id": "446373",
"Score": "0",
"body": "I was going to suggest a regex approach (using re.sub), but needed to see the sample data to know if it would work."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T07:57:38.060",
"Id": "229445",
"ParentId": "229439",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229445",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T02:52:22.447",
"Id": "229439",
"Score": "3",
"Tags": [
"python",
"parsing"
],
"Title": "Parsing large text files - Masking all bank numbers"
}
|
229439
|
<p>This code runs slowly, even with numbers smaller than 1,000,000. Can someone help me optimize this thing?</p>
<pre class="lang-swift prettyprint-override"><code>// Finds the highest perfect square below a certain input (int)
let target: Int = 758865 // Swap this out for testing other numbers
var smlSqr = [Int]()
let findLimit = Int(Double(target).squareRoot().rounded(.up)) // Saves CPU time, because perfect squares less than
// number a but higher than a.squareRoot is impossible.
var index = 0
var maxSqr = 0 // Final result
var candidate = 0
repeat {
smlSqr.append(index * index)
index += 1
} while(index < findLimit)
while candidate < smlSqr.count {
if smlSqr[candidate] > maxSqr {
maxSqr = smlSqr[candidate]
}
candidate += 1
}
print(String(maxSqr)) // For debugging, should print out 100
print(Int(Double(maxSqr).squareRoot())) // For debugging, making sure the number is actually a perfect square
</code></pre>
<p>I'm using Swift 5.1 on Xcode 11.
Also using a playground (if that helps)</p>
|
[] |
[
{
"body": "<blockquote>\n <p>Also using a playground (if that helps)</p>\n</blockquote>\n\n<p>Well, that is the main reason for the slow execution. A playground is an interactive environment, and the code is not optimized. For all computations in the main playground file, intermediate results are displayed in the side bar (such as the values of the variables, or how often a loop has executed). This makes longer computations really slow.</p>\n\n<p>For code that consists of many computation steps you better</p>\n\n<ul>\n<li>either move it to a function in a separate playground source file, </li>\n<li>or use a compiled Xcode project instead of a playground.</li>\n</ul>\n\n<p>I often prefer a compiled project over a playground because</p>\n\n<ul>\n<li>you can <em>debug</em> your code (single-step, inspect variables, ...),</li>\n<li>you can enable optimizations (compile with the “Release” configuration) for performance critical tasks.</li>\n</ul>\n\n<p>But your code can also be simplified and optimized. This loop</p>\n\n<pre><code>var index = 0\nvar smlSqr = [Int]()\nrepeat {\n smlSqr.append(index * index)\n index += 1\n} while(index < findLimit)\n</code></pre>\n\n<p>appends one array element in each loop iteration, so that it can be written as a <em>map</em> operation:</p>\n\n<pre><code>let smlSqr = (0..<findLimit).map { k in k * k }\n</code></pre>\n\n<p>(You may also think about better variable names: what does <code>smlSqr</code> stand for?)</p>\n\n<p>And this</p>\n\n<pre><code>var maxSqr = 0 // Final result\nvar candidate = 0\nwhile candidate < smlSqr.count {\n if smlSqr[candidate] > maxSqr {\n maxSqr = smlSqr[candidate]\n }\n candidate += 1\n}\n</code></pre>\n\n<p>determines the largest array element. The is a dedicated method for that purpose:</p>\n\n<pre><code>let maxSqr = smlSqr.max()!\n</code></pre>\n\n<p>(We can force-unwrap here if we know that the array is not empty.) But the array elements are sorted in increasing order, so that the largest element is actually the last element:</p>\n\n<pre><code>let maxSqr = smlSqr.last!\n</code></pre>\n\n<p>So what we have so far is</p>\n\n<pre><code>let target = 758865\nlet findLimit = Int(Double(target).squareRoot().rounded(.up))\nlet smlSqr = (0..<findLimit).map { k in k * k }\nlet maxSqr = smlSqr.last!\n</code></pre>\n\n<p>and now we can see that this can be simplified even further: The last element appended to the array is <code>(findLimit - 1) * (findLimit - 1)</code>, so that we only need</p>\n\n<pre><code>let target = 758865\nlet findLimit = Int(Double(target).squareRoot().rounded(.up))\nlet maxSqr = (findLimit - 1) * (findLimit - 1)\n</code></pre>\n\n<p>(And this is so short and fast that you can execute it in in a playground directly, without any of the optimization tricks mentioned above.)</p>\n\n<p>To make the code reusable, you should define it as a function:</p>\n\n<pre><code>func largestSquareRoot(lessThan n: Int) -> Int {\n let root = Int(Double(n).squareRoot().rounded(.up)) - 1\n return root * root\n}\n</code></pre>\n\n<p>Note that this gives a nonsensical result for <span class=\"math-container\">\\$ n = 0 \\$</span> and crashes for <span class=\"math-container\">\\$ n < 0 \\$</span>. You'll have to define what result you want in those cases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T15:00:45.830",
"Id": "446450",
"Score": "0",
"body": "```smlSqr``` means \"small squares\" (a list of perfect squares smaller than input)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T19:00:18.837",
"Id": "447844",
"Score": "2",
"body": "I think Martin figured that out. Lol. I think the point was that we generally prefer clarity over brevity, and as such `smallSquares` might be a better name than `smlSqr`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T09:29:57.520",
"Id": "229450",
"ParentId": "229441",
"Score": "6"
}
},
{
"body": "<p>Martin is right that playgrounds are notoriously inefficient. Using compiled target will solve this problem.</p>\n\n<p>But the other issue is that the chosen algorithm is inefficient. Your algorithm is basically trying every integer, one after another, until you reach the appropriate value. So, with your input of 758,865, you’ll try every integer between 0 and 872. That’s 873 iterations.</p>\n\n<p>There are far better approaches. Martin (+1) is right that the easiest solution is to use the built-in <code>sqrt()</code> function. That having been said, these sorts of questions are testing your ability to write algorithms and they don’t generally want you just calling some system function.</p>\n\n<h3>Binary search</h3>\n\n<p>So, which algorithm should we use? The “go to” solution for improving searches is often the <a href=\"https://en.wikipedia.org/wiki/Binary_search_algorithm\" rel=\"nofollow noreferrer\">binary search</a>. Let’s say you wanted square root of <code>n</code>. You know that the answer rests somewhere in the range between <code>0</code> and <code>n</code>. </p>\n\n<ol>\n<li>Let’s consider <code>0</code> to be our “lower bound” and <code>n</code> to be our “upper bound” of possible values.</li>\n<li>Pick a “guess” value in the middle of the range of possible values;</li>\n<li>Square this guess by multiplying it by itself;</li>\n<li>See if the result of this is too big or too small;\n\n<ul>\n<li>If it’s too big, throw away the top half of the range (by adjusting the upper bound of our modified range to be what was previously the middle of the range, namely our last guess);</li>\n<li>Likewise, if it’s too small, we throw away the bottom half of the range (by adjusting the lower bound of our range to be equal to the last guess); and</li>\n</ul></li>\n<li>Repeat the process, halving the range of possible values each time, looping back to step 2.</li>\n</ol>\n\n<p>This binary search technique finds the answer to 758,865 in 20 iterations rather than 873.</p>\n\n<p>That might look like:</p>\n\n<pre><code>func nearestSquare(below value: Int) -> Int? {\n guard value > 0 else { return nil }\n\n let target = value - 1\n var upperBound = value\n var lowerBound = 0\n\n repeat {\n let guess = (upperBound + lowerBound) / 2\n let guessSquared = guess * guess\n let difference = guessSquared - target\n if difference == 0 {\n return guessSquared\n } else if difference > 0 {\n upperBound = guess\n } else {\n lowerBound = guess\n }\n } while (upperBound - lowerBound) > 1\n\n return lowerBound * lowerBound\n}\n</code></pre>\n\n<p>There are refinements you could do, but this is the basic idea. Keep cutting the range of possible solutions in half and trying the middle value until you’ve got a winner. The binary search is a mainstay of efficient searches through large ranges of possible values.</p>\n\n<h3>Newton-Raphson</h3>\n\n<p>That having been said, while a binary search is a huge improvement, there are even other, more efficient, algorithms, if you’re so inclined. For example, <a href=\"https://en.wikipedia.org/wiki/Newton%27s_method\" rel=\"nofollow noreferrer\">Newton–Raphson</a> can calculate the result for 758,865 in only 12 iterations.</p>\n\n<p>The Newton-Raphson is an iterative technique in which you</p>\n\n<ol>\n<li>take a guess;</li>\n<li>identify where that falls on a curve;</li>\n<li>calculate the tangent to that point on the curve;</li>\n<li>identify the x-intercept of that tangent; and</li>\n<li>use that as your next guess, repeating until you find where it crosses the x-axis.</li>\n</ol>\n\n<p>So, the notion is that the square root of <code>n</code> can be represented as the positive x-intercept of the function:</p>\n\n<blockquote>\n <p><span class=\"math-container\">\\$y = x^2 - n\\$</span></p>\n</blockquote>\n\n<p>We know that the tangent of a given point on this curve in iteration <em>i</em> is:</p>\n\n<blockquote>\n <p><span class=\"math-container\">\\$y = m_ix + b_i\\$</span></p>\n</blockquote>\n\n<p>Where the slope is the first derivative of the above curve:</p>\n\n<blockquote>\n <p><span class=\"math-container\">\\$m_i = 2x_i\\$</span></p>\n</blockquote>\n\n<p>and the y-intercept is:</p>\n\n<blockquote>\n <p><span class=\"math-container\">\\$b_i = y_i - m_ix_i\\$</span></p>\n</blockquote>\n\n<p>And the x-intercept (i.e. our guess for the next iteration) of that tangent is:</p>\n\n<blockquote>\n <p><span class=\"math-container\">\\$x_{i+1} = -\\frac{b_i}{m_i}\\$</span></p>\n</blockquote>\n\n<p>So, you can calculate the nearest perfect square below a given value using Newton-Raphson like so:</p>\n\n<pre><code>func nearestSquare(below value: Int) -> Int? {\n guard value > 0 else { return nil }\n\n let target = value - 1\n\n func f(_ x: Int) -> Int { // y = x² - n\n return x * x - target\n }\n\n var x = target\n var y = f(x)\n\n while y > 0 {\n let m = 2 * x // slope of tangent\n let b = Double(y - m * x) // y-intercept of tangent\n x = Int((-b / Double(m)).rounded(.down)) // x-intercept of tangent, rounded down\n y = f(x)\n }\n\n return x * x\n}\n</code></pre>\n\n<p>Or you can simplify that formula a bit, doing a few arithmetic substitutions, to:</p>\n\n<blockquote>\n <p><span class=\"math-container\">\\$x_{i+1} = x_i-\\frac{y_i}{2x_i}\\$</span></p>\n</blockquote>\n\n<p>Thus:</p>\n\n<pre><code>func nearestSquare(below value: Int) -> Int? {\n guard value > 0 else { return nil }\n\n let target = Double(value - 1)\n\n func f(_ x: Double) -> Double { // y = x² - n\n return x * x - target\n }\n\n var x = target\n var y = f(x)\n\n while y > 0 {\n x = x - (y / x / 2).rounded(.up)\n y = f(x)\n }\n\n return Int(x * x)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T04:34:09.020",
"Id": "230204",
"ParentId": "229441",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230204",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T03:14:17.460",
"Id": "229441",
"Score": "4",
"Tags": [
"performance",
"beginner",
"swift"
],
"Title": "Finding a perfect square smaller than an input number (Swift)"
}
|
229441
|
<p>my use-case (an home task to practice abstraction, exception handling, unitests) is regarding a message-queue with small-fixed-size client requests from <strong>stdin</strong> of such: </p>
<blockquote>
<ol>
<li>[ENQ] data (insert json data to queue)</li>
<li>[DEQ] (get latest in queue)</li>
<li>[STATUS] (status of queue)</li>
<li>[STOP] (stop server)</li>
<li>[EXIT]</li>
</ol>
</blockquote>
<p>Without any scalability demands, except that there could be multi-clients and command might be extended in future.</p>
<p>I know there could be <strong>multiple approaches to handle multi-client-server model</strong> - multi-threaded or select one and that there are existent frameworks (Twisted, gevant).
I have chosen to implement a simple socket-per-command approach with BLOCKING threads. one main server thread will serve each coming socket with a timeout. every-time a new request arrives - new socket_connection is open - server reads whole data, sends a response and socket is closed. Then server moves to the next socket_connection, eventually holding ONE socket-a-time in a while() loop.</p>
<p><strong>Pros for the approach are:</strong></p>
<ol>
<li>Intention to practice on abstraction, exception handling, tests and not on 'the right' way to work with sockets.</li>
<li>Easy to code and handle command-per-connection and verify buffer is fully 'read' by server.</li>
</ol>
<p><strong>Cons:</strong></p>
<ol>
<li>Sending huge JSON data on ENQ might block server main thread for long period of time. </li>
<li>Not easy to extend / scale.</li>
<li>Overhead of open-close connection socket.</li>
<li>NO Concurrency.</li>
</ol>
<p><strong>My questions are:</strong> </p>
<ol>
<li>Are best practices/design patterns used for this use-case? in terms of time of coding-time, complexity, performance, etc.</li>
<li>If so - how is the flow?</li>
<li>Are all cases taken care?</li>
<li>Exception handling?</li>
<li><strong>Is this approach better than select?</strong> server now holds 2x sockets (master & client) and only takes care of one socket, client- creates and terminates it socket per each stdin-request. rather than Select() which holds multiple sockets per client and DOES NOT TERMINATE socket for the whole std-in connection.</li>
</ol>
<p><strong>Server-side: accept a socket connection and send response:</strong></p>
<pre><code>def serve_forever(self):
# init socket
self.socket = self.init_socket(self.connection_details)
while not self._stop:
# connect new client:
conn, addr = self.socket.accept()
conn.settimeout(Utils.TIMEOUT)
self.logger.info("New client {} has arrived".format(conn.getpeername()))
response = {}
try:
# read from socket:
data = self.read(conn)
self.logger.info("Read successfully data from client")
if not data:
break # client disconnected while writing to socket
# write response to socket:
response = self.handle_request(Utils.json_decode(data))
self.write(conn, Utils.json_encode(response))
self.logger.info("Sent successfully {}".format(response))
except (socket.timeout, SocketReadError, SocketWriteError) as e:
self._handle_socket_err(response, e)
finally:
# close connection:
self._close_connection(conn)
self.logger.info("Closed client connection successfully")
self.stop_server()
</code></pre>
<p><strong>Client-side: create a socket-per-command(request):</strong></p>
<pre><code>def run(self):
while True:
# parse std_input
in_read = input("Enter wanted command\n").split(" ", 1)
if not Utils.validate_input(in_read):
print("Wrong stdin command entered")
continue
# init new socket connection:
self.connect()
try:
# send request to server:
request = self.parse_command(in_read)
self.write(self.socket, Utils.json_encode(request))
self.logger.info("Client {} sent successfully command: {}".format(self._get_name(), request))
# read response from server:
response = Utils.json_decode(self.read(self.socket))
self.logger.info("Client {} received successfully response {}".format(self._get_name(), response))
self.close_connection()
except (socket.timeout, SocketReadError, SocketWriteError) as e:
self.logger.error("Exception occurred".format(e))
else:
if request.get("type") == "EXIT" or request.get("type") == "STOP":
self.logger.info("Closing server and existing client stdin")
exit()
</code></pre>
<p><strong>And simple handle_request (command) on server side:</strong></p>
<pre><code>def handle_request(self, request: dict) -> dict:
self.logger.debug("Handling request {}".format(request))
command_type, payload, status_code = request.get("type"), request.get("payload"), StatusCode.OK
if command_type == "ENQ":
status_code, payload = self._handle_enq(payload)
elif command_type == "DEQ":
status_code, payload = self._handle_deq(payload)
elif command_type == "DEBUG":
status_code, payload = self._handle_debug(payload)
elif command_type == "STAT":
status_code, payload = self._handle_stat(payload)
elif command_type == "STOP" or command_type == "EXIT":
status_code, payload = self._handle_stop(payload)
self.logger.debug("Finished handling request")
response = self._create_response(status_code, command_type, payload)
return response
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T08:25:31.213",
"Id": "229447",
"Score": "3",
"Tags": [
"python",
"socket",
"tcp"
],
"Title": "one-thread blocking approach for socket tcp multi-client server"
}
|
229447
|
<p>I do some art both analog and digital. This time I did some color test digitally. To work on my programming skill so that it's shareable I'm asking for help to get some code review.</p>
<ul>
<li>How's the readability? </li>
<li>Is it easy to follow line of thought? </li>
<li>Suggestion as to how to improve?</li>
</ul>
<p>I'm using <a href="https://pypi.org/project/graphics.py/" rel="nofollow noreferrer">John Zelles graphics.py</a> for this</p>
<hr>
<pre><code>#A program for fun to see how red, blue and purple appears at resolution
from math import *
from graphics import *
def hole(win, centerx, centery, radius): #draws an inverted sphere
for circle in range(radius, 0, -1):
c = Circle(Point(centerx, centery), circle)
c.setWidth(0)
coloratangle = int(sin(circle/radius*pi/2)*255) #max resolution from black to white is 255 steps
c.setFill(color_rgb(coloratangle * (circle % 2), 0, coloratangle * ((circle + 1) % 2))) # Modulus instead of Boolean? Modulus in c.setFill or in another line?
c.draw(win)
windowheight = 1350
windowwidth = 730
win = GraphWin("My Circle", windowheight, windowwidth)
win.setBackground(color_rgb(255, 100, 100))
centerx = int(windowheight / 2)
centery = int(windowwidth / 2) #intetger
radius = int(sqrt(centerx**2 + centery**2)) #pythagoras
hole(win, centerx, centery, radius)
win.getMouse() # Pause to view result
win.close() # Close window when done
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T23:55:01.277",
"Id": "446379",
"Score": "0",
"body": "`graphics` doesn't seem to be in the standard library. It's probably \"Zelle's graphics\", available via https://pypi.org/project/graphics.py/ - seem right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T08:14:18.847",
"Id": "446413",
"Score": "0",
"body": "Yes its John Zelles graphics, sorry i forgot to write it in original post. Since you added this information is it no longer new information or should i ad it to question as new information?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T13:29:12.920",
"Id": "446428",
"Score": "0",
"body": "It's totally fine to add more explanatory information to your existing question."
}
] |
[
{
"body": "<p>I actually ran this. Good thing I don't have epilepsy, because wow. The flashing is intense.</p>\n\n<p>There are many ways to improve this, depending on how technical you want to get. Move to a more advanced graphics library that's able to draw circles in an off-screen memory buffer before showing them in <code>tkinter</code>, your current windowing framework. This will speed up the rendering significantly and won't create that flashing (unless that's part of your art?).</p>\n\n<p>There's a bug where moving your window creates even more flashing - this time, instead of being due to the concentric circles being rendered from the outside in, I suspect it's from the circles being re-rendered by <code>graphics.py</code> rather than flattening the representation of the image to a rasterized buffer. Rendering to an off-screen buffer will fix this, too.</p>\n\n<p>There's another bug: closing the window produces this stack trace -</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> File \"/opt/pycharm-community-2019.2.1/helpers/pydev/pydevd.py\", line 2060, in <module>\n main()\n File \"/opt/pycharm-community-2019.2.1/helpers/pydev/pydevd.py\", line 2054, in main\n globals = debugger.run(setup['file'], None, None, is_module)\n File \"/opt/pycharm-community-2019.2.1/helpers/pydev/pydevd.py\", line 1405, in run\n return self._exec(is_module, entry_point_fn, module_name, file, globals, locals)\n File \"/opt/pycharm-community-2019.2.1/helpers/pydev/pydevd.py\", line 1412, in _exec\n pydev_imports.execfile(file, globals, locals) # execute the script\n File \"/opt/pycharm-community-2019.2.1/helpers/pydev/_pydev_imps/_pydev_execfile.py\", line 18, in execfile\n exec(compile(contents+\"\\n\", file, 'exec'), glob, loc)\n File \"/home/gtoombs/PycharmProjects/zelles/zelles.py\", line 25, in <module>\n win.getMouse() # Pause to view result\n File \"/home/gtoombs/.virtualenvs/zelles/lib/python3.7/site-packages/graphics/__init__.py\", line 316, in getMouse\n if self.isClosed(): raise GraphicsError(\"getMouse in closed window\")\ngraphics.GraphicsError: getMouse in closed window\n</code></pre>\n\n<p>which means that you're not handling shut-down gracefully. See if you can change your exit condition to be either when the mouse event is received or the window is closed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T08:40:55.450",
"Id": "446416",
"Score": "0",
"body": "Thank you for running the program and lending your insights wich are eye opening to me. When i look into the ways to improve the program and probably run into hard to solve obstacles should i post as a comment to make a thread or state a new post question? For example the computer im using run out of memory for some fractals rendering. I was thinking about saving it to image every number of iterations to skip layers behind top circle. Is flattening to skip layers behind top circle?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T13:31:09.150",
"Id": "446429",
"Score": "1",
"body": "If you're asking clarifying questions to my answer, you can do so in the comments. If you're running out of memory, that's a question for StackOverflow. Yes, flattening forgets all of the layers and all of the information about circle sizes, only saving the image."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T14:55:28.930",
"Id": "446575",
"Score": "0",
"body": "Hi:) After trying to get a more gracefull shut down I thought the program might be better off without the last two lines?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T15:14:02.093",
"Id": "446578",
"Score": "0",
"body": "You still need something to pause the program. Replace those two lines with `win.wait_window()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T17:17:59.183",
"Id": "446628",
"Score": "0",
"body": "when i do so and exit without clicking in window i get \"error\" message. Without those three lines the window hovers paused even though the program is stopped in idle and every way ive closed the window no \"error\" message. Is there an error message im not seeing with default idle?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T17:32:16.157",
"Id": "446633",
"Score": "0",
"body": "We're a little off the rails, here. I recommend that you post your code on StackOverflow to fix the closure bug."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T17:19:13.440",
"Id": "447037",
"Score": "0",
"body": "Hi:) I dont know why but it seams to me that minimizing the pop up window while running the program iterates the image a whole lot quicker and when maximized paints it in one go. Im a bit curious to why but have enough on my table for now but in the future is that a question for stack overflow? Anyhow i wanted to share what i found out:)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T00:31:25.480",
"Id": "229479",
"ParentId": "229448",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T08:41:50.130",
"Id": "229448",
"Score": "3",
"Tags": [
"python",
"computational-geometry"
],
"Title": "A program for fun to see how red and blue appears blended to purple due to resolution"
}
|
229448
|
<p>I am making a basic program just for a local machine so I do not need to create anything fancy but I am finding that my code is going to become quite lengthy. Any tips on how to improve it so I am not repeating code? I have additional code to add in respect to client data etc but I am primarily concentrating on the foundation first.</p>
<pre><code>from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.withdraw()
def login(event):
if ent1.get() == 'admin' and ent2.get() == 'password':
root.iconify()
top.destroy()
def client_data(event):
root.withdraw()
top = Toplevel()
top.title('Client Data')
top.geometry('800x500')
top.configure(background='grey')
client1 = Message(top, text='Random skeleton', bg='grey', width=350)
client1.pack()
x = Button(top, text='Close', bg='red', command=top.destroy)
root.iconify()
x.pack()
image1 = ImageTk.PhotoImage(Image.open('ileye.png'))
top = Toplevel()
top.title('Login')
top.configure(background='grey')
photo = Label(top, image=image1)
photo.pack()
user = Label(top, text='User name', bg='grey')
user.pack()
ent1 = Entry(top, bg='grey')
ent1.pack()
pwd = Label(top, text='Password', bg='grey')
pwd.pack()
ent2 = Entry(top, show='*', bg='grey')
ent2.bind('<Return>', login)
ent2.pack()
ex = Button(top, text='EXIT', command=root.quit)
ex.pack()
check = Checkbutton(top, text='Remember me', bg='grey')
check.pack()
root.title('Main Screen')
root.attributes('-zoomed', True)
menu_drop = Menu(root)
root.config(menu=menu_drop)
file = Menu(menu_drop)
menu_drop.add_cascade(label='Options', menu=file)
file.add_command(label='New', command=root.quit) ## New Function
client = Button(root, text='Client list')
file.add_separator()
file.add_command(label='Close App', command=root.quit)
client.bind('<Button-1>', client_data)
client.pack()
exi = Button(root, text='EXIT', command=root.quit)
exi.pack()
root.mainloop()
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>Any tips on how to improve it so I am not repeating code?</p>\n</blockquote>\n\n<p>There isn't really a lot of repeated code, here. I think you're fine on that front.</p>\n\n<h2>Avoid globals</h2>\n\n<p>Starting with <code>image1</code> onward, you have lots of globals. Try to move them into a class, for a few reasons: re-entrance (you could spawn multiple identical windows), general code organization, namespace cleanliness, etc.</p>\n\n<h2>Credential management</h2>\n\n<pre><code>if ent1.get() == 'admin' and ent2.get() == 'password':\n</code></pre>\n\n<p>I know that you are</p>\n\n<blockquote>\n <p>making a basic program just for a local machine</p>\n</blockquote>\n\n<p>but this is never a good habit to get into. Hard-coding passwords is not secure, and it isn't much more difficult to do the \"right\" thing. Import a library to be able to securely handle authentication and encrypted credential storage.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T13:08:04.870",
"Id": "446426",
"Score": "0",
"body": "Brill thanks for the advice. I will probably use crypto or something similar in respect to credential management. I will put the globals into a class also. I want it to be right"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T03:15:36.583",
"Id": "229484",
"ParentId": "229451",
"Score": "2"
}
},
{
"body": "<h3>Never do this:</h3>\n\n<pre class=\"lang-py prettyprint-override\"><code>from tkinter import *\n</code></pre>\n\n<p>Instead use:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from tkinter import Every, Class, I, Will, Ever, Need\n</code></pre>\n\n<p>Or if your really must:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import tkinter as tk\n# Or:\nimport tkinter\n</code></pre>\n\n<p>or similar. <code>import *</code> just dumps all module-level variables in your global space, which makes it a lot harder to read your code.</p>\n\n<h3>GUI Organization</h3>\n\n<p>I'm not 100% on how much this applies to Tkinter, but for PyQt we'd put as much of the initialization of GUI elements into extensions of the element's classes. So any child widget of X would be defined by and inside a method of X. </p>\n\n<p>Otherwise, you could put it all in a function named main() and then call that function inside a <code>if __name__ == \"__main__\":</code> <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">guard</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T13:08:45.147",
"Id": "446427",
"Score": "0",
"body": "Thats a very good point thank you for that! I will amend it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T13:36:34.963",
"Id": "446430",
"Score": "0",
"body": "\"Never do this\" - there's a little more nuance than that. Another alternative is to `import tkinter as tk`, so that you don't have to spell out all of your imported classes, and the module references are more brief. Also note that your advice forces people to fill their namespace with module symbols, which shouldn't always be done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T13:48:11.877",
"Id": "446431",
"Score": "0",
"body": "I guess that's worth mentioning as alternative. Personally, though, I find that long.dotted.names also have a tendency to confuse me when parsing code."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T07:18:35.767",
"Id": "229494",
"ParentId": "229451",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229484",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T09:30:37.867",
"Id": "229451",
"Score": "3",
"Tags": [
"python",
"tkinter"
],
"Title": "Creating a basic structure in tkinter"
}
|
229451
|
<p>This code generates a fractal picture. I'm experimenting with using long variable names to see if the code is still readable without comments. I'm a slow reader and loose track a lot and thought to myself why read twice (variable names and comments).</p>
<ul>
<li>(When) is it better to replace comments with longer descriptive variable and function names?</li>
<li>Does this code make sense to you?</li>
<li>Would it be better off with comments?</li>
</ul>
<pre class="lang-py prettyprint-override"><code>from math import *
from graphics import *
def brushes(win, centerx, centery, brushmaximumradius):
for brush in range(brushmaximumradius, 0, -1):
spiralrevolutions = 10 * pi
spiralanglevector = ((brushmaximumradius - brush) / brushmaximumradius * spiralrevolutions) ** 1.6
spiralradius= (brushmaximumradius - brush) ** 0.8
xaxistremble = (spiralradius / 10) * cos(spiralanglevector * 3)
yaxistremble = (spiralradius / 10) * sin(spiralanglevector * 3)
xkoordinat = int(spiralradius * cos(spiralanglevector) + xaxistremble) + centerx
ykoordinat = int(spiralradius * sin(spiralanglevector) + xaxistremble) + centery
c = Circle(Point(xkoordinat, ykoordinat), brush)
c.setWidth(0)
period = 1.3
perioddisplacement = 0.15
maximumlightintensity = 223
lowestlightintensity = 22
lightintensityatangle = int(sin(brush/brushmaximumradius*pi/2 * period + perioddisplacement) * maximumlightintensity + lowestlightintensity)
amplitude = amplitudedisplacement = 0.5
cirkelRGBred = int(lightintensityatangle * (sin(spiralanglevector) * amplitude + amplitudedisplacement))
cirkelRGBgreen = int(lightintensityatangle * (sin(spiralanglevector + pi/2) * amplitude + amplitudedisplacement))
cirkelRGBblue = int(lightintensityatangle * (sin(spiralanglevector + pi) * amplitude + amplitudedisplacement))
c.setFill(color_rgb(cirkelRGBred, cirkelRGBgreen, cirkelRGBblue))
c.draw(win)
windowwidth = 1350
windowheight = 730
win = GraphWin("My Circle", windowwidth, windowheight)
win.setBackground(color_rgb(55, 55, 55))
centerx = int(windowwidth / 2)
centery = int(windowheight / 2)
windowcornerfitting = 1.04
brushmaximumradius = int(windowcornerfitting * sqrt(centerx**2 + centery**2))
brushes(win, centerx, centery, brushmaximumradius)
win.getMouse()
win.close()
</code></pre>
<p><img src="https://i.stack.imgur.com/xnsbW.png" alt="enter image description here"></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T14:28:15.230",
"Id": "446441",
"Score": "0",
"body": "I'm not convinced that this picture is a fractal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T14:51:45.077",
"Id": "446447",
"Score": "0",
"body": "Hi:) How do you mean, in what way? I started to think about the precise definition of a fractal (wich i dont know). Anyhow its a python program that iterates and the picture is the result."
}
] |
[
{
"body": "<blockquote>\n <p>(When) is it better to replace comments with longer descriptive variable and function names?</p>\n</blockquote>\n\n<p>That's one of the finer arts of programming, and varies by language. Much of the time, code should be clear enough and variable names sensible enough that comments are rarely needed, except for in the important places like method docstrings (which should exist regardless).</p>\n\n<p>Since Python is not a strongly-typed language, it needs a little bit of encouragement to add type information, but it can still be (kind of) done via PEP484. Doing this will further enhance your ability to understand the code without needing to rely on explanatory comments. For example (these are only educated guesses):</p>\n\n<pre><code>def brushes(win: GraphWin, center_x: int, center_y: int, brush_max_radius: float):\n</code></pre>\n\n<p>Note the underscore convention for Python variable names.</p>\n\n<blockquote>\n <p>Does this code make sense to you?</p>\n</blockquote>\n\n<p>I mean... not really? But that's just because I don't understand the fractal algorithm.</p>\n\n<p>Some of the variable names are not English - koordinat? Since most of your other names are English, you should make this English, too. Some people argue that English is the universal language of development. I'm less convinced, but at least you should be internally consistent.</p>\n\n<p><code>brushes</code> is a confusing name. A method name should be an action - perhaps <code>draw_brushes</code>.</p>\n\n<p>Another trick to get shorter, but still understandable, variable names - drop redundant information. <code>windowwidth</code> is the only width in your code, and it's used right next to the place where it's called, so call it simply <code>WIDTH</code> (capitals because it's a constant).</p>\n\n<blockquote>\n <p>Would it be better off with comments?</p>\n</blockquote>\n\n<p>Yes, definitely - but only comments that are useful.</p>\n\n<p>A comment like this:</p>\n\n<pre><code># spiral revolutions\nspiral_revolutions = 10*pi\n</code></pre>\n\n<p>is useless. However, a comment like this is very important and useful:</p>\n\n<pre><code>\"\"\"\nThis is an implementation of the fractal algorithm xxx from chapter\nyyy of Zells' Python Programming.\n\n:param win: The window object to which the fractal will be drawn.\n:param center_x: The x-coordinate of the fractal's origin, in window space. \n:param center_y: The y-coordinate of the fractal's origin, in window space.\n:param brush_max_radius: The maximum radius of the circles constituting the fractal.\n\"\"\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T11:09:10.247",
"Id": "446423",
"Score": "1",
"body": "It occurd to me that what im asking for is some sort of pointer as to what is common sense and practice so that programs i write can be useful to other programers and i think you gave me some good useful tips. Thank you:)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-02T11:43:19.950",
"Id": "474168",
"Score": "0",
"body": "Python *is* strongly typed, but not statically typed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T03:00:26.077",
"Id": "229483",
"ParentId": "229452",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T09:30:49.413",
"Id": "229452",
"Score": "3",
"Tags": [
"python"
],
"Title": "A fractal picture - John Zells graphics.py"
}
|
229452
|
<p>I'm doing a code-challenge problem:</p>
<hr />
<h3>Input</h3>
<p>The first line consists of an integer <code>T</code> (T ≤ 100) which represents the number of test cases. Each test case consists of an integer <code>N</code> (5 ≤ N ≤ 100.000) which represents the number of integers, followed by a line that consists of <code>N</code> integers <code>Ai</code> (0 ≤ Ai ≤ 1000) separated by a space.</p>
<h3>Output</h3>
<p>For each test case, print in a line an integer that represents the sum of 5 largest numbers.</p>
<hr />
<p>My code (below) works for small tests, but on the online judge, it resulted in Time Limit Exceeded. Some approaches I've tried that I think speed up the program (need confirmation):</p>
<ol>
<li>Changing language from C++ to C (does it give significant boost?)</li>
<li>When calculating the sum, I use <code>while</code> instead of <code>for</code> loop (which one is more effective?)</li>
</ol>
<hr />
<pre><code>#include <stdio.h>
int main () {
int testCases;
scanf("%d", &testCases);
for (int i = 1; i <= testCases; i++) {
int size, sum, temp, k, limit;
sum = 0;
temp = 0;
scanf("%d", &size);
int array[size];
for (int i = 0; i < size; i++) {
scanf("%d", &array[i]);
}
for (int i = 0; i < size; i++) {
for (int j = i+1; j < size; j++) {
if (array[j] < array[i]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
} else {
continue;
}
}
}
k = size - 1;
limit = size - 6;
while (k > limit) {
sum += array[k];
k--;
}
printf("%d\n", sum);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T09:59:44.280",
"Id": "446539",
"Score": "0",
"body": "Interestingly, the code is neither a well-formed C++ program nor a well-formed C program because of the usage of VLAs (variable length arrays)."
}
] |
[
{
"body": "<p>We need only 5 maximum elements, for that we don't need to sort whole array. We can use alternative approach</p>\n\n<p><strong>Approach 1</strong>: Use 5 local variables and keep track of minimum element in it.</p>\n\n<p><strong>Approach 2</strong>: Use Min-heap and insert first 5 elements of array in min-heap, then iterate on array from index = 5, if heap-root is smaller than number in array then extract that number from min-heap, and insert new.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T10:00:53.867",
"Id": "446541",
"Score": "0",
"body": "Welcome to Code Review!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T10:22:26.243",
"Id": "229454",
"ParentId": "229453",
"Score": "5"
}
},
{
"body": "<ol>\n<li><p>NO: C++ is not magically slower than C. Bad C++ code is slower than good C code and vice versa.</p></li>\n<li><p>NO: For the compiler it is completely irrelevant whether you use a <code>for</code> or a <code>while</code> loop as they will all be normalized into a consistent representation anyway.</p></li>\n</ol>\n\n<p>Now to the actual review. Your code will not improve from porting to C as you are already not using any C++ features.</p>\n\n<p>In C++ you should generally use streams. They have a bad reputation but generally they greatly improve your code:</p>\n\n<pre><code>int numTests;\nstd::cin >> numTests;\n</code></pre>\n\n<p>This also works for ranges</p>\n\n<pre><code>std::vector<int> array(size);\n\nstd::istream_iterator<int> eos; // end-of-stream iterator\nstd::istream_iterator<int> iit (std::cin); // stdin iterator\nstd::copy(iit, eos, array.begin()); // copy from std::cin\n</code></pre>\n\n<p>For sorting you should refer to the standard library aka <code>std::sort</code>. However, you should not even sort but determine the 5 largest elements. This is achieved by the algorithm <code>nth_element</code></p>\n\n<pre><code>std::nth_element(array.begin(), std::next(array.begin(), 5), array.end(), std::greater<int>());\n</code></pre>\n\n<p>Now you can simply sum them up</p>\n\n<pre><code>const int result = std::accumulate(array.begin(), std::next(array.begin(), 5), 0);\n</code></pre>\n\n<p>So the whole algorithm would be</p>\n\n<pre><code>const int sum_largest(const std::size_t numElements, std::vector<int>& data) {\n if (numElements > data.size()) {\n // Error handling\n }\n std::nth_element(data.begin(), std::next(data.begin(), numElements), data.end(), std::greater<int>());\n return std::accumulate(data.begin(), std::next(data.begin(), numElements), 0);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T15:53:04.713",
"Id": "446458",
"Score": "0",
"body": "Oh, one other point - just as the question code should check the return value from `scanf()`, code using operator `>>` should check the consequent state of the stream before assuming that the read was successful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T17:31:02.803",
"Id": "446467",
"Score": "0",
"body": "@TobySpeight You are absolutely correct that input code should check the state. (Allthough for coding challenges one can work with the guaranteed input)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T10:00:05.313",
"Id": "446540",
"Score": "0",
"body": "Why return a `const int`? Here `const` hardly makes a difference as the return type of a function per [\\[expr.6\\]](https://timsong-cpp.github.io/cppwp/n4659/expr#6)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T12:31:32.713",
"Id": "446555",
"Score": "0",
"body": "@L.F. Because copy & paste is strong. That was a leftover from the line before."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T14:50:41.940",
"Id": "449373",
"Score": "0",
"body": "For getting 5 largest elements it is better to use `std::partial_sort` or `std::partial_sort_copy`. It is implemented via a different algorithm which is faster for small numbers like 5 (but slower for large numbers)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T12:20:13.130",
"Id": "229462",
"ParentId": "229453",
"Score": "4"
}
},
{
"body": "<p>There isn't going to be a significant difference between C and C++ when using the same algorithm.</p>\n\n<p>Using a <code>while</code> loop versus a <code>for</code> loop in this case will not have a significant difference either. The loop is only going to sum 5 values.</p>\n\n<p>The problem is the algorithm, as another answer pointed out do as much of the sorting as possible as the numbers are input. Don't input directly into the array, because that forces the sort, input into a variable and compare the variable against the the contents of the already sorted array, only replace the numbers in the array if the new number is larger.</p>\n\n<p>If the program was broken up into functions you could profile it to see where it was spending the most time, but it is obvious that the sort is the time sink. Breaking it up into function might help with writing the code and debugging as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T12:32:55.790",
"Id": "229463",
"ParentId": "229453",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229462",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T10:09:53.077",
"Id": "229453",
"Score": "1",
"Tags": [
"c++",
"beginner",
"c",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Sum the largest five numbers"
}
|
229453
|
<p>This is within a base class of a library, where several other classes inherit this one. </p>
<p>This seems like the simplest way of just getting some data, for now without timeout/errorhandling. This is supposed to get some data that will most ofthe time be converted to a small JSONObject.</p>
<p>Do you think I should put everything inside the <code>try</code> and use <code>val</code>? Any other suggestions? I'm basically just learning networking with android, only did it in C#.NET before.</p>
<pre><code>protected fun sendGetRequest(url: URL): String {
var urlConnection: HttpsURLConnection? = null
var reader: InputStreamReader? = null
var responseData = ""
try {
urlConnection = url.openConnection() as HttpsURLConnection
reader = InputStreamReader(urlConnection.inputStream)
responseData = reader.readText()
}catch (e: Exception){
this.messageHandler.handleMessage(e.message!!)
}finally {
reader?.close()
urlConnection?.disconnect()
}
return responseData
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T14:10:48.470",
"Id": "446334",
"Score": "1",
"body": "But you _are_ doing error handling. What does `this.messageHandler` do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T14:26:53.167",
"Id": "446340",
"Score": "0",
"body": "It propagates messages to the outside of the library. Right now the app using it just shows the message in a toast. With error handling I mean actually handling http codes and such."
}
] |
[
{
"body": "<p>The core of your code can be replaced by the following code:</p>\n\n<pre><code>url.openConnection() //you can cast to fail if it isn't https\n .getInputStream() //same as you\n .reader() // same as wrapping it in inputStreamReader\n .use { it -> // start lambda that handles the closing of the reader for you\n it.readText() // note, it's one parameter, so 'it ->' can be omitted\n }\n</code></pre>\n\n<p>The code above returns the text or throws the exception it got during execution, but always closes the reader, which in turn <a href=\"https://stackoverflow.com/questions/3956163/does-closing-the-inputstream-of-a-socket-also-close-the-socket-connection\">closes the connection</a>.</p>\n\n<p>The code above is almost the same as the code below btw:</p>\n\n<pre><code>url.readText()\n</code></pre>\n\n<p>If you want to remove all the variables, you should know that try catch can return a value:</p>\n\n<pre><code>val a = try{ 1 } catch(e: Exception) { 2 }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T12:03:20.870",
"Id": "446554",
"Score": "0",
"body": "So if I handle possible exceptions somewhere else, basically the whole thing I made is just `url.readText()`? That is quite simple. I'm glad I asked."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T14:00:12.097",
"Id": "446564",
"Score": "0",
"body": "yup. \n[In the documentation](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.net.-u-r-l/read-text.html), Kotlin tells you not to use it for *huge* files. The reason is because the text will be stored into a String, so into memory. This means it can almost always be ignored."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T14:06:55.767",
"Id": "446566",
"Score": "0",
"body": "In android you could theoretically store around [4 million characters](https://stackoverflow.com/a/15369204/3193776). Just a little bit more than the letters of the bible :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T14:08:58.983",
"Id": "446567",
"Score": "1",
"body": "Oh I expect a small json object most of the time, and an error page or nothing on error. Thanks for the help :D"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T10:19:07.840",
"Id": "229558",
"ParentId": "229455",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229558",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T10:29:58.770",
"Id": "229455",
"Score": "1",
"Tags": [
"android",
"kotlin",
"https"
],
"Title": "Simple function to Http GET some data"
}
|
229455
|
<p>Recently I asked the <a href="https://codereview.stackexchange.com/questions/229244/algorithm-that-spans-orthogonal-vectors-python">similar question</a>, but the algorithm was implemented in Python. Now I've tried to implement the same algorithm, but in C++ (I'm <em>very</em> new to it):</p>
<pre><code>#include<iostream>
#include<cstdlib>
#include<ctime>
#include<cmath>
#include <tgmath.h>
using namespace std;
const int MAXRANGE = 1000;
int randint(int low, int high){
return rand() % (high - low) + low;
}
void generate_vector(float vec[],int dimension){
for (int i = 0; i < dimension; i++){
vec[i] = randint(-MAXRANGE,MAXRANGE);
}
// We need to ensure that the last entry doesn't equal to zero
if (vec[dimension-1] == 0){
while (vec[dimension-1] == 0){
vec[dimension-1] = randint(-MAXRANGE,MAXRANGE);
}
}
}
void generate_orthogonal (float *vector, float orthogonal_vector[], int dimension){
float last_entry;
float dot_product = 0;
for (int i = 0; i < dimension -1; i++){
orthogonal_vector[i] = randint(-MAXRANGE,MAXRANGE);
}
for (int i = 0; i < dimension -1; i++){
dot_product = dot_product + (vector[i] * orthogonal_vector[i]);
}
last_entry = -(dot_product/vector[dimension-1]);
orthogonal_vector[dimension-1] = last_entry;
}
float dot_product(float *vector1, float vector2[],int dimension){
float sum = 0;
for (int i = 0; i < dimension; i++){
sum += (vector1[i])*(vector2[i]);
}
return sum;
}
void print_vector(float *A,int dim){
cout << "(";
for (int i = 0; i < dim; i++){
if (i == dim -1){
cout << A[i];
}
else{
cout << A[i] << ",";}
}
cout << ")^T" << endl;
}
int main(){
srand(time(0));
int dimension;
cout << "Choose dimension for the vector: ";
cin >> dimension;
float arbitrary_vector[dimension], orthogonal[dimension];
generate_vector(arbitrary_vector,dimension);
generate_orthogonal(arbitrary_vector,orthogonal,dimension);
cout << "First vector: ";
print_vector(arbitrary_vector,dimension);
cout << "Orthogonal vector: ";
print_vector(orthogonal,dimension);
cout << "Dot product of the vectors: ";
cout << dot_product(arbitrary_vector,orthogonal,dimension) << endl;
}
</code></pre>
<hr>
<p>What can be improved?</p>
<hr>
<p>As some people previously pointed out, the algorithm would throw exception if the last entry of the first vector was <span class="math-container">\$0\$</span>. I made an a slight change to ensure that <code>generate_vector</code> function won't generate vector where the last element is zero.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T11:26:53.547",
"Id": "446317",
"Score": "2",
"body": "Hi Nelver! Since you are very new to C++, I have added the beginner tag for you. As a beginner, this helps you get reviews that stick a bit closer to the basics and explain a bit more about the how and why. See [Why is the \\[beginner\\] tag appropriate here as opposed to e.g. Stack Overflow?](https://codereview.meta.stackexchange.com/q/9327)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T11:29:59.720",
"Id": "446318",
"Score": "0",
"body": "@L.F. Thank you!"
}
] |
[
{
"body": "<p>Welcome to C++.</p>\n\n<p>It seems that you are more or less trying to write C code rather than C++ though. Lets have a look at what you can improve:</p>\n\n<ol>\n<li><p>Never do <code>using namespace std;</code> It is a terrible practise that gets you into trouble really fast. <code>std::</code> is not that hard to type so get in the habit early.</p></li>\n<li><p>If you have compile time constants use them via <code>constexpr</code></p></li>\n<li><p>Your <code>dot_product</code> function is already implemented in the standard library. It is called <code>inner_product</code>. So the following code can be replaced</p>\n\n<blockquote>\n<pre><code>float dot_product(float *vector1, float vector2[],int dimension){\n float sum = 0;\n for (int i = 0; i < dimension; i++){\n sum += (vector1[i])*(vector2[i]);\n }\n return sum;\n}\n</code></pre>\n</blockquote>\n\n<p>by the following code</p>\n\n<pre><code>std::inner_product(a.cbegin(), a.cend(), b.cbegin(), float(0.0));\n</code></pre></li>\n<li><p>Similarly there is a <code>generate</code> function that fills a vector with a generator. Note that C++ has a variety of good random number generators (<code>rand()</code> is not one of them) in the <code><random></code> header. I don't know why you use integers for the float vectors but you can adapt that easily.</p>\n\n<p>EDIT: Incorporated problems found by @L.F.</p>\n\n<pre><code>#include <algorithm>\n#include <random>\n\nclass randomStreamUniformInt {\npublic:\n explicit randomStreamUniformInt(int lower_bound, int upper_bound)\n : mt(std::random_device{}()), uniform_dist(lower_bound, upper_bound) {}\n explicit randomStreamUniformInt(int lower_bound, int upper_bound, double seed)\n : mt(seed), uniform_dist(lower_bound, upper_bound) {}\n\n int operator() () { return uniform_dist(mt); }\nprivate:\n std::mt19937_64 mt;\n std::uniform_int_distribution<> uniform_dist;\n};\n\nstatic randomStreamUniformInt rng(-MAXRANGE, MAXRANGE); \n\nstd::vector<float> generate random(const std::size_t numElements) {\n std::vector<float> res(numElements);\n std::generate(res.begin(), res.end(), rng);\n return res;\n}\n</code></pre>\n\n<p>It would be even better to pass the random number generator as an argument rather than a global variable. I leave that as an exercise.</p></li>\n<li><p>You should use standard facilities for arrays such as <code>std::vector</code> or <code>std::array</code> depending on whether you know the size at compile time. So the following code:</p>\n\n<blockquote>\n<pre><code>float arbitrary_vector[dimension], orthogonal[dimension]\n</code></pre>\n</blockquote>\n\n<p>Should be better written as</p>\n\n<pre><code>std::vector<float> arbitrary_vector = generate_random(dimension);\n</code></pre>\n\n<p>Note that it is always better to put each declaration into a single line.</p></li>\n<li><p>Your method <code>generate_orthogonal</code> can be improved accordingly.</p>\n\n<pre><code>std::vector<float> generate_orthogonal(const std::vector<float>& a) {\n // get some random data\n std::vector<float> b = generate_random(a.size());\n\n // find the last non zero entry in a\n // We have to turn the reverse iterator into an iterator via std::prev(rit.base())\n auto IsZero = [] (const float f) -> bool { return f == float(0.0);};\n auto end = std::prev(std::find_if_not(a.crbegin(), a.crend(), IsZero).base());\n\n // determine the dot product up to end\n float dot_product = std::inner_product(a.cbegin(), end, b.cbegin(), float(0.0));\n\n // set the value of b so that the inner product is zero\n b[std::distance(a.cbegin(), end)] = - dot_product / (*end);\n\n return b;\n}\n</code></pre></li>\n</ol>\n\n<p>So put together it would look something like this:</p>\n\n<pre><code>#include <algorithm>\n#include <random>\n#include <vector>\n\nconstexpr int MAXRANGE = 1000;\n\nclass randomStreamUniformInt {\npublic:\n explicit randomStreamUniformInt(int lower_bound, int upper_bound)\n : mt(std::random_device{}()), uniform_dist(lower_bound, upper_bound) {}\n explicit randomStreamUniformInt(int lower_bound, int upper_bound, double seed)\n : mt(seed), uniform_dist(lower_bound, upper_bound) {}\n\n int operator() () { return uniform_dist(mt); }\nprivate:\n std::mt19937_64 mt;\n std::uniform_int_distribution<> uniform_dist;\n};\n\nstatic randomStreamUniformInt rng(-MAXRANGE, MAXRANGE); \n\nstd::vector<float> generate random(const std::size_t numElements) {\n std::vector<float> res(numElements);\n std::generate(res.begin(), res.end(), rng);\n return res;\n}\n\nstd::vector<float> generate_orthogonal(const std::vector<float>& a) {\n // get some random data\n std::vector<float> b = generate_random(a.size());\n\n // find the last non zero entry in a\n // We have to turn the reverse iterator into an iterator via std::prev(rit.base())\n auto IsZero = [] (const float f) -> bool { return f == float(0.0);};\n auto end = std::prev(std::find_if_not(a.crbegin(), a.crend(), IsZero).base());\n\n // determine the dot product up to end\n float dot_product = std::inner_product(a.cbegin(), end, b.cbegin(), float(0.0));\n\n // set the value of b so that the inner product is zero\n b[std::distance(a.cbegin(), end)] = - dot_product / (*end);\n\n return b;\n}\n\nint main() {\n std::size_t dimension = 20;\n\n std::vector<float> a = generate_random(dimension);\n std::vector<float> b = generate_orthogonal(a);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T12:12:07.580",
"Id": "446319",
"Score": "0",
"body": "Oops, didn't notice you already posted an answer because my Internet connection sucks. Sorry for the duplicate information!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T12:18:38.300",
"Id": "446320",
"Score": "0",
"body": "BTW, it appears that your `generate_random` function will generate the same numbers every time. Should `rng` be static?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T12:23:39.673",
"Id": "446321",
"Score": "0",
"body": "Argh yes, Normally it would be passed around sorry"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T19:50:26.493",
"Id": "446368",
"Score": "1",
"body": "maybe mention that builtins like \"inner_product\" are likely to use SSE2/optimized code, so one more reason not to roll your own."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T11:21:16.713",
"Id": "446424",
"Score": "0",
"body": "Also, `float(0.0)` is just `0.0f`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T14:54:47.073",
"Id": "446448",
"Score": "0",
"body": "A very minor nitpick, I try to keep people brand new to C++ away from reverse iterators because of how unintuitive their behaviour can be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T15:17:37.517",
"Id": "446453",
"Score": "0",
"body": "@L.F. that is correct. However, as it turns out the algorithm right now would also work for other types if one would templatize the function. using 0.0f would not"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T11:58:52.470",
"Id": "229460",
"ParentId": "229457",
"Score": "9"
}
},
{
"body": "<p>Welcome to C++! This code review focuses on writing idiomatic C++ code.</p>\n\n<blockquote>\n<pre><code>#include<iostream>\n#include<cstdlib>\n#include<ctime>\n#include<cmath>\n#include <tgmath.h>\n</code></pre>\n</blockquote>\n\n<p>Don't <code>#include <tgmath.h></code> because it is deprecated. It just includes <code>#include <complex></code> and <code>#include <cmath></code>. In this case, you do not use complex numbers, and you have <code>#include <cmath></code>.</p>\n\n<p>It is common practice to place a space after <code>#include</code> to improve readability. Also, sorting the <code>#include</code> directives makes them easier to navigate:</p>\n\n<pre><code>#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <iostream>\n</code></pre>\n\n<blockquote>\n<pre><code>using namespace std;\n</code></pre>\n</blockquote>\n\n<p>Well, no. <code>using namespace std;</code> is considered bad practice in C++ because it potentially introduces name clashes. See <a href=\"https://stackoverflow.com/q/1452721\">Why is <code>using namespace std;</code> considered bad practice?</a>.</p>\n\n<p>Instead, explicitly qualify the names with <code>std::</code>. This won't be a lot of effort once you get used to it, but it really helps to avoid subtle problems.</p>\n\n<blockquote>\n<pre><code>const int MAXRANGE = 1000;\n</code></pre>\n</blockquote>\n\n<p>Constants are indicated with <code>constexpr</code> in C++. In general, <code>constexpr</code> allows the constant to be used in more loci than <code>const</code> does.</p>\n\n<p>ALL CAPS names are usually reserved for macros. They are not commonly used for constants.</p>\n\n<blockquote>\n<pre><code>int randint(int low, int high){\n return rand() % (high - low) + low;\n\n }\n</code></pre>\n</blockquote>\n\n<p>The indentation is a bit irregular. There is usually a line break or space before the <code>{</code>.</p>\n\n<p><code>rand</code> is infamous for being a low-quality random number generator. Use <code><random></code> instead. See <a href=\"https://stackoverflow.com/q/53040940\">Why is the new random library better than <code>std::rand()</code>?</a>. Time is also not always considered a good seed. <code>std::random_device</code> is better. The function can be rewritten like this:</p>\n\n<pre><code>int randint(int low, int high)\n{\n static std::mt19937 engine{std::random_device{}()};\n\n assert(low <= high); \n std::uniform_int_distribution<int> dist{low, high};\n return dist(engine);\n}\n</code></pre>\n\n<p>Note that I used <code>assert</code> (defined in header <code><cassert></code>) to express the pre-condition.</p>\n\n<blockquote>\n<pre><code>void generate_vector(float vec[],int dimension){\n for (int i = 0; i < dimension; i++){\n vec[i] = randint(-MAXRANGE,MAXRANGE);\n }\n\n // We need to ensure that the last entry doesn't equal to zero\n\n if (vec[dimension-1] == 0){\n while (vec[dimension-1] == 0){\n vec[dimension-1] = randint(-MAXRANGE,MAXRANGE);\n\n }\n }\n\n\n}\n</code></pre>\n</blockquote>\n\n<p>Several problems:</p>\n\n<ul>\n<li><p>Containers from the standard library are generally preferred over raw C arrays. Use <code>std::vector</code> instead.</p></li>\n<li><p>You should really be generating <code>float</code> values instead of <code>int</code> values.</p></li>\n<li><p>Using out-parameters is less idiomatic than using the return value.</p></li>\n<li><p>Retrying is not a good strategy to ensure that the last entry is non-zero. Generating a number in <code>[-maxrange, 0)</code> and then having a 50% chance of negating the sign is probably better.</p></li>\n<li><p>You can use standard algorithms (available in header <code><algorithm></code>) to simplify the code.</p></li>\n</ul>\n\n<p>Here's how I would fix these problems (without using <code>randint</code>). I have added some comments to help you understand.</p>\n\n<pre><code>constexpr float maxrange = 1000.0f;\n\nstd::mt19937 engine{std::random_device{}()};\n\nstd::vector<float> generate_vector(int dimension)\n{\n assert(dimension > 0);\n\n // generate the first (n - 1) elements\n std::vector<float> result(dimension);\n std::uniform_real_distribution<float> dist{-maxrange, maxrange};\n std::generate(result.begin(), result.end() - 1, []{ return dist(engine); });\n\n // generate the last element\n dist.param({-maxrange, 0});\n result.back() = dist(engine);\n // negate the sign with a 50% possibility\n if (std::bernoulli_distribution bdist{0.5}; bdist(engine))\n result.back() = -result.back();\n\n // NRVO, no copying, no performance degradation\n return result;\n}\n</code></pre>\n\n<p>Also, <code>double</code> is generally used instead of <code>float</code> in C++ unless you have a good reason.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>void generate_orthogonal (float *vector, float orthogonal_vector[], int dimension){\n float last_entry;\n float dot_product = 0;\n for (int i = 0; i < dimension -1; i++){\n orthogonal_vector[i] = randint(-MAXRANGE,MAXRANGE);\n }\n for (int i = 0; i < dimension -1; i++){\n dot_product = dot_product + (vector[i] * orthogonal_vector[i]);\n }\n last_entry = -(dot_product/vector[dimension-1]);\n orthogonal_vector[dimension-1] = last_entry;\n}\n</code></pre>\n</blockquote>\n\n<p>Some problems, in addition to the aforementioned ones:</p>\n\n<ul>\n<li><p>Use <code>++i</code>, not <code>i++</code>, in the <code>for</code> statement. See <a href=\"https://stackoverflow.com/q/484462\">Difference between pre-increment and post-increment in a loop?</a>.</p></li>\n<li><p>You have the dot product function later, you can use it.</p></li>\n<li><p>The elements of <code>vector</code> should be <code>const</code>.</p></li>\n<li><p>The <code>last_entry</code> variable is not necessary; just assign the result of the calculation directly to <code>orthogonal_vector[dimension - 1]</code>. It should be obvious that we are referring to the last entry if <code>.back()</code> is used.</p></li>\n</ul>\n\n<p>Note that dot product is available in the standard library as <code>std::inner_product</code> (available in header <code><numeric></code>), so no need to roll out your own.</p>\n\n<pre><code>std::vector<float> generate_orthogonal(const std::vector<float>& vector)\n{\n // at least one dimension\n assert(!vector.empty());\n\n // same\n std::vector<float> result(dimension);\n std::uniform_real_distribution<float> dist{-maxrange, maxrange};\n std::generate(result.begin(), result.end() - 1, []{ return dist(engine); });\n\n // generate the last element\n auto dot_product = std::inner_product(vector.begin(), vector.end() - 1, result.begin());\n result.back() = -dot_product / vector.back();\n\n // same\n return result;\n}\n</code></pre>\n\n<blockquote>\n<pre><code>float dot_product(float *vector1, float vector2[],int dimension){\n float sum = 0;\n for (int i = 0; i < dimension; i++){\n sum += (vector1[i])*(vector2[i]);\n }\n return sum;\n}\n</code></pre>\n</blockquote>\n\n<p>As I said before, this function is available in the standard library as <code>std::inner_product</code>.</p>\n\n<blockquote>\n<pre><code>void print_vector(float *A,int dim){\n cout << \"(\";\n for (int i = 0; i < dim; i++){\n if (i == dim -1){\n cout << A[i];\n }\n else{\n cout << A[i] << \",\";}\n }\n cout << \")^T\" << endl;\n}\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://stackoverflow.com/q/213907\">Don't use <code>std::endl</code> without a reason.</a> Use <code>\\n</code> instead.</p>\n\n<p>You can simplify the code by printing the first element first:</p>\n\n<pre><code>void print_vector(const std::vector<float>& vector)\n{\n assert(!vector.empty());\n\n std::cout << '(' << vector[0];\n for (auto it = vector.begin() + 1; it != vector.end(); ++it) {\n std::cout << \", \" << *it;\n }\n std::cout << \")^T\\n\";\n}\n</code></pre>\n\n<hr>\n\n<p>You may noticed that <code>assert(!vector.empty())</code> appeared several times in the code. Maybe write a class for that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T12:24:46.267",
"Id": "446322",
"Score": "0",
"body": "Nice review, there is always benefit in a second set of eyes. Especially if it is a throrough as yours"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T07:17:27.617",
"Id": "446403",
"Score": "0",
"body": "Thanks a lot for mentioning `std::random_device` for seeding. I have some old code to update."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T15:08:20.893",
"Id": "446452",
"Score": "1",
"body": "The prefix/postfix page you link says specifically it does not matter which is used in the kinds of `for` loops in the OP."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T12:08:05.437",
"Id": "229461",
"ParentId": "229457",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "229461",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T10:57:39.253",
"Id": "229457",
"Score": "6",
"Tags": [
"c++",
"beginner",
"vectors"
],
"Title": "Algorithm that generates orthogonal vectors: C++ implementation"
}
|
229457
|
<p>What follows is a small but useful set of functions on transitive graphs and graphs that must be conformed to transitivity. Natural language is rich in transitive relationships expressed in a synthetic way, such as "they live in the same city", "they are friends". These two examples are binary transitive relations expressed succinctly.</p>
<p>The two propositions: "A, C, F and H live in the same city." and "W lives in the same city as X and Y.", although having substantially the same meaning, they cannot be unified as: "A, C, F, W, X, Y and H live in the same city." Their formulation as pairs of a transitive graph allows it, using the correct algorithm. The functions of this module perform this task.</p>
<pre><code>module TransitiveGraph
(checkGraphTransitivity
,addPairPreservingGraphTransitivity
,makeGraphTransitive
,unionOfTransitiveGraphsPreservingTransitivity
,fromGraphsToTransitiveGraph
,missingPairsToMakeTheGraphTransitive
) where
import Data.Set (Set)
import qualified Data.Set as S
import qualified Data.List as L
import Data.Map (Map)
import qualified Data.Map as M
import Data.Foldable as F (all,any)
type Pair a = (a,a)
type Graph a = Set (Pair a)
checkGraphTransitivity
:: Ord a => Graph a -> Bool
checkGraphTransitivity gr =
let (dom,cod) = S.foldr (\(a,b) (dom,cod) -> (S.insert a dom, S.insert b cod)) (S.empty,S.empty) gr
nonterminals = S.intersection dom cod
terminals = cod S.\\ nonterminals
mp_gr = S.foldr (\(k,v) -> M.insertWith S.union k (S.singleton v)) M.empty gr
in go mp_gr (S.toList dom) nonterminals terminals S.empty
where
go :: Ord a => Map a (Set a) -> [a] -> Set a -> Set a -> Set a -> Bool
go _ [] _ _ _ = True
go mp_gr (d:ds) nonterminals terminals antecs =
let antecs' = S.insert d antecs
image_d = mp_gr M.! d
preimage = (S.intersection nonterminals image_d) S.\\ terminals
image2 = S.foldr (\i_d acc -> S.union acc (mp_gr M.! i_d)) S.empty preimage
image2' = image2 S.\\ antecs'
antecs'' = S.union preimage antecs'
in F.all (`S.member` image_d) image2' && go mp_gr ds nonterminals terminals antecs
addPairPreservingGraphTransitivity
:: Ord a => Graph a -> Pair a -> Graph a
addPairPreservingGraphTransitivity gr c@(a,b)
| F.any ((== b) . fst) gr = S.insert c . S.union gr . S.map (\x -> (a,x)) . S.map snd . S.filter ((== b) . fst) $ gr
| otherwise = S.insert c gr
makeGraphTransitive
:: Ord a => Graph a -> Graph a
makeGraphTransitive gr = S.foldr (flip addPairPreservingGraphTransitivity) S.empty gr
-- Graphs transitivity of arguments is NOT checked
unionOfTransitiveGraphsPreservingTransitivity
:: Ord a => Graph a -> Graph a -> Graph a
unionOfTransitiveGraphsPreservingTransitivity gr1 gr2 = S.union (f gr1 gr2) (f gr2 gr1)
where
f g1 g2 = S.foldr (\c acc -> addPairPreservingGraphTransitivity acc c) g1 (g2 S.\\ g1)
fromGraphsToTransitiveGraph
:: Ord a => Graph a -> Graph a -> Graph a
fromGraphsToTransitiveGraph gr1 gr2 =
unionOfTransitiveGraphsPreservingTransitivity (makeGraphTransitive gr1) (makeGraphTransitive gr2)
missingPairsToMakeTheGraphTransitive
:: Ord a => Graph a -> Graph a
missingPairsToMakeTheGraphTransitive gr = makeGraphTransitive gr S.\\ gr
</code></pre>
<p><strong>EXAMPLES</strong></p>
<pre><code>gr1 = S.fromList [(1,3),(3,5),(5,2),(2,7),(1,5),(1,2),(5,7)]
gr2 = S.fromList [(1,7),(3,2),(3,7),(2,5)]
checkGraphTransitivity gr1 == False
makeGraphTransitive gr1 == S.fromList [(1,2),(1,3),(1,5),(1,7),(2,7),(3,2),(3,5),(3,7),(5,2),(5,7)]
missingPairsToMakeTheGraphTransitive gr1 == S.fromList [(1,7),(3,2),(3,7)]
unionOfTransitiveGraphsPreservingTransitivity gr1 gr2 == S.fromList [(1,2),(1,3),(1,5),(1,7),(2,2),(2,5),(2,7),(3,2),(3,5),(3,7),(5,2),(5,5),(5,7)]
------------------------------
livesInTheSameCity1 = S.fromList [('a','f'),('c','d'),('d','b')]
livesInTheSameCity2 = S.fromList [('e','f'),('c','g'),('d','b'),('g','a')]
makeGraphTransitive livesInTheSameCity1
fromList [('a','f'),('c','b'),('c','d'),('d','b')]
makeGraphTransitive livesInTheSameCity2
fromList [('c','a'),('c','g'),('d','b'),('e','f'),('g','a')]
fromGraphsToTransitiveGraph livesInTheSameCity1 livesInTheSameCity2
fromList [('a','f'),('c','a'),('c','b'),('c','d'),('c','f'),('c','g'),('d','b'),('e','f'),('g','a'),('g','f')]
</code></pre>
<hr>
<p><strong>The error detected by Franky is fixed:</strong></p>
<hr>
<pre><code>addPairPreservingGraphTransitivity
:: Ord a => Graph a -> Pair a -> Graph a
addPairPreservingGraphTransitivity gr p
| S.member p gr = gr
| otherwise = makeGraphTransitive $ S.insert p gr
-- ex. addPairPreservingGraphTransitivity (S.fromList [('a','b'), ('c','d')]) ('b','c')
-- > fromList [('a','b'),('a','c'),('a','d'),('b','c'),('b','d'),('c','d')]
type Domain a = Set a
makeGraphTransitive :: Ord a => Graph a -> Graph a
makeGraphTransitive gr = go (domain gr) gr
where
go :: Ord a => Domain a -> Graph a -> Graph a
go dom gr
| changed = go dom gr'
| otherwise = gr
where
(gr',changed) = go2 dom gr
go2 :: Ord a => Domain a -> Graph a -> (Graph a, Bool)
go2 dom gr = S.foldr (\d res@(acc, changed) ->
case go3 acc d of
Nothing -> res
Just acc' -> (acc',True)
) (gr,False) dom
go3 :: Ord a => Graph a -> a -> Maybe (Graph a)
go3 gr d
| S.isSubsetOf images2 image_d = Nothing
| otherwise = Just $ S.union gr $ S.map (\i -> (d,i)) images2
where
images2 = S.map snd preimages
preimages = S.filter ((`S.member` image_d) . fst) gr
image_d = elementImage gr d
-- ex. makeGraphTransitive $ S.fromList [('a','b'),('b','c'),('z','w'),('w','y'),('c','d'),('d','e'),('e','f')]
-- > fromList [('a','b'),('a','c'),('a','d'),('a','e'),('a','f'),('b','c'),('b','d'),('b','e'),('b','f'),('c','d'),('c','e'),('c','f'),('d','e'),('d','f'),('e','f'),('w','y'),('z','w'),('z','y')]
-- ex. makeGraphTransitive $ S.fromList [('b','a'),('c','b'),('z','w'),('w','y'),('d','c'),('e','d'),('f','e')]
-- > fromList [('b','a'),('c','a'),('c','b'),('d','a'),('d','b'),('d','c'),('e','a'),('e','b'),('e','c'),('e','d'),('f','a'),('f','b'),('f','c'),('f','d'),('f','e'),('w','y'),('z','w'),('z','y')]
domain :: Ord b1 => Set (b1, b2) -> Set b1
domain gr = S.map fst gr
elementImage :: (Ord a1, Eq a2) => Set (a2, a1) -> a2 -> Set a1
elementImage gr d = S.foldr (\(x,y) acc -> if x == d then S.insert y acc else acc) S.empty gr
</code></pre>
|
[] |
[
{
"body": "<p>There is some asymmetry in your code:</p>\n\n<pre><code>addPairPreservingGraphTransitivity gr c@(a,b)\n | F.any ((== b) . fst) gr = S.insert c . S.union gr . S.map (\\x -> (a,x)) . S.map snd . S.filter ((== b) . fst) $ gr\n</code></pre>\n\n<p>If there is <code>F.any ((== b) . fst) gr</code>, where is the opposite direction <code>F.any ((== a) . snd) gr</code>? And indeed, <code>makeGraphTransitive</code> does not work as I expect:</p>\n\n<pre><code>*TransitiveGraph> makeGraphTransitive (S.fromList [('c','b'), ('b','a')])\nfromList [('b','a'),('c','b')]\n</code></pre>\n\n<p>The easy example with <code>a</code> and <code>c</code> renamed works fine in <code>makeGraphTransitive (S.fromList [('a','b'), ('b','c')])</code>.</p>\n\n<p>I tried to fix it with</p>\n\n<pre><code>addPairPreservingGraphTransitivity gr c@(a,b)\n | F.any ((== b) . fst) gr || F.any ((== a) . snd) gr = S.insert c . S.union gr . S.union (S.map (\\x -> (x,b)) . S.map fst . S.filter ((== a) . snd) $ gr). S.map (\\x -> (a,x)) . S.map snd . S.filter ((== b) . fst) $ gr\n</code></pre>\n\n<p>but this still fails with this example, <code>('a','d')</code> is missing:</p>\n\n<pre><code>*TransitiveGraph> addPairPreservingGraphTransitivity (S.fromList [('a','b'), ('c','d')]) ('b','c')\nfromList [('a','b'),('a','c'),('b','c'),('b','d'),('c','d')]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T18:15:09.800",
"Id": "229655",
"ParentId": "229459",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T11:42:43.050",
"Id": "229459",
"Score": "3",
"Tags": [
"haskell",
"graph"
],
"Title": "Transitive graph"
}
|
229459
|
<h3>Motivation</h3>
<p>I came across an interesting question on SO: <a href="https://stackoverflow.com/questions/12667415/determine-if-string-has-all-unique-characters">determine-if-string-has-all-unique-characters</a> and thought about providing an extension method to enable duplicate removal given some kind of normalization. </p>
<h3>Description</h3>
<blockquote>
<p>The goals:</p>
<ul>
<li>Remove any duplicate characters (keep the first occurence) and return the updated string.</li>
<li>The method should be able to handle <em>diacritics</em> and <em>extended unicode</em> characters. </li>
<li>The method should allow the consumer to control normalization to find duplicates (for instance, case-sensitivity).</li>
</ul>
</blockquote>
<h3>Questions</h3>
<ul>
<li>Looking for general feedback on C# conventions</li>
<li>Performance feedback</li>
<li>Am I reinventing the wheel?</li>
</ul>
<h3>Code</h3>
<pre><code>public static class StringExtension
{
public static string RemoveDuplicateChars(
this string text, Func<string, string> normalizer = null)
{
var output = new StringBuilder();
var entropy = new HashSet<string>();
var iterator = StringInfo.GetTextElementEnumerator(text);
if (normalizer == null)
{
normalizer = x => x.Normalize();
}
while (iterator.MoveNext())
{
var character = iterator.GetTextElement();
if (entropy.Add(normalizer(character)))
{
output.Append(character);
}
}
return output.ToString();
}
}
</code></pre>
<h3>Unit Tests</h3>
<p>Let's test a string that contains variations on the letter <code>A</code>, including the Angstrom sign <code>Å</code>. The Angstrom sign has unicode codepoint <code>u212B</code>, but can also be constructed as the letter <code>A</code> with the diacritic <code>u030A</code>. Both represent the same character.</p>
<pre><code>[TestClass]
public class Fixtures
{
[TestMethod]
public void Fixture()
{
// ÅÅAaA -> ÅAa
Assert.AreEqual("ÅAa", "\u212BA\u030AAaA"
.RemoveDuplicateChars());
// ÅÅAaA -> ÅA
// Note that the ToLowerInvariant is used to normalize characters
// when searching for duplicates, it does not mean the output gets
// transformed to lower case.
Assert.AreEqual("ÅA", "\u212BA\u030AAaA"
.RemoveDuplicateChars(x => x.Normalize().ToLowerInvariant()));
}
}
</code></pre>
|
[] |
[
{
"body": "<p>There are not much to say other than the usual missing argument null check:</p>\n\n<p>It is valid to write the following:</p>\n\n<pre><code> string test = null;\n test.RemoveDuplicateChars();\n</code></pre>\n\n<p>and <code>RemoveDuplicateChars</code> will be called with a <code>null</code> for the <code>this</code> argument <code>text</code>. Therefore you'll have to test for <code>null</code>:</p>\n\n<pre><code>public static string RemoveDuplicateChars(\n this string text, Func<string, string> normalizer = null)\n{\n if (text == null)\n return text;\n\n ...\n</code></pre>\n\n<p>or throw an exception...</p>\n\n<hr>\n\n<p>The default initialization of <code>normalizer</code> could be a little less verbose:</p>\n\n<pre><code> normalizer = normalizer ?? ((x) => x.Normalize());\n</code></pre>\n\n<hr>\n\n<p>A minor detail: Angstrom and Å: is also represented by <code>\\u00C5</code>, which your code interprets as equal to Angstrom, but MS Word interprets them as different when using its Find-function?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T15:13:13.963",
"Id": "446577",
"Score": "1",
"body": "Your last point is in particular interesting. Both \\u00C5 and \\u212B are the Angstrom symbol. The lambda that you rewrote in a more compact way handles _normalisation_. This means that both these characters represent the same glyph. So normalized, they are exactly the same: https://docs.microsoft.com/en-us/dotnet/api/system.string.normalize?view=netframework-4.8. I bet MS Word does not normalize, or normalizes using a different algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T15:27:17.063",
"Id": "446581",
"Score": "1",
"body": "@dfhwze: My point about Angstrom was just to communicate the difference because I observed it - not to tell what is most correct - and I don't think that Word is the most realiable witness of truth :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T15:30:09.273",
"Id": "446582",
"Score": "1",
"body": "That's the thing, it's hard to tell what is correct, because it depends on the rules to which equivalence is checked. That's why I found your last paragraph spot on. Finding duplicates in Unicode characters is context-bound, maybe even subjective to some point."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T14:32:07.297",
"Id": "229568",
"ParentId": "229464",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229568",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T12:58:01.020",
"Id": "229464",
"Score": "3",
"Tags": [
"c#",
"algorithm",
"strings",
"extension-methods"
],
"Title": "Removing duplicate Unicode characters"
}
|
229464
|
<p>I'm relatively new to OOP with JS and want to find out:</p>
<ol>
<li>If my code can be improved somehow, and</li>
<li><strong><em>key question</em></strong> Identify how and where I can typically use OOP more in my job (as I can usually just use arrays and don't need objects)</li>
</ol>
<p>I have built a basic demo that just stores some animal data as objects and displays them when clicking on the boxes.</p>
<p>Can anyone briefly review the code and spot any improvements? And more importantly, what are typical tasks that objects are better for rather than just using arrays? I'm a front-end developer and typically use arrays for tasks like storing html data and changing content with click events, hovers and other event listeners, and have never had to use objects although want to.</p>
<p>Thanks for any advice here. My code and CodePen URL are below:</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>let animals = document.querySelectorAll('.animal'),
animalsObj = [],
mainTitle = document.querySelector('#title'),
mainDescription = document.querySelector('#desc');
class Animal {
// constructor
constructor (name, description) {
this.name = name;
this.description = description;
animalsObj.push(this);
}
}
for (let i = 0; i < animals.length; i++) {
let name = animals[i].querySelector('.name').textContent,
description = animals[i].querySelector('.description').textContent;
// instantiate object
new Animal(name, description);
animals[i].addEventListener("click", () => {
console.log('clicked on ' + animalsObj[i].name);
mainTitle.textContent = animalsObj[i].name;
mainDescription.textContent = animalsObj[i].description;
});
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.animals {
display: flex;
}
.animal {
border: 1px dashed grey;
padding: 1em;
}
.animal:nth-of-type(odd) { background: #f0f0f0 }
.animal:nth-of-type(even) { background: #ccc }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='container'>
<div class='animals'>
<div class='animal'>
<h2 class='name'>Lion</h2>
<p class='description'>A big cat.</p>
</div>
<div class='animal'>
<h2 class='name'>Stoat</h2>
<p class='description'>A weasel thing.</p>
</div>
<div class='animal'>
<h2 class='name'>Chicken</h2>
<p class='description'>Good to eat.</p>
</div>
</div>
<div class='output-area'>
<h2 id='title'>Animal</h2>
<p id='desc'>Description</p>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>Codepen: <a href="https://codepen.io/ns91/pen/qBWLYLp" rel="nofollow noreferrer">https://codepen.io/ns91/pen/qBWLYLp</a></p>
|
[] |
[
{
"body": "<h2>OO-Design</h2>\n\n<blockquote>\n <p><em>key question Identify how and where I can typically use OOP more in my job (as I can usually just use arrays and don't need objects</em></p>\n</blockquote>\n\n<p>In your transformation towards OOP, you're still in the habit of resorting to arrays.\nYou let each new instance of this class be registered in some global array.</p>\n\n<blockquote>\n<pre><code>class Animal {\n constructor (name, description) {\n this.name = name;\n this.description = description;\n animalsObj.push(this);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Don't do this as it pollutes your object-oriented design.</p>\n\n<pre><code>class Animal {\n constructor (name, description) {\n this.name = name;\n this.description = description;\n }\n}\n</code></pre>\n\n<p>If you wish to store these instances in the array, let the consumer code handle it. This way, you can decide by use case how instances of objects should be handled.</p>\n\n<pre><code>const animals = [];\nconst animal = new Animal(\"Roger\", \"my pet\");\nanimals.push(animal);\n</code></pre>\n\n<p>This would also keep you from instantiating an object without storing the instance in a variable, because the magic no longer happens behind the screens.</p>\n\n<blockquote>\n<pre><code>new Animal(name, description); // no longer registers to a global array\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T18:09:45.820",
"Id": "446470",
"Score": "1",
"body": "Very helpful, thank you. Will I always need to typically use arrays with objects? Because it’s somewhere to store the data. What are the typical things a front end developer can do using OOP, and without arrays?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T17:51:33.087",
"Id": "229473",
"ParentId": "229472",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229473",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T17:35:50.387",
"Id": "229472",
"Score": "2",
"Tags": [
"javascript",
"beginner",
"object-oriented"
],
"Title": "Simple JS OOP - Clicking the box to fetch and display object content"
}
|
229472
|
<p>Here is a shortest possible syntax for replacing whitespaces with <code>null</code> and throwing an exception where it is not allowed:</p>
<pre><code>public class Name
{
string _first;
public string First
{
get => _first;
set => _first = (Optional)value;
}
string _middle;
public string Middle
{
get => _middle;
set => _middle = (Required)value;
}
}
</code></pre>
<p>Where:</p>
<pre><code>public class Optional
{
public static explicit operator Optional(string text) => new Optional(text);
public static implicit operator string(Optional optional) => optional.Text;
Optional(string text) => Text = IsNullOrWhiteSpace(text) ? null : text;
string Text { get; }
}
</code></pre>
<p>And:</p>
<pre><code>public class Required
{
public static explicit operator Required(string text) => new Required((Optional)text);
public static implicit operator string(Required required) => required.Text;
Required(string text) => Text = text ?? throw new FormatException();
string Text { get; }
}
</code></pre>
<p>P.S. Value modification on property assignment is not recommended, but could be very handy sometimes :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T19:47:38.740",
"Id": "446504",
"Score": "3",
"body": "I hope you won't take this the wrong way, but the whole \"reasoning\" part doesn't bring anything to the post and should be removed. If you want to explain your reasoning, try to stick to the point, StackExchange isn't a blog."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T19:54:20.197",
"Id": "446509",
"Score": "2",
"body": "I wanted to edit my comment but can't : Explaining your reasoning is fine (great, even), but there's just too much \"political\" fluff around it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T12:50:07.153",
"Id": "446557",
"Score": "1",
"body": "This question is [being discussed in meta](https://codereview.meta.stackexchange.com/questions/9348/what-to-do-with-a-post-that-feels-like-a-blog-entry)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T10:29:40.883",
"Id": "446971",
"Score": "1",
"body": "The \"Question\" area is for the question, not for responding to answers."
}
] |
[
{
"body": "<p><em>Edit: the tone of this might seem a bit negative, so I'll add that this was a fun one to review in hopes of lightening the mood ;)</em></p>\n\n<p>Miscellaneous thoughts:</p>\n\n<ul>\n<li><p>This is horrifying! Why did you do this?!</p></li>\n<li><p>You can just about get away with this for properties, but for method calls with required/optional fields, a <code>FormatException</code> will be inadequate (an <code>ArgumentException</code> telling the caller which argument went wrong is important), which rather limits the scope of this technique.</p></li>\n<li><p>Because the thing is type specific, you could give it a sensible name (e.g. <code>OptionalString</code>), make both conversions implicit, and use it as the field type. This would required even less syntax, and would be somewhat less opaque to the maintainer who has to live with this.</p></li>\n<li><p>These need documentation: it's not obvious that an <code>Optional</code> should convert <code>\"\"</code> to <code>null</code>: this is enough to put me off it completely.</p></li>\n<li><p>You can get this 'low-char-count syntax by using a <code>static using</code> and providing these as static methods to a static class. The advantages would include:</p>\n\n<ul>\n<li>It's not horrifying</li>\n<li>It requires less code, because you don't have to build a whole type and its conversions for each sort of string</li>\n<li>You can't misuse the types in ways you didn't intend, and they don't appear everywhere</li>\n<li>You can throw the static methods at a delegate if you have need</li>\n<li>It's not horrifying</li>\n<li>People who don't hate themselves can use the fully qualified name</li>\n<li>It won't incur an allocation every time you assign a value (though using <code>struct</code>s would address this already)</li>\n<li>You have greater freedom with the type of checks you can perform (e.g. multiple parameters)</li>\n<li>It will be easier to document, because the API will be single method, not a type+stuff</li>\n<li>It's not horrifying</li>\n</ul></li>\n<li><p>It's good that the conversion to the types is an explicit one, as this limits the scope for things going wrong with the intended usage.</p></li>\n<li>It would be nice if the <code>Text</code> members were explicitly <code>private</code>, so there was no question as to your intentions.</li>\n<li>I personally do not like the expression-bodied syntax for constructors, but that's probably just me.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T22:42:31.997",
"Id": "446376",
"Score": "2",
"body": "Throwing in a regular constructor is totally valid -- this is how you signal that you cannot create a valid instance using given constructor parameters. Violation of CA1065 is throwing in a *static* constructor only."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T22:49:14.380",
"Id": "446377",
"Score": "0",
"body": "@Bronx wow, thanks for calling that out. I spent some time wondering how to phrase that bit because I couldn't think of a good reason other than to make the tooling happen, so I'm glad to remove it ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T00:34:49.277",
"Id": "446382",
"Score": "0",
"body": "@VisualMelon please see the reasoning update above :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T08:33:25.923",
"Id": "446414",
"Score": "0",
"body": "@DmitryNogin I hope this answer didn't come across too seriously ;) It's an interesting idea, but I don't buy the argument that we keep things simple and predictable for the sake of inexperienced programmers: we keep them simple and predictable for the sake of tired and hungry programmers who don't want to spent 20 seconds understanding these conversion classes (and forget what they were actually trying to debug) when everyone natively speaks the language of functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T08:36:23.880",
"Id": "446415",
"Score": "0",
"body": "@DmitryNogin I completely agree that `Optional` and `Required` can be types in their own right, but then should be exposed in the public API, rather than used for conversions which are hidden inside properties. I'm not sure what the bit about not mentioning C# experience is about... but I guess I'll be unemployable then ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T15:10:09.743",
"Id": "447012",
"Score": "0",
"body": "\"This is horrifying! Why did you do this?!\" Should that really be a bulletpoint by itself? You're not expanding on why you think *'this'* is horrifying. Is it the code, the approach or that OP went for the shortest possible syntax instead of a more readable one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T15:31:21.117",
"Id": "447017",
"Score": "0",
"body": "@Mast it's an attempt a humour; if you think it's out of place, I'll be happy to remove it (or if you want to edit yourself, that's fine by me too)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T21:22:36.353",
"Id": "229478",
"ParentId": "229477",
"Score": "8"
}
},
{
"body": "<p>Not sure that adding a 7-line validator class per validation rule (plus typecasting abuse) is any shorter/better than a set of more straightforward composable validating one-liners, something like:</p>\n\n<pre><code>public static class ValidatingTransformers\n{\n public static T ThrowsIfNull<T>(this T s, string msg = \"\") =>\n s != null ? s : throw new ArgumentException(msg);\n public static string ThrowsIfEmpty(this string s, string msg = \"\") =>\n !string.IsNullOrWhiteSpace(s) ? s : throw new ArgumentException(msg);\n\n public static string EmptyIfNull(this string s) => s ?? \"\";\n public static string NullIfEmpty(this string s) => !string.IsNullOrWhiteSpace(s) ? s : null;\n\n ... et cetera\n}\n\n</code></pre>\n\n<p>Some other thoughts:</p>\n\n<ol>\n<li>Replacing empty/whitespace strings with <code>null</code> does not look like a great idea to me. Because, well, the <code>null</code> and the <code>NullReferenceException</code>. An empty string looks like a safer alternative.</li>\n<li>I'd avoid property setters and mutating a state, even if setters protect invariants. Much simpler, shorter, and safer alternative:</li>\n</ol>\n\n<pre><code>public class Name\n{\n public string First { get; }\n public string Middle { get; }\n public string Last { get; }\n\n public Name(string first, string middle, string last)\n {\n First = first.NullIfEmpty();\n Middle = middle.ThrowsIfNull(\"middle name must not be null\");\n Last = last.ThrowsIfEmpty(\"last name must not be empty\");\n }\n}\n</code></pre>\n\n<p>Shorter code, one single place for all validations, never ever get an object in an inconsistent state, no issues with concurrent mutations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T03:55:40.313",
"Id": "446384",
"Score": "0",
"body": "+1, yes - I used extension methods before. The problem is - invoking a method on the null reference makes my feeling scream a way more than a type cast. Would it still be a typecasting abuse for you if relevant model names be used, like `(Text)str` or `(TextOrNull)str` for the same purposes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T03:59:10.547",
"Id": "446385",
"Score": "0",
"body": "Type cast exception will look reasonable then for `(Text)` as no white spaces are allowed for the type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T04:21:48.157",
"Id": "446387",
"Score": "1",
"body": "Typecasting like _first = (Optional)value;` suggests that `_first` has a type of `Optional`, otherwise why would anyone do the cast? It is not obvious that the only reason for the cast is validation via some intermediate type. But even if we accept this semantic, it still needs a lot of boilerplate code comparing to static functions."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T03:46:48.967",
"Id": "229485",
"ParentId": "229477",
"Score": "9"
}
},
{
"body": "<h2>Usability</h2>\n\n<p>I would have expected <code>Optional</code> to transform <code>null</code> and whitespace only content into <code>String.Empty</code>, not the around way around.</p>\n\n<pre><code> Optional(string text) => Text = IsNullOrWhiteSpace(text) ? string.Empty : text;\n</code></pre>\n\n<p>And <code>Required</code> to throw on <code>null</code> or whitespace only content.</p>\n\n<pre><code> Required(string text) => Text = !IsNullOrWhiteSpace(text) ? text : throw new FormatException();\n</code></pre>\n\n<p>This way, the pattern focuses on actual string content, rather than on a technical <em>null</em> vs <em>empty</em> debate.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T04:34:02.670",
"Id": "229486",
"ParentId": "229477",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "229486",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T20:10:42.317",
"Id": "229477",
"Score": "2",
"Tags": [
"c#",
"strings",
"null"
],
"Title": "String whitespaces"
}
|
229477
|
<p>My code finds the maximum subarray sum and the starting and ending index of that subarray.</p>
<pre><code>int Max(int a,int b){return (a>b)?a:b;}
int Max(int a,int b,int c){return Max(Max(a,b),c);}
int MaxAcrossSubArray(int arr[],int l,int m,int r,int &Start,int &End)
{
Start=m;//initialize start index
int sum=arr[m];
int sum_l=arr[m];
for(int i=m-1;i>=l;--i)//include mid(---------|)
{
sum+=arr[i];
if(sum>sum_l)
{
Start=i;
sum_l=sum;
}
}
End=m+1;//initialize end index
sum=arr[m+1];
int sum_r=arr[m+1];
for(int i=m+2;i<=r;++i)//include mid(|-----------------)
{
sum+=arr[i];
if(sum>sum_r){
End=i;
sum_r=sum;
}
}
return sum_l+sum_r;//(-----------|---------------------)
}
int MaxSubArray(int arr[],int l,int r,int &Start,int &End)
{
if(l==r)
{
Start=l;
End=r;
return arr[l];
}
else
{
int mid=(l+r)/2;
int sA=-1,eA=-1,sB=-1,eB=-1,sC=-1,eC=-1;
int a=MaxSubArray(arr,l,mid,sA,eA);
int b=MaxSubArray(arr,mid+1,r,sB,eB);
int c=MaxAcrossSubArray(arr,l,mid,r,sC,eC);
int Maximum=Max(a,b,c);
if(Maximum==a)
{
Start=sA;
End=eA;
return a;
}
else if(Maximum==b)
{
Start=sB;
End=eB;
return b;
}
else
{
Start=sC;
End=eC;
return c;
}
}
}
}
int main()
{
int arr[9]={-2, 1, -3, 4, -1, 2, 1, -5, 4};
int Start=-1;
int End=-1;
cout<<MaxSubArray(arr,0,8,Start,End)<<"\n";
cout<<Start<<"\n";
cout<<End<<"\n";
for(int i=Start;i<=End;++i)
{
cout<<arr[i]<<"\t";
}
cout<<"\n";
return 0;
}
</code></pre>
<p>Is there any way to optimize this? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T09:25:02.250",
"Id": "446419",
"Score": "2",
"body": "Welcome to Code Review! You'll receive better reviews if you show a complete program. You seem to be missing some `#include` lines - if you [edit] to add them, we'll have a complete program that we could compile and run."
}
] |
[
{
"body": "<p>Welcome to Code Review!</p>\n\n<h1>Algorithm</h1>\n\n<p>Since you specifically asked how to optimize the code, I'll put this part first. You are using a divide-and-conquer algorithm. This algorithm is <span class=\"math-container\">\\$\\operatorname{\\Theta}(n \\log n)\\$</span>. There's a better <span class=\"math-container\">\\$\\Theta(n)\\$</span> algorithm which works like this: go through the array, from index <code>i = [0, n)</code>. Keep track of two variables:</p>\n\n<ul>\n<li><p><code>max_sum</code>: maximum subarray sum so far.</p></li>\n<li><p><code>max_end_sum</code>: maximum subarray sum ending at index <code>i</code>.</p></li>\n</ul>\n\n<p>Initially, both can be considered to be \"negative infinity\". At each element, these variables can be updated in constant time with the following formulas:</p>\n\n<pre><code>new_max_sum = max{max_sum, array[i], max_end_sum + array[i]}\nnew_max_end_sum = max{array[i], max_end_sum + array[i]}\n</code></pre>\n\n<h1>Readability</h1>\n\n<p>Code is read more than written. Here are some tips to improve readability:</p>\n\n<ul>\n<li><p>Always put a space after a comma and around binary operators. Instead of</p>\n\n<pre><code>int c=MaxAcrossSubArray(arr,l,mid,r,sC,eC);\n</code></pre>\n\n<p>Use</p>\n\n<pre><code>int c = MaxAcrossSubArray(arr, l, mid, r, sC, eC);\n</code></pre></li>\n<li><p>Always put the opening and closing braces of a function body on separate lines. Instead of</p>\n\n<pre><code>int Max(int a,int b){return (a>b)?a:b;}\n</code></pre>\n\n<p>Use</p>\n\n<pre><code>int Max(int a, int b)\n{\n return (a > b) ? a : b;\n}\n</code></pre></li>\n<li><p>Put a space after control keywords like <code>for</code> or <code>if</code>. This helps visually distinguish them from functions and operators (<code>sizeof</code>, <code>typeid</code>, etc.).</p></li>\n<li><p>Be consistent with indentation. Bad example:</p>\n\n<pre><code>if(Maximum==a)\n{\n Start=sA;\n End=eA;\n return a;\n}\n\nelse if(Maximum==b)\n {\n Start=sB;\n End=eB;\n return b;\n }\n</code></pre></li>\n</ul>\n\n<h1>The standard library facilities</h1>\n\n<p>The function <code>Max</code> is already available in the standard library as <code>std::max</code>. For example:</p>\n\n<pre><code>std::max(42, 420) == 420\nstd::max({42, 420, 4200}) == 4200\n</code></pre>\n\n<p>(You may noticed that you need to use braces if the number of arguments is not exactly two.)</p>\n\n<p>The following loop:</p>\n\n<pre><code>for(int i=Start;i<=End;++i)\n{\n\n cout<<arr[i]<<\"\\t\";\n}\n</code></pre>\n\n<p>can be replaced by a call to <code>std::copy</code> with <code>std::ostream_iterator</code>.</p>\n\n<p>In C++, raw C arrays are not recommended. You are advised to use standard library containers like <code>std::array</code> instead. Indexes should be of type <code>std::size_t</code> or <code>std::ptrdiff_t</code> instead of <code>int</code>.</p>\n\n<p>Here's how the code may look like in modern C++, with iterators and tuples: (just a rough idea, not particularly optimized)</p>\n\n<pre><code>template <\n typename ForwardIt,\n typename Value,\n typename BinaryOp = std::plus<>,\n typename Compare = std::less<>\n >\nstd::tuple<ForwardIt, ForwardIt, Value>\nmaximum_subarray(ForwardIt first, ForwardIt last, Value init,\n BinaryOp combine = {}, Compare compare = {})\n{\n auto max_sum = std::make_tuple(first, first, init);\n auto max_end_sum = std::make_tuple(first, init);\n\n for (; first != last; ++first) {\n auto& [it, value] = max_end_sum;\n value = combine(value, *first);\n if (compare(value, *first)) {\n it = first;\n value = *first;\n }\n if (compare(std::get<2>(max_sum), value)) {\n max_sum = {it, std::next(first), value};\n }\n }\n\n return max_sum;\n}\n\ntemplate <typename ForwardIt>\nauto maximum_subarray(ForwardIt first, ForwardIt last)\n{\n using Value = typename std::iterator_traits<ForwardIt>::value_type;\n return maximum_subarray(first, last, Value());\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T10:48:10.177",
"Id": "229501",
"ParentId": "229481",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T01:20:45.573",
"Id": "229481",
"Score": "4",
"Tags": [
"c++",
"performance",
"algorithm",
"array",
"divide-and-conquer"
],
"Title": "Maximum sub-array sum"
}
|
229481
|
<p><strong>Would my code be considered fairly optimal and efficient? If not, where can I look to improve the code?</strong> The program works just fine.</p>
<p><strong>Would this method scale well if the dictionary containing the number of bank account increases?</strong></p>
<p><strong>Design</strong>: I have designed and kept only one object in <code>main()</code>. i.e. <code>bank_1</code>, contains a dictionary of information regarding multiple bank accounts. I have elected to only create the object <code>bank_account</code> in<code>open_bank_account()</code> and <code>check_bank_blanance()</code> when needed and these objects disappear once the function is done.</p>
<p><strong>Intention</strong>: The intention here is to use as few objects as possible in <code>main()</code>.</p>
<p><strong>Output</strong>: The program runs just fine; just enter <code>1</code>, then enter <code>2</code>, then enter <code>777</code> followed by <code>777</code>. It will print the bank account balance of $1.00 of the account id <code>777</code>.</p>
<pre><code>class Bank_Account:
def __init__(self, account_id, account_pin, account_balance):
self._account_id = account_id
self._account_pin = account_pin
self._account_balance = account_balance
self._individual_bank_account_dicitionary = {}
self._individual_bank_account_dicitionary[account_id] = {"Pin": account_pin, "Balance": account_balance}
def get_bank_account_balance(self, account_id):
return "Balance: ${:.2f}".format(self._individual_bank_account_dicitionary[account_id]["Balance"])
def __str__(self):
return "{}".format(self._individual_bank_account_dicitionary)
class Bank:
def __init__(self, bank_name):
self._bank_name = bank_name
self._bank_dicitionary = {}
def update_bank_dictionary(self, bank_account):
self._bank_dicitionary[bank_account._account_id] = {"Pin": bank_account._account_pin, "Balance": bank_account._account_balance}
# 1. A method to return the dictionary of bank accounts of the object from class Bank.
# 2. In this case, only bank_1 from main() is the object argument.
def get_bank_dictionary(self):
return self._bank_dicitionary
# 1. Method to create object bank_account only when needed.
def get_bank_account(self, account_id):
account_pin = self._bank_dicitionary[account_id]["Pin"]
account_balance = self._bank_dicitionary[account_id]["Balance"]
bank_account = Bank_Account(account_id, account_pin, account_balance)
return bank_account
# 1. This is used to convert the dictionary into a string for printing purposes.
def string_bank_dictionary(self):
string_list = ["account ID: {} \naccount Pin: {} \nBank Balance: {} \n".format(key, self._bank_dicitionary[key]["Pin"], self._bank_dicitionary[key]["Balance"])\
for key, value in self._bank_dicitionary.items()]
return "\n".join(string_list)
def __str__(self):
return "{}".format(self.string_bank_dictionary())
def open_bank_account(bank):
# # Uncomment out when running actual program.
# account_id = input("Enter account id here: ")
# account_pin = input("Enter account pin here: ")
# account_balance = input("Enter account initial balance here: ")
# Comment out when running actual program.
# Currently in used for testing purposes.
account_id = 455
account_pin = 123
account_balance = 888
bank_account = Bank_Account(account_id, account_pin, account_balance)
bank.update_bank_dictionary(bank_account)
# Comment out when running actual program.
# Currently in used for testing purposes.
account_id = 777
account_pin = 777
account_balance = 1
bank_account = Bank_Account(account_id, account_pin, account_balance)
bank.update_bank_dictionary(bank_account)
# Comment out when running actual program.
# Currently in used for testing purposes.
account_id = 631
account_pin = 222
account_balance = 50
bank_account = Bank_Account(account_id, account_pin, account_balance)
bank.update_bank_dictionary(bank_account)
return bank
def check_bank_blanance(bank):
valid_id_password = False
temporary_dictionary = bank.get_bank_dictionary()
while True:
account_id = int(input("Enter account id here: "))
account_pin = int(input("Enter account pin here: "))
for key in temporary_dictionary.keys():
if account_id == key and temporary_dictionary[account_id]["Pin"] == account_pin:
valid_id_password = True
bank_account = bank.get_bank_account(account_id)
print(bank_account.get_bank_account_balance(account_id))
break
if valid_id_password == True:
break
else:
print("Invalid account id/password. Please try again.")
def main():
bank_1 = Bank("ABC Bank")
while True:
print("Menu \n1. Open bank account \n2. Check balance")
while True:
account_choice = int(input("Enter option here: "))
if account_choice <= 0 and account_choice >= 7:
account_choice = int(input("Enter option here: "))
else:
break
if account_choice == 6:
break
elif account_choice == 1:
bank_1 = open_bank_account(bank_1)
elif account_choice == 2:
balance = check_bank_blanance(bank_1)
main()
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>Would this method scale well if the dictionary containing the number of bank account increases?</p>\n</blockquote>\n\n<p>Yes, I think so - dictionary access is fast, O(1) or \"constant time\".</p>\n\n<h2>Typo</h2>\n\n<p><code>check_bank_blanance</code> should be <code>check_bank_balance</code>, or more likely <code>check_balance</code>.</p>\n\n<p><code>_individual_bank_account_dicitionary</code> should be <code>_individual_bank_account_dictionary</code>. That said - why does this dict exist at all? From what I see it only contains attributes that should be class members.</p>\n\n<h2>Method names</h2>\n\n<p>Just call <code>get_bank_account_balance</code> <code>get_balance</code> - or, if you make it a <code>@property</code>, simply <code>balance</code>.</p>\n\n<h2>str</h2>\n\n<pre><code>return \"{}\".format(self._individual_bank_account_dicitionary)\n</code></pre>\n\n<p>should just be</p>\n\n<pre><code>return str(self._individual_bank_account_dictionary)\n</code></pre>\n\n<h2>Class names</h2>\n\n<p><code>Bank_Account</code> should just be named <code>BankAccount</code>.</p>\n\n<h2>Data exposure</h2>\n\n<p>The method <code>get_bank_dictionary</code> probably shouldn't exist. You're exposing data that should be dealt with by the class itself. This code:</p>\n\n<pre><code> for key in temporary_dictionary.keys():\n if account_id == key and temporary_dictionary[account_id][\"Pin\"] == account_pin:\n</code></pre>\n\n<p>should exist in the <code>Bank</code> class, perhaps as <code>get_account()</code>. Also, don't loop through the dict to find a key - just do a dict lookup using <code>[]</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T16:08:45.297",
"Id": "229521",
"ParentId": "229488",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T05:31:42.830",
"Id": "229488",
"Score": "5",
"Tags": [
"python",
"performance",
"python-3.x",
"object-oriented",
"memory-optimization"
],
"Title": "Bank account balance program"
}
|
229488
|
<p>I tend to include something like the following in small and medium-sized Python projects, either at the top of the executable or as <code>logger.py</code>:</p>
<pre><code>import logging
import sys
logger = logging.getLogger(__name__)
stoh = logging.StreamHandler(sys.stderr)
fmth = logging.Formatter("[%(levelname)s] %(asctime)s %(message)s")
stoh.setFormatter(fmth)
logger.addHandler(stoh)
logger.setLevel(logging.DEBUG)
</code></pre>
<p>Then import <code>logger</code> from <code>logger</code> (as needed), and proceed to make calls throughout the project like <code>logger.level('message')</code>.</p>
<p>Are there any obvious (or non-obvious) red flags or anti-patterns with this approach?</p>
|
[] |
[
{
"body": "<h2>Setting up logging</h2>\n\n<p>You might be interested in <a href=\"https://docs.python.org/3/library/logging.html#logging.basicConfig\" rel=\"nofollow noreferrer\"><code>logging.basicConfig</code></a>, which can setup everything you setup there as well. It's not sufficient if you want for example both a file and a stream logger, but for a small, static configuration like this it's perfectly suitable. Your code up there becomes a simple:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>logging.basicConfig(format=\"[%(levelname)s] %(asctime)s %(message)s\", level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n</code></pre>\n\n<p>And you're done. (<a href=\"https://docs.python.org/3/library/logging.handlers.html#logging.StreamHandler\" rel=\"nofollow noreferrer\">The default stream is <code>sys.stderr</code></a>.)</p>\n\n<p>Do note that in no way, shape or form is the long form wrong - it's easier extendable, for one. However, for a quick script it might be easier to use basicConfig.</p>\n\n<h3>Module-level logging</h3>\n\n<p>I'd recommend you use a different logger for every different file, and have all of them be named the way you did that one. However, if you then also include the <code>%(name)</code> parameter in your format string, your logging messages will each contain the filename of the file they're logging from. This will help in debugging if you don't know exactly where the problems come from. I personally also include <code>%(lineno)</code> for the line number. Personally, I always use the <code>.format</code> method for my logging strings, which makes it look like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>logging.basicConfig(format=\"{levelname: <8}:{asctime}:{name: <30}:{lineno: <4}:{message}\", level=logging.DEBUG, style=\"{\")\n# Or with % formatting:\nlogging.basicConfig(format=\"%(levelname)-8s:%(asctime)s:%(name)-30s:%(lineno)-4s:%(message)s\", level=logging.DEBUG)\n</code></pre>\n\n<p>Which tells me exactly where a logging statement was made as well. You won't have to search for your own exact wording anymore when you resume debugging your code for that one weird issue 3 months from now. You can just grab filename and linenumber and you're at the right location.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T14:58:58.443",
"Id": "446449",
"Score": "1",
"body": "Left fill with %-formatting is `%-Ns`, where N is a number. E.g. `{: <8}` => `%-8s`, `{levelname: <8}` => `%(levelname)-8s`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T15:03:32.830",
"Id": "446451",
"Score": "0",
"body": "`logging` prints to stderr by default, no?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T15:40:50.203",
"Id": "446455",
"Score": "0",
"body": "Thanks, improved the answer with the left-fill. I....actually couldn't find in the docs where it'd log by default, but if it leaves it up to the StreamHandler, that one defaults to `sys.stderr`. Since it's not that important a part of the answer, I just removed the sentence."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T16:08:36.903",
"Id": "446460",
"Score": "0",
"body": "Thanks! I'm submitting an edit to further improve it. I looked myself and saw in the documentation for `basicConfig` it says it sets up a `StreamHandler`, and `StreamHandler` defaults to `sys.stderr`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T06:47:16.837",
"Id": "446525",
"Score": "0",
"body": "Ah, that's ok. I didn't know and didn't want to bet it didn't set a different stream when init-ed through basicConfig."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T07:00:58.367",
"Id": "229492",
"ParentId": "229490",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "229492",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T06:36:00.103",
"Id": "229490",
"Score": "8",
"Tags": [
"python",
"logging"
],
"Title": "Minimal Python logging"
}
|
229490
|
<p>Code below reads static variables from <code>ProductConfiguration</code> class. Functions <code>setAccess</code> and <code>setMarketAccess</code> in two classes <code>ProductInitialization</code> and <code>ProductMarketInitialization</code> reads variables from <code>ProductConfiguration</code>. Can this reading be done in a better way? I still want to have file <code>ProductConfiguration</code> to hold public variables. Was just wondering if there is a better way of reading this variables in the other two classes, may be there in future there will be additional classes that will read variables from <code>ProductConfiguration</code></p>
<pre><code>public class ProductConfiguration{
public static final PRODUCT_ACCESS=//this value is read from properties file
public static final MARKET_PRODUCT_ACCESS=//this value is read from properties file
}
public class ProductInitialization{
public Product setAccess(Product p){
if(p.brand == "LOCAL") {
p.access=ProductConfiguration.PRODUCT_ACCESS;
return p;
}
p.access = "DEFAULT";
return p;
}
}
public class ProductMarketInitialization{
public void setMarketAccess(Product p){
if(p.type == "MARKET"){
p.access=
ProductConfiguration.MARKET_PRODUCT_ACCESS;
return p;
}
p.access ="MARKET_DEFAULT";
return p;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T07:55:37.887",
"Id": "446411",
"Score": "7",
"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) for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T09:54:34.203",
"Id": "446422",
"Score": "0",
"body": "This isn't related to your question exactly but you might want to change how you are comparing the strings. Strings should always be compare using equals(), so your code would be .brand.equals(\"LOCAL\"). == compares the exact value. This works for primitives, but Strings are objects. And variables containing objects dont' really containg objects, but a reference to the object. You will learn more about this in the future, but for now if you want it to work you have use equals()."
}
] |
[
{
"body": "<p>I cannot imagine the code being that reduced; you probably removed extraneous code.\nThe code shown should be clearer as:</p>\n\n<pre><code>public class ProductInitialization {\n public void setAccess(Product p){\n p.access = p.brand.equals(\"LOCAL\") ? ProductConfiguration.PRODUCT_ACCESS\n : \"DEFAULT\";\n }\n}\n\npublic class ProductMarketInitialization {\n public void setMarketAccess(Product p){\n p.access = p.type.equals(\"MARKET\") ? ProductConfiguration.MARKET_PRODUCT_ACCESS\n : \"MARKET_DEFAULT\";\n }\n}\n</code></pre>\n\n<p>The <code>ProductConfiguration</code> is taken from a properties file. This <code>PropertiesResourceBundle</code> is principally partly lazy. A <code>ListResourceBundle</code> would be totally immediate, as this is a java class containing arrays. If on the other hand you would like the startup as smoothly as possible, a totally lazy loading would need <strong>getters</strong> for the <code>ProductConfiguration</code>.</p>\n\n<p>This seems still not very important, so be it.</p>\n\n<p>The special cases of a brand <code>LOCAL</code> and type <code>MARKET</code>, and finally a special result <code>DEFAULT</code> and <code>MARKET_DEFAULT</code> hinting at yet another case handling are more cumbersome.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Old New\n\nLOCAL ${productConf.productAccess}\nother Optional.empty()\n\nMARKET ${productConf.marketProductAccess}\nother Optional.empty()\n</code></pre>\n\n<p>So making the access field an <code>Optional<...></code>, maybe even an optional getter.</p>\n\n<p>Having two initialisation classes seems <strong>overdesigned</strong>, especially as they create two distinct categories of the same <code>Product</code>.</p>\n\n<p>In general it seems too early to pay too much attention to <em>adding extra code</em> for nicety's sake.</p>\n\n<pre><code> public void configAccessForDefault(Product p){\n p.access = p.brand.equals(\"LOCAL\") ? ProductConfiguration.PRODUCT_ACCESS\n : \"DEFAULT\";\n }\n\n public void configAccessForMarket(Product p){\n p.access = p.type.equals(\"MARKET\") ? ProductConfiguration.MARKET_PRODUCT_ACCESS\n : \"MARKET_DEFAULT\";\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T08:55:43.553",
"Id": "229498",
"ParentId": "229496",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T07:49:20.300",
"Id": "229496",
"Score": "0",
"Tags": [
"java"
],
"Title": "How to make below code more readable and efficient?"
}
|
229496
|
<blockquote>
<p>I have a class <code>LoanAccount</code> that contains an attributes <code>creationDate</code> and <code>loanAmount</code>. </p>
<p>I want to implement a Comparator that sorts the accounts by loan amount in descending order.
When the loan amounts are the same, sorts the accounts
ascending by date.</p>
</blockquote>
<p>The code look like this:</p>
<p><strong>Class</strong></p>
<pre><code>public class LoanAccount {
private String id;
private Date creationDate;
private BigDecimal loanAmount;
}
</code></pre>
<p><strong>Comparator</strong></p>
<pre><code>public class LoanAccountAmountComparator implements Comparator<LoanAccount> {
@Override
public int compare(LoanAccount o1, LoanAccount o2) {
if (o1 == null) {
if (o2 == null) {
return 0;
}
return -1;
}
if (o2 == null) {
return 1;
}
if (o1.getLoanAmount() == null) {
if (o2.getLoanAmount() == null) {
return 0;
}
return -1;
}
if (o2.getLoanAmount() == null) {
return 1;
}
int comparedLoanAmount = o2.getLoanAmount().compareTo(o1.getLoanAmount());
if (comparedLoanAmount == 0) {
if (o1.getCreationDate() == null) {
if (o2.getCreationDate() == null) {
return 0;
}
return -1;
}
if (o2.getCreationDate() == null) {
return 1;
}
return o1.getCreationDate().compareTo(o2.getCreationDate());
} else {
return comparedLoanAmount;
}
}
}
</code></pre>
<p>Objects <code>o1</code>, <code>o2</code> can be null. Fields <code>creationDate</code> and <code>loanAmount</code> can be null.</p>
<p>I want to ask you if there are better ways to handle null pointer exception in compareTo method.</p>
<p>For me it looks like there are too many if conditions </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T09:02:08.957",
"Id": "446418",
"Score": "2",
"body": "@dfhwze I've posted the real class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T09:29:04.667",
"Id": "446420",
"Score": "3",
"body": "some useful comparison strategies in Java: https://www.baeldung.com/java-8-comparator-comparing and https://stackoverflow.com/a/20093589/11523568"
}
] |
[
{
"body": "<p>it is possible to handle null pointer exception using <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#comparing-java.util.function.Function-\" rel=\"nofollow noreferrer\">Comparator.comparing</a> static method. If you want to comparing <code>loanAmount</code> fields in your objects and you want that every not null value is greater than <code>null</code> you can use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#nullsFirst-java.util.Comparator-\" rel=\"nofollow noreferrer\">Comparator.nullFirst</a> method in combination with <code>Comparator.comparing</code> like the below code:</p>\n<pre><code>Comparator.comparing(LoanAccount::getLoanAmount,\n Comparator.nullsFirst(Comparator.naturalOrder()))\n</code></pre>\n<p><code>NaturalOrder</code> is a method returning a comparator that compares Comparable objects in natural order.\nYou can also combine more comparators in a chain with method <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#thenComparing-java.util.Comparator-\" rel=\"nofollow noreferrer\">Comparator.thenComparing</a> like the code below:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Comparator\n .comparing(LoanAccount::getLoanAmount,\n Comparator.nullsFirst(Comparator.naturalOrder()))\n .thenComparing(LoanAccount::getCreationDate, \n Comparator.nullsFirst(Comparator.naturalOrder()))\n .compare(o1, o2);\n</code></pre>\n<p>Now you can rewrite your comparator with equal behaviour shortly:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class LoanAccountAmountComparator\n implements Comparator<LoanAccount> {\n\n @Override\n public int compare(LoanAccount o1, LoanAccount o2) {\n if (o1 == null && o2 == null) return 0;\n if (o1 == null) return -1;\n if (o2 == null) return 1;\n return Comparator\n .comparing(LoanAccount::getLoanAmount,\n nullsFirst(naturalOrder()))\n .thenComparing(LoanAccount::getCreationDate,\n nullsFirst(naturalOrder()))\n .compare(o1, o2);\n }\n}\n</code></pre>\n<p>Note: the use of class <code>Date</code> is discouraged, it is better if you use instead the <code>java.time</code> package classes for time related code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T18:09:32.880",
"Id": "446469",
"Score": "2",
"body": "Two more things... First you could pass the inner comparator itself to `Comparator.nullsFirst()`, which would make that comparator handle `null` automatically (thus avoiding the three if at the beginning). Second, that whole thing become your comparator, so you don't need the LoanAccountAmountComparator class at all. Simply move the comparator construction to some other place (for example, the LoadAccount class), and store it into a public static field (lets say `ACCOUNT_BY_AMOUNT_AND_DATE_COMPARATOR`)..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T20:27:11.963",
"Id": "446515",
"Score": "0",
"body": "@jwatkins You are right."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T17:49:00.637",
"Id": "229530",
"ParentId": "229497",
"Score": "8"
}
},
{
"body": "<p>Here is another twist, roughly similar to dariosicily's proposal.</p>\n\n<p>It differs in the following points:</p>\n\n<ul>\n<li>It create the aggregated comparator only once, then store it in a static field. Why? Because functions such as <code>Comparator.nullsFirst()</code> and <code>Comparator.comparing()</code> implies object allocation, which you definitely want to avoid if your comparator is called from tight loops (for example, a sort or tree insertion algorithm).</li>\n<li>Null checks on the LoadAccount objects themselves have also been delegated to <code>Comparator.nullsFirst()</code>. That means that absolutely no <code>if</code> statement is required!</li>\n<li>I moved that comparator to a public, static field of a utility class. I have learned from personal experience that comparators on domain model objects very often come in \"families\". In different places, you want different sorting strategies, for the same objects. Here, for demonstration, I also included one comparator for <code>loadAmount</code> (that is, without fallback on tie), and another one for <code>creationDate</code>. But you can see how this idea can be generalized.</li>\n<li>In this sample, I have adopted an uncommon indentation strategy. I think this is justified in this case because it helps make it easier to see which fields are sorted by each comparator, and in which order. This is of great importance when you have comparators that involve a significant number of fields.</li>\n</ul>\n\n<pre><code> public class LoanAccountAmountComparators {\n\n /**\n * A comparator that sort LoanAccounts, by load's amount, in decreasing order.\n */\n public static final Comparator<LoanAccount> BY_AMOUNT = \n Comparator.nullsFirst(\n Comparator.comparing(\n LoanAccount::getLoanAmount, Comparator.nullsFirst(Comparator.reverseOrder())\n );\n );\n\n /**\n * A comparator that sort LoanAccounts, by creation date, in ascending order.\n */\n public static final Comparator<LoanAccount> BY_DATE = \n Comparator.nullsFirst(\n Comparator.comparing(\n LoanAccount::getCreationDate, Comparator.nullsFirst(Comparator.naturalOrder())\n );\n );\n\n /**\n * A comparator that sort LoanAccounts, by creation amount (in descending order),\n * then by date (in ascending order).\n */\n public static final Comparator<LoanAccount> BY_AMOUNT_AND_DATE = \n Comparator.nullsFirst(\n Comparator.comparing(\n LoanAccount::getLoanAmount, Comparator.nullsFirst(Comparator.reverseOrder())\n ).thenComparing(\n LoanAccount::getCreationDate, Comparator.nullsFirst(Comparator.naturalOrder())\n );\n );\n }\n</code></pre>\n\n<p>It should be noted that, in this example, all fields involved are indeed some kind of objects. If, however, your comparator would involve fields containing primitive types, then you should use the corresponding <code>Comparator.comparing<primitiveType></code> function (that is, never let some primitive be boxed to object only so it can be compared to <code>Comparator.naturalOrder()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T18:33:15.573",
"Id": "229531",
"ParentId": "229497",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "229530",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T08:29:45.743",
"Id": "229497",
"Score": "6",
"Tags": [
"java",
"null",
"cyclomatic-complexity"
],
"Title": "handle null in Comparator class"
}
|
229497
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.