text
stringlengths
1
2.12k
source
dict
c#, reinventing-the-wheel, reflection RandomAccumulator Please use consistent naming for your properties (NumberToCreate, useRatio, etc.) Set properties' default value on the auto-generated propreties rather than inside a dedicated ctor Set the default value only if it differs from the runtime default public class RandomAccumulator { public int NumberToCreate { get; set; } public bool UseRatio { get; set; } = true; public bool IsKerman { get; set; } public float FtMRatio { get; set; } public float MinStupid { get; set; } public float MaxStupid { get; set; } public float MinBrave { get; set; } public float MaxBrave { get; set; } public int MinNumberOfBadasses { get; set; } public int MaxNumberOfTourists { get; set; } public int Pilots { get; set; } public int Engineers { get; set; } public int Scientists { get; set; } public RandomAccumulator Reset() => new(); }
{ "domain": "codereview.stackexchange", "id": 44079, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, reinventing-the-wheel, reflection", "url": null }
python, numpy, playing-cards Title: Poker hand valuator in Python Question: As you will probably notice very quickly from the code below, I'm not very experienced coder. Below is my attempt at valuating poker hands in Python. The code below may not be pretty but it seems to be doing the job. And it seems to be quick enough to evaluate ranges on flop and turn. The output allows for easy comparison of hands (on my to do list next). Please kindly review my code and let me know if there are any obvious ways to make it quicker and easier to read? Any hints will be highly appreciated. import numpy, random #Poker hand is ordered in form of a "punchcard". Rows are colors. #Order in a row is from 2 to A #Card array [[2s,3s,4s,5s,6s,7s,8s,9s,Ts,Js,Qs,Ks,As], # [2h,3h,4h,5h,6h,7h,8h,9h,Th,Jh,Qh,Kh,Ah], # [2c,3c,4c,5c,6c,7c,8c,9c,Tc,Jc,Qc,Kc,Ac], # [2d,3d,4d,5d,6d,7d,8d,9d,Td,Jd,Qd,Kd,Ad]] #Deck for testing deck = ["2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s", "Ts", "Js", "Qs", "Ks", "As", "2h", "3h", "4h", "5h", "6h", "7h", "8h", "9h", "Th", "Jh", "Qh", "Kh", "Ah", "2c", "3c", "4c", "5c", "6c", "7c", "8c", "9c", "Tc", "Jc", "Qc", "Kc", "Ac", "2d", "3d", "4d", "5d", "6d", "7d", "8d", "9d", "Td", "Jd", "Qd", "Kd", "Ad", ] #Function generating 1000 7 card hands to test def thousandHands(deck): allTheHands = [] for i in range(1000): random.shuffle(deck) allTheHands.append(deck[:7]) return allTheHands #Hand Encoder takes a list of strings and translates it to a matrix def HandEncoder(card_list): poker_hand = [ [ 0 for i in range(13) ] for j in range(4) ]
{ "domain": "codereview.stackexchange", "id": 44080, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, playing-cards", "url": null }
python, numpy, playing-cards card_dict = { "2s": [[0],[0]], "2h": [[1],[0]], "2c": [[2],[0]], "2d": [[3],[0]], "3s": [[0],[1]], "3h": [[1],[1]], "3c": [[2],[1]], "3d": [[3],[1]], "4s": [[0],[2]], "4h": [[1],[2]], "4c": [[2],[2]], "4d": [[3],[2]], "5s": [[0],[3]], "5h": [[1],[3]], "5c": [[2],[3]], "5d": [[3],[3]], "6s": [[0],[4]], "6h": [[1],[4]], "6c": [[2],[4]], "6d": [[3],[4]], "7s": [[0],[5]], "7h": [[1],[5]], "7c": [[2],[5]], "7d": [[3],[5]], "8s": [[0],[6]], "8h": [[1],[6]], "8c": [[2],[6]], "8d": [[3],[6]], "9s": [[0],[7]], "9h": [[1],[7]], "9c": [[2],[7]], "9d": [[3],[7]], "Ts": [[0],[8]], "Th": [[1],[8]], "Tc": [[2],[8]], "Td": [[3],[8]], "Js": [[0],[9]], "Jh": [[1],[9]], "Jc": [[2],[9]], "Jd": [[3],[9]], "Qs": [[0],[10]],"Qh": [[1],[10]],"Qc": [[2],[10]],"Qd": [[3],[10]], "Ks": [[0],[11]],"Kh": [[1],[11]],"Kc": [[2],[11]],"Kd": [[3],[11]], "As": [[0],[12]],"Ah": [[1],[12]],"Ac": [[2],[12]],"Ad": [[3],[12]], } for card in card_list: i = card_dict.get(card)[0].pop() j = card_dict.get(card)[1].pop() poker_hand[i][j] = 1 return poker_hand #Hand valuation function def ValuePokerHand(PokerHand): handArray = numpy.array(PokerHand) #list of sums of cards with given face value face_values = numpy.sum(handArray, axis=0) #function to check for consecutive five cards in a range def checkForStraight(inputArray): result = [False, 0] for card_i in range(13, 4, -1): if numpy.all(inputArray[card_i-5:card_i]): result = [True, card_i-1] break elif numpy.all(inputArray[0:4]) and inputArray[12] >= 1: result = [True, 3] return result
{ "domain": "codereview.stackexchange", "id": 44080, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, playing-cards", "url": null }
python, numpy, playing-cards #Step 1 - check for Straight flush and if present return the index of highest card for color in handArray: if checkForStraight(color)[0]: result = ["Straight Flush"] + [checkForStraight(color)[1]] return result #Step 2 - check for quads and return index of quads and index of kicker if numpy.amax(face_values) == 4: quad_index = numpy.argmax(face_values) kicker_index = 0 for kicker in range(12, 0, -1): if 4 > face_values[kicker] > 0: kicker_index = kicker break return ["Quads", quad_index, kicker_index] #Step 3 - check for full house and return indexex of trips and pair if numpy.sort(face_values)[12] == 3 and numpy.sort(face_values)[11] >=2: trips_index = 0 pair_index = 0 for trips in range (12, 0, -1): if face_values[trips] == 3: trips_index = trips break for pair in range (12, 0, -1): if pair != trips_index: if face_values[pair] >=2: pair_index = pair break return ["Full House", trips_index, pair_index] #Step 4 - check for Flush and return index of the highest card in sequence for color in handArray: if numpy.sum(color) >= 5: result = ["Flush"] for card in range (12, -1, -1): if color[card] > 0: result.append(card) return result[:6] #Step 5 - Check for Straight and return the index of highest card in sequence if checkForStraight(face_values)[0]: return ["Straight"] + [checkForStraight(face_values)[1]]
{ "domain": "codereview.stackexchange", "id": 44080, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, playing-cards", "url": null }
python, numpy, playing-cards #Step 6 - Check for trips and return indices of trips and two highest kickers if numpy.sort(face_values)[12] == 3: trips_index = numpy.argmax(face_values) first_kicker = 0 second_kicker = 0 for card_i in range(12, 0, -1): if 3 > face_values[card_i] > 0: first_kicker = card_i break for card_j in range(first_kicker - 1, 0, -1): if 3 > face_values[card_j] > 0: second_kicker = card_j break return ["Trips", trips_index, first_kicker, second_kicker] #Step 7 - Check for 2 pairs and return indices of both pairs and a kicker if numpy.sort(face_values)[12] == 2 and numpy.sort(face_values)[11] >=2: first_pair = 0 second_pair = 0 kicker = 0 for pair1 in range (12, 0, -1): if face_values[pair1] == 2: first_pair = pair1 break for pair2 in range (12, 0, -1): if pair2 != first_pair: if face_values[pair2] ==2: second_pair = pair2 break for card in range (12, 0, -1): if card != first_pair and card != second_pair: if face_values[card] > 0: kicker = card return ["Two Pairs", first_pair, second_pair, kicker] #Step 8 - Check for pair and retuns indices of a pair and 3 highest kickers if numpy.sort(face_values)[12] == 2: pair_index = 0 kickers = [] for card in range (12, 0, -1): if face_values[card] == 2: pair_index = card break for kicker in range (12, 0, -1): if face_values[kicker] > 0 and kicker != pair_index: kickers.append(kicker) kicker1, kicker2, kicker3 = kickers[0:3] return ["Pair", pair_index, kicker1, kicker2, kicker3]
{ "domain": "codereview.stackexchange", "id": 44080, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, playing-cards", "url": null }
python, numpy, playing-cards #Step 9 - High Card, returns list of indices of top 5 cards res = ["High Card"] for card in range(12, -1,- 1): if face_values[card] > 0: res.append(card) return res[:6] handsList = thousandHands(deck) #function comparing list of hands and returning the highest one def compareHands(listOfHands): pass for hand in handsList: print(hand, ValuePokerHand(HandEncoder(hand)))
{ "domain": "codereview.stackexchange", "id": 44080, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, playing-cards", "url": null }
python, numpy, playing-cards Answer: Here are a few comments about your code: Bug Your code works mostly fine, but fails to identify an ace-low straigh (A 2 3 4 5). Testing To test your code, you try to run it with 1000 random hands. While this may be useful to check if your code runs at all and behaves mostly as expected, it is not a good enough approach, as illustrated by the bug I pointed out. The odds of a random hand having this specific straight is quite low, and identifying visually it in a 1000-line printout is next to impossible. You should define specific and reproducible test-cases, trying to cover all cases. Using a testing framework like unittest is also highly recommended. Code layout Given the functionality provided by your code, I assume it's intended for use as part of a bigger program, perhaps a poker simulating game, or a training application. It should also be able to be used by your test runner. In both case, you should lay out your code like a module, allowing to import HandValuator in another file. This implies removing all statements outside of the scope of functions, or putting them behind a if __name__ == '__main__ guard, and removing functions that wouldn't be useful outside of your module (such as thousandHands) or hiding them by prefixing their name with an underscore (_). Try to figure out what API you want to expose. If I were to reuse your code, I would probably want to simply call ValuePokerHand(hand), not ValuePokerHand(HandEncoder(hand))), and as such HandEncoder should probably called from inside ValuePokerHand and "hidden" from the caller. Style As noted in another answer, you should follow style conventions recommended by PEP-8, including naming conventions, imports on separate lines, white space usage... This would make your code more consistent for everyone (including your future self) familiar with Python, and as such easier to work with and review. Documentation and comments
{ "domain": "codereview.stackexchange", "id": 44080, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, playing-cards", "url": null }
python, numpy, playing-cards Documentation and comments You document your functions and module using comments, which is better than nothing, but these would better be docstrings and be included after the functions' signatures (or at the beginning of the module). Otherwise, your use of comments is pretty good. Naming Functions and method are better described by a verb than a noun. As such, ValuePokerHand would be better named evaluate_poker_hand, or HandEncoder as encode_hand Logic If find your logic hard to follow, for example I can't wrap my head around your use of an array of flags for the full deck, as encoded by the HandEncoder. I feel like the logic could be simplified by working with arrays of cards. Use appropriate types/classes You mention that "The output allows for easy comparison of hands". I disagree, what you have are arrays of mixed strings and ints of varying length, and comparing them isn't going to be trivial. If no builtin type is a good match for your data, classes are a useful thing to implement, and will make working with them much easier down the line. Another option would be to evaluate hands to a numerical value, which will be trivially compared down the line.
{ "domain": "codereview.stackexchange", "id": 44080, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, playing-cards", "url": null }
python Title: Automate the Boring Stuff Chapter 12 - Link Verification Question: The project outline: Write a program that, given the URL of a web page, will attempt to download every linked page on the page. The program should flag any pages that have a 404 “Not Found” status code and print them out as broken links. My solution: # Usage: python link_verification.py "webpage to search" import sys, requests, bs4 def link_validator(links): for link in links: page = link.get("href") if str(page).startswith("https://"): url = link.get("href") res = requests.get(url) try: res.raise_for_status() print(f"Page found: {page}") except Exception as exc: print(f"There was a problem with {page}:\n{exc}") def main(): while True: url = sys.argv[1] # Enter a website to search res = requests.get(url) try: res.raise_for_status() except Exception as exc: print(f"There was a problem: {exc}") continue soup = bs4.BeautifulSoup(res.text, "html.parser") links = soup.select("a") link_validator(links) print("Search complete") break if __name__ == '__main__': main() Answer: So far, I think your code looks really good. It's clear and easy to read, you are using library code to reduce boilerplate (r.raise_for_status), and you have an if __name__ guard. Nice work! A few things I'd consider: while True: break You don't need the loop in your main function, since it only goes through a single iteration unless there's a problem with the URL. In that case, I'd probably just raise rather than continue. sys args It's usually more conventional to unpack sys args in the if __name__ block and pass them as arguments to main. This way there isn't a weird side effect if you want to use this function in another module: def main(url): res = requests.get(url) ...
{ "domain": "codereview.stackexchange", "id": 44081, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python if __name__ == "__main__": url = sys.argv[1] main(url) if guards on loops: When using a for loop, it's common to see this kind of pattern: for thing in iterable: if condition: # do things While this is easy to understand and straightforward, it can be a little cleaner and avoid extra indentation to check the negative case and skip it: for thing in iterable: if not condition: continue # do things, note no else So in your link_validator: def link_validator(links): for link in links: page = link.get("href") if not str(page).startswith('https://'): continue url = link.get("href") res = requests.get(url) try: res.raise_for_status() print(f"Page found: {page}") except Exception as exc: print(f"There was a problem with {page}:\n{exc}")
{ "domain": "codereview.stackexchange", "id": 44081, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
swift, mvc, ios, mvvm Title: MVVM pattern in Swift Question: I've been coding for some time now and since I am working alone I'm not strict in my coding structure approach(bad idea) and was only focused on getting things done which resulted in MVC(MASSIVE-View-Controllers). Now recently I've started adapting to MVVM and things are looking clean and simple. But I'm not sure if I'm following or breaking the MVVM pattern. Please review the code below. MyActivityModel(Model) // MARK: - Request struct MyActivityRequest: Convertable{ var UserID = UD.string(forKey: USER_ID) ?? "" var TransactionType = ActivityType.ALL.rawValue } // MARK: - Response struct MyActivityResponse: Codable { let Value: [MyActivityObject]? let Response: String? let ResponseCode: Int? } struct MyActivityObject: Codable { let Date, Points: String? let TransactionType, Amount: String? let BranchTitle, TransactionCode: String? } ActivityVC(View) import UIKit class MyActivityVC:UIViewController{ var activityType = ActivityType.ALL let vm = MyActivityVM() let common = Common() var activityView: UIView! @IBOutlet weak var noInternetLabel: UILabel! @IBOutlet weak var noInternetView: UIView! @IBOutlet weak var noDataLabel: UILabel! @IBOutlet weak var noDataAvailableView: UIView! @IBOutlet weak var tabelView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.title = "Transactions".localized() SetupViews() BindViews() LoadData() } func SetupViews(){ activityView = common.GetActivityView(holderView: self.view) noInternetLabel.text = "No active internet connection".localized() noDataLabel.text = "You don't have any transactions yet".localized() } override func viewWillAppear(_ animated: Bool) { self.navigationController?.setNavigationBarHidden(false, animated: true) }
{ "domain": "codereview.stackexchange", "id": 44082, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, mvc, ios, mvvm", "url": null }
swift, mvc, ios, mvvm func BindViews(){ vm.activities.bind { [weak self] in if $0.count == 0 { self?.tabelView.isHidden = true self?.noDataAvailableView.isHidden = false }else{ self?.tabelView.isHidden = false self?.noDataAvailableView.isHidden = true self?.tabelView.reloadData() } } vm.loading.bind { [weak self] in self?.activityView.isHidden = !$0 } vm.errorMessage.bind { [weak self] in guard let self else {return} if $0.errorMessage.count > 0 { if $0 == .noInternet{ self.noInternetView.isHidden = false self.noDataAvailableView.isHidden = true self.tabelView.isHidden = true }else{ self.common.ShowDialog(_title: nil, _msg: $0.errorMessage, _view: self) } } } } func LoadData(){ vm.LoadActivitiesData(activityType: activityType) } } extension MyActivityVC: UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return vm.activities.value.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: MyActivityCell.ID) as? MyActivityCell else { return UITableViewCell() } cell.activity = vm.activities.value[indexPath.row] return cell } } MyActivityCell(View) import UIKit class MyActivityCell: UITableViewCell {
{ "domain": "codereview.stackexchange", "id": 44082, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, mvc, ios, mvvm", "url": null }
swift, mvc, ios, mvvm MyActivityCell(View) import UIKit class MyActivityCell: UITableViewCell { static let ID = "activity_cell" @IBOutlet weak var branchTitle: UILabel! @IBOutlet weak var pointsLabel: UILabel! @IBOutlet weak var USDLabel: UILabel! @IBOutlet weak var label: UILabel! @IBOutlet weak var label2: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var activityTypeView: UIView! var activity : MyActivityObject? { didSet{ branchTitle.text = activity?.BranchTitle pointsLabel.text = activity?.Points USDLabel.text = activity?.Amount dateLabel.text = activity?.Date guard let type = Int(activity?.TransactionCode ?? "00") else {return} var color = UIColor.gray switch type { case 1: color = .systemGreen case 2: color = .systemRed case 3: color = .systemYellow default: color = .gray } activityTypeView.backgroundColor = color } } override func awakeFromNib() { super.awakeFromNib() label.text = "PTS".localized() label2.text = "USD".localized() } } MyActivityVM(Viewmodel) import Foundation class MyActivityVM{ var request = MyActivityRequest() var activities: Observable<[MyActivityObject]> = Observable([MyActivityObject]()) var loading: Observable<Bool> = Observable(false) var errorMessage: Observable<RequestErrorHandling> = Observable(RequestErrorHandling.none) func LoadActivitiesData(activityType: ActivityType){ request.TransactionType = activityType.rawValue guard let body = request.convertToDict() else {return}
{ "domain": "codereview.stackexchange", "id": 44082, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, mvc, ios, mvvm", "url": null }
swift, mvc, ios, mvvm loading.value = true URLSession.shared.Request(params: "activities", body: body, expecting: MyActivityResponse.self){result in DispatchQueue.main.async{ [weak self] in guard let self else {return} self.loading.value = false switch result { case .success(let data): if data.Response == "success"{ guard let transactions = data.Value else { return } self.activities.value.append(contentsOf: transactions) } case .failure(let failure): self.errorMessage.value = failure as! RequestErrorHandling } } } } } I've omitted the URLSession extension to create and fire the API request. I'm not using callback/closures because the views are bind using Boxing here. Any comments are appreciated. PS Not sure if this is the correct place to ask this question so please don't down vote. Answer: The overall MVVM implementation within MyActivityVC seems fine. FWIW, before you give up on MVC entirely, I might advise referring to Dave DeLong’s A Better MVC posts or the video. It is an interesting take on the “massive view controller” joke. Also, rather than this Observable implementation, you might consider refactoring to use Combine. Or even Combine in conjunction with SwiftUI. Given the evolution of observable patterns native to Swift, the use of third-party implementations feels like a bit of an anachronism. A few tactical observations on your code snippets: It is a bit curious that MyActivityCell is not following the same MVVM pattern, but rather is falling back to more of a MVC/MVP style pattern. I'd either go all in on MVVM, or not do it at all.
{ "domain": "codereview.stackexchange", "id": 44082, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, mvc, ios, mvvm", "url": null }
swift, mvc, ios, mvvm As a matter of convention, methods and properties names should start with lowercase letters. The viewWillAppear should call super. I would advise renaming tabelView to tableView.
{ "domain": "codereview.stackexchange", "id": 44082, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, mvc, ios, mvvm", "url": null }
python, programming-challenge, hash-map, lambda Title: Finger Exercise: Update book cipher by creating new book Question: I'm working my way through the finger exercises in John Guttag's book Introduction to Python Programming, third edition. The following finger exercise on page 143 describes encryption/decryption with a book cipher. The first exercise was to implement decoder and decrypt in the same style as encryption is working. The book mentions this bug and gives the task to implement a solution like they hinted at: The bug: When a character occurs in plain text but not in the book, something bad happens. The code_keys dictionary assigns -1 to each such character, and decode_keys assigns -1 to the last character in the book, whatever that may be. The solution: Create a new book by appending something to the original book. My solution new_book uses a lambda function to be in line with the rest of the code. But this overturns the principle of encryption, if the plain text is needed during encryption and decryption # Mapping individual, unique letters of plaintext to index number gen_code_keys = (lambda book, plain_text: {c: str(book.find(c)) for c in plain_text}) # Slicing operator at the end to remove the first '*' at the beginning encoder = (lambda code_keys, plain_text: "".join(["*" + code_keys[c] for c in plain_text])[1:]) # Encrypt plain_text by giving the encoder a book for indexing encrypt = (lambda book, plain_text: encoder(gen_code_keys(book, plain_text), plain_text)) # Decode key generator analogue to gen_code_keys gen_decode_keys = (lambda book, cipher: {c: book[int(c)] for c in cipher.split("*")}) # Implement decoder by looping through all numbers in cipher decoder = (lambda decode_keys, cipher: "".join((decode_keys[c] for c in cipher.split("*")))) # Decrypting the cipher analog to encrypt function decrypt = (lambda book, cipher: decoder(gen_decode_keys(book, cipher), cipher))
{ "domain": "codereview.stackexchange", "id": 44083, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, hash-map, lambda", "url": null }
python, programming-challenge, hash-map, lambda Don_Quixote = "In a village of La Mancha, the name of which I have no " \ "desire to call to mind, there lived not long since one of those " \ "gentlemen that keep a lance in the lance-rack, an old buckler, a lean " \ "hack, and a greyhound for coursing." # --------------- My Solution --------------- # # Creating new book with missing letters in book to fix cipher bug new_book = (lambda book, plain_text: book + "".join([c for c in plain_text if c not in book])) # plain text contains the letters: !ABENQjx plain_text = "No joke, Abraham Boston had six beer. Everyone it Q!" # Create new book by appending missing letter from plain_text book = new_book(Don_Quixote, plain_text) print(plain_text) cipher = encrypt(book, plain_text) print(cipher) print(decrypt(book, cipher)) Ok, so I changed my code so far that I create the updated book with the missing characters appended before encrypting/decrypting. Thus I removed the function call new_book inside the encrypt and decrypt function. With that at least I don't need the plain_text in my decrypt function. Are there further improvements I could make? Answer: It is difficult to answer this question. There is so much about the code I hate, but I have to restrict my review to only your code: the code after the # —- My solution -- # comment marker. Forget lambda lambda functions have their uses. This is not one of them. Compare this: new_book = (lambda book, plain_text: book + "".join([c for c in plain_text if c not in book])) with this: def new_book(book, plain_text): return book + "".join([c for c in plain_text if c not in book])
{ "domain": "codereview.stackexchange", "id": 44083, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, hash-map, lambda", "url": null }
python, programming-challenge, hash-map, lambda They both do exactly the same thing: they create a function accepting two parameters, and assign that function to the identifier new_book. In my opinion, the latter is clearer; the reader can immediately tell a function is being defined. The indentation is less, and a level of parentheses has been removed. Additionally, several language features are available with the def version - type-hints and """docstrings""" - which can further improve understandability. def new_book(book: str, plain_text: str) -> str: """ Create a new “book” to use for encryption and decryption, will is a duplicate of the original book, plus any letters in the `plain_text` message which are missing from the original book. """ return book + "".join([c for c in plain_text if c not in book]) O(mn) Your book has a certain number of characters. Let’s call that m. Your plain_text has a certain number of characters. Let’s call than n. [c for c in plain_text if c not in book] This loops n times, going through all of the letters of plain_text, and for each letter, it searches book for an occurrence of that letter. If a letter is not found in book, that is only determined after scanning through all m letters of the book. n outer loops iterations with up to m iterations in the inner loop means this is has a worst case of \$O(m*n)\$ operations. Potentially quite slow! This worse case bound can be improved, but it requires a bit of preprocessing … which is easy with the def version of the function: def new_book(book, plain_text): book_letters = set(book) return book + "".join([c for c in plain_text if c not in book_letters])
{ "domain": "codereview.stackexchange", "id": 44083, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, hash-map, lambda", "url": null }
python, programming-challenge, hash-map, lambda Turning book into a set of letters is an \$O(m)\$ operation. With that, c not in book_letters becomes an \$O(1)\$ operation. Repeated in the loop n times makes it \$O(n)\$, so the entire function becomes \$O(m + n)\$ … considerably faster. But wait! While we’re at it, what is with the temporary list of characters [c …]? It is created just to be iterated over in the join(…). Why not just iterate without the temporary list creation? def new_book(book, plain_text): book_letters = set(book) return book + "".join(c for c in plain_text if c not in book_letters) Better solutions Why add plain_text to the book? If you and you friend (or spy) have exchanged a book, and then you need to send a message with letters which were not in the book, you have to send a complete new_book to your friend (spy) … which could be intercepted making the encryption useless. Plus, if a second message is sent with still different letters, yet another book would be necessary. A third message would require a third book, and so on! Decoding the cipher would require knowing which book was used to encode it (book1, book2, book3, …) — information which is not given. It is a simple matter to expand the book without relying on plain_text. Just unconditionally add string.printable to the original book. This easily takes care of your missing !ABENQjx characters. Except, it is still not a complete solution. Résumé would still result in -1 encodings. Adding the entire Unicode character set to book would be required, if you stayed with this approach. Instead, why not record the maximum value your book encoder returns, and return that value plus ord(c) for characters not in the book? When an encoded value exceeds the maximum value the book can decode, subtract that maximum, and use chr(#) to convert it back to the required character.
{ "domain": "codereview.stackexchange", "id": 44083, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, hash-map, lambda", "url": null }
pascal Title: Pascal Bubble Sort Implementation Question: I would prefer a review of: Efficiency Standards Different approaches Here's the code: program bubbleSort; var toSort: array[1..5] of integer = (3, 25, 2, 69, 1); passChanges: boolean = true; counter, index, temp: integer; begin while passChanges do begin index := 1; passChanges := false; for index := 1 to length(toSort) - 1 do begin if (toSort[index] > toSort[index +1]) then Begin temp := toSort[index + 1]; toSort[index + 1] := toSort[index]; toSort[index] := temp; passChanges := true; end; end; end; for counter := 1 to length(toSort) do writeln(toSort[counter]); readln; end. Answer: As long as we're bumping this older question: for index := 1 to length(toSort) - 1 do You don't need to iterate over the entire array every time. You could set a variable and decrement it. E.g. unsortedCount: integer = length(toSort); Then before the loop Dec (unsortedCount); While this won't change the asymptotic analysis (still quadratic worst case), it can cut the effective time. This works because Bubble Sort is guaranteed to move the largest element in a segment to the last position in each pass. Once that's done, that element will no longer move. So we don't need to check it again and can reduce the segment size. Note: it's been at least thirty years since I programmed in Pascal. And I was not an expert on Pascal syntax then. Please don't take anything I wrote as suggesting the correct Pascal way to do things. This is purely an algorithmic review.
{ "domain": "codereview.stackexchange", "id": 44084, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "pascal", "url": null }
python Title: Automate the Boring Stuff Chapter 13 - Multiplication Table Maker Question: The project outline: Create a program multiplicationTable.py that takes a number N from the command line and creates an N×N multiplication table in an Excel spreadsheet. My solution: # A program to create a NxN multiplication table in excel # Usage: python multiplication_table_maker.py "number" "folder to save the table in" import openpyxl, sys from openpyxl.utils import get_column_letter, column_index_from_string def main(num, save_path): workbook = openpyxl.Workbook() sheet = workbook.active for sequence, index in enumerate(range(2, num + 2), 1): top = sheet.cell(row=1, column=index).value = sequence side = sheet.cell(row=index, column=1).value = sequence bottom_right = sheet.cell(row=num + 1, column=num + 1).coordinate for rows in sheet["B2":f"{bottom_right}"]: for cells in rows: top = int(sheet[f"{get_column_letter(cells.column)}1"].value) side = int(sheet[f"A{cells.row}"].value) cells.value = top * side workbook.save(f"{save_path}\multiplication_table_maker.xlsx") if __name__ == '__main__': num = int(sys.argv[1]) # Enter a number save_path = sys.argv[2] main(num, save_path) Answer: enumerate(range(2, num + 2), 1) is confusing, consider naming the argument as in the docs: enumerate(range(2, num + 2), start=1) The name sequence is misleading since it stands for a single number. Same for rows and cells: should be row and cell. top = int(sheet[f"{get_column_letter(cells.column)}1"].value) side = int(sheet[f"A{cells.row}"].value) Here you retrieve values from the excel table. Those values belong to the range you defined a few lines earlier, so just get them from there, it will be faster and more clear.
{ "domain": "codereview.stackexchange", "id": 44085, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
c#, tic-tac-toe Title: Determine winner of a TicTacToe game Question: i'm trying to find the winner of a 3x3 TicTacToe game. I user input N which is number of moves, and then N moves like (1,0), (0,2), etc. (X strats the game). At the end of the game the program should return who wins the game (X or 0) or "draw" if there is no winner. I have the following code: namespace ConsoleApp20; public class Program { public static string Tictactoe(int[][] moves) { int[] row = new int[3]; int[] col = new int[3]; int diag1 = 0; int diag2 = 0; const int c1 = 2; const int c2 = 3; int n = Convert.ToInt32(Console.ReadLine()); for (int i = 0; i < n; i++) { int x = moves[i][0]; int y = moves[i][1]; var inc = i % 2 == 0 ? 1 : -1; row[x] += inc; col[y] += inc; if (x == y) { diag1 += inc; } if (x + y == c1) { diag2 += inc; } if (Math.Abs(row[x]) == c2 || Math.Abs(col[y]) == c2 || Math.Abs(diag1) == c2 || Math.Abs(diag2) == c2) { return i % c1 == 0 ? "X" : "0"; } } return moves.Length == 9 ? "Draw" : "Pending"; } } I need a suggestion about how to reduce the cyclomatic complexity of this method from 11 to 10. Answer: Without having a proper context, here are my suggestions. Where I had made any assumptions I stated them before any suggestions. Constants Assumption(s) c2 represents the dimension of the TicTacToe's matrix Suggestion(s) You should define them on the class-level rather than inside the method You should use better naming than c1 and c2 to express your intents You should use c2 in the arrays declarations as well new int[c2]; to ease the future work if you need to support 2x2 or 4x4 TicTacToe as well User input Suggestion(s)
{ "domain": "codereview.stackexchange", "id": 44086, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, tic-tac-toe", "url": null }
c#, tic-tac-toe User input Suggestion(s) User can provide any data textual data via the console interface Please make sure that input is in the right format (use int.TryParse) and between the right range if (n < lowerLimiter || n > upperLimit) throw new ArgumentOutOfRangeException(...); Depending on the requirements you might need to implement a retry logic which runs until the user provides a valid input Jagged array Assumption(s) The first dimension represents the move ordinal The second dimension represents the coordinates (x and y in your case) Suggestion(s) It seems like that the second dimension of the jagged array will always contain 2 elements It might make sense to use a dedicated structure for that Either by using some built-in ones like Point struct or creating your own Iterating through a jagged array can be done by a foreach I'm uncertain how does N relates to the first dimension of the moves, so this might not be applicable for your use case foreach (var (move, moveIndex) in moves.Select((array, index) => (array, index))) { var (x, y) = (move[0], move[1]); var inc = moveIndex % 2 == 0 ? 1 : -1; ... } Ternary conditional operator Suggestion(s) Rather than having guard expression to do an assignment only if certain criteria is met you can use ?: operator here as well to stream-line your code diag1 = x == y ? diag1 + inc : diag1; diag2 = x + y == c1 ? diag2 + inc : diag2; Please spend some time to try to find better names than diag1 and diag2 Single return Suggestion(s) Try to aim for having only a single return Rather than calling a return inside the for/foreach loop use break int? lastMoveIndex = null; foreach (...) { ... if (Math.Abs(row[x]) == c2 || Math.Abs(col[y]) == c2 || Math.Abs(diag1) == c2 || Math.Abs(diag2) == c2) { lastMoveIndex = moveIndex; break; } }
{ "domain": "codereview.stackexchange", "id": 44086, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, tic-tac-toe", "url": null }
c#, tic-tac-toe return lastMoveIndex.HasValue ? lastMoveIndex.Value % c1 == 0 ? "X" : "0" : moves.Length == 9 ? "Draw" : "Pending";
{ "domain": "codereview.stackexchange", "id": 44086, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, tic-tac-toe", "url": null }
c, game, homework Title: Rock Paper Scissors, Player vs Computer Question: I was given for homework to make a rock paper scissor game where I input my choice as a string either: "@" for rock, "[]" for paper or "X" for scissors. The computer chooses a random one and it's printed who wins. I'm worried that my code isn't good enough. #include <stdio.h> /* printf, scanf, NULL */ #include <stdlib.h> /* srand, rand */ #include <time.h> /* time */ #include <string.h> /* strcmp */ /* Configure */ #define MAX_SIGN_LEN (8) #define STR_ROCK "@" #define STR_PAPER "[]" #define STR_SCISSORS "X" typedef enum RPS_ENUMERATOR { ROCK, PAPER, SCISSORS, N_RPS } rps; typedef enum RPS_RESULT { YOU_LOOSE, YOU_WIN, TIED, N_RESULTS } rpsResult; const char *rpsSigns [N_RPS] = { STR_ROCK, STR_PAPER, STR_SCISSORS }; const char *gameResult [N_RESULTS] = { "YOU LOOSE!", "YOU_WIN", "TIED" }; rpsResult combinations[N_RPS][N_RPS] = { {TIED, YOU_WIN, YOU_LOOSE}, {YOU_LOOSE, TIED, YOU_WIN}, {YOU_WIN, YOU_LOOSE, TIED} }; int validate_answer (char buffer[MAX_SIGN_LEN], rps rpsUser) { if(rpsUser == N_RPS) { printf("WTF is \"%s\" ?\n", buffer); return 1; } return 0; } rps get_choice_value (char buffer[MAX_SIGN_LEN]) { rps rpsUser = ROCK; for(rpsUser = ROCK; rpsUser < N_RPS; rpsUser++) if(!strcmp(buffer, rpsSigns[rpsUser])) break; return rpsUser; } void run_game () { rps rpsRandom = ROCK; rps rpsUser = ROCK; char buffer[MAX_SIGN_LEN] = {'\0'}; /* Generate a random number between 0 and 3 (inclusive-exclusive) */ rpsRandom = rand() % N_RPS; /* Print requirement */ printf("Choose rock, Paper, Scissors ( %s | %s | %s ): ", rpsSigns[ROCK], rpsSigns[PAPER], rpsSigns[SCISSORS]); /* Ask user */ scanf("%8s", buffer);
{ "domain": "codereview.stackexchange", "id": 44087, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, game, homework", "url": null }
c, game, homework /* Ask user */ scanf("%8s", buffer); /* Obtain user choice as a number */ rpsUser = get_choice_value(buffer); /* Check if choice was valid */ if(validate_answer(buffer, rpsUser) == 1) return; /* Print result */ printf("Program chose: %s. %s\n", rpsSigns[rpsRandom], gameResult[combinations[rpsRandom][rpsUser]]); } int main (void) { /* initialize random seed: */ srand(time(NULL)); /* Run game */ while(1) run_game(); return 0; } Answer: Readability As mentioned, the width of the code spans through 112 characters, which is /not/ obviously too far. I recommend it not exceed 100 characters at most. Even that can be a little too much and force people to do a lot of eye movement in order to read your code. Consider: printf("Choose rock, Paper, Scissors ( %s | %s | %s ): ", rpsSigns[ROCK], rpsSigns[PAPER], rpsSigns[SCISSORS]); or #define ENTRY_TEXT "Choose rock, Paper, Scissors ( %s | %s | %s ): " ... printf(ENTRY_TEXT, rpsSigns[ROCK], rpsSigns[PAPER], rpsSigns[SCISSORS]);
{ "domain": "codereview.stackexchange", "id": 44087, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, game, homework", "url": null }
c, game, homework Overflow The other valid point that was already mentioned is that scanf is called to read up to 8 characters, but it also transparently writes '\0' at the end of buffer so it may end up writing 9 characters and cause a buffer overflow. Change the format parameter to "%7s" (as chux said, 7 being the specifier width) Error-checking I would recommend you to check scanf against the number of items of the argument list successfully read. Not a bad practice. Limit restrictions It is perfectly fine to hard code length limits, but if you do so, make sure you let the user be aware, perhaps by printing at the end of input suggestion "(max 8 characters)" Otherwise Users might be puzzled as to why their input has been abruptly trimmed. Infloops I can understand why are you taking a serving of the while(1) loop. Loops without an escape clause are nothing more than intended deadlocks. Intended or not, they are still deadlocks and should be taken care of. Minimal changes can be made to force your way out of the loop if you type "exit" or just "e" or maybe do that after 100 rounds. At the end, you can print statistics of how many rounds were lost, won or tied. Implementation details control Minimal changes can be made to allow the user to specify how they want the rock, paper, scissors -representing strings to look like. One would prefer singular characters such as "R", "P", "S", other might prefer morse code... consider using fgets() fgets() is a simpler function that will read the entire line and will not stop on just about any whitespace (which can be more or less hideously achieved via %7[^\n]%c"...) if(fgets(buffer, MAX_SIGN_LEN, stdin) == NULL) puts("Treat error...");
{ "domain": "codereview.stackexchange", "id": 44087, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, game, homework", "url": null }
c, game, homework Thanks to @Toby Speight for reminding me that gets is unsafe as it doesn't have any means to protect against possible overflow return value If your program loop now has an escape clause, you can probably return errno or something. If the improved program design follows the 100 turns advice you can return EXIT_FAILURE if for some reason not all games were played out.
{ "domain": "codereview.stackexchange", "id": 44087, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, game, homework", "url": null }
c, ruby-on-rails Title: FizzBuzz solved by neural network
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails Question: I wrote a very simple AI in C and connected it to the web through Ruby on Rails. It learns the fizzbuzz problem. I'm writing this because I'm back on the job market after 20 years. Of course, github didn't even exist back then. So, now the job hunt environment is totally different and I don't have the assets recruiters are looking for. So, I'm begging for help. I'm asking for a code review of this and any advice you guys have for me. https://github.com/rickcockerham/fizzbuzz-ai Thanks, Rick // Fbai class. // A C program that learns the Fizz Buzz problem. // I used my neural network code that I downloaded years ago and modified. // I have simplified the neural network code to make it only has complicated as
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails // it needs to be to solve this simple problem. One hidden layer and four separate // networks is all it takes to solve the FB problem in 5-10 learning runs. //################################################################################
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails #include <stdio.h> #include <stdlib.h> #include <ruby.h>
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails //nn constants double Error, eta = 0.1; // a very slow learning rate double alpha = 0.90, smallwt = 0.2; #define PASSES 1 //passes per training run. #define NUMPATTERNS 100 // 1-100 #define NUMHIDDEN 1 // hidden layers
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails #define NUMINPUTS 1 //number of inputs. In this case it's just a single integer. #define NNS 4 // one neural network output per norm,fizz,buzz,fizzbuzz double expected[NNS][NUMPATTERNS+1]; //holds the test data.
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails // The weights and outputs of the neural network. double WeightIH[NNS][NUMINPUTS+1][NUMHIDDEN+1];//2. bias and input double WeightHO[NNS][NUMHIDDEN+1]; double SumH[NNS][NUMPATTERNS+1][NUMHIDDEN+1], Hidden[NNS][NUMPATTERNS+1][NUMHIDDEN+1]; double SumO[NNS][NUMPATTERNS+1], Output[NNS][NUMPATTERNS+1]; double DeltaO[NNS], SumDOW[NNS][NUMHIDDEN+1], DeltaH[NNS][NUMHIDDEN+1]; double DeltaWeightIH[NNS][NUMINPUTS+1][NUMHIDDEN+1], DeltaWeightHO[NNS][NUMHIDDEN+1]; // The names of each network. #define NORM 0 #define FIZZ 1 #define BUZZ 2 #define FIZZBUZZ 3 void train(); int gotest(int); void init_ai();
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails void train(); int gotest(int); void init_ai(); //######################################## //random double. I would normally use lib sodium for better random. double randd() { return rand() / (double)RAND_MAX; } //################################################################################ // Ruby - C interface code. // These functions are exposed to Ruby. VALUE rb_fbai;
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails VALUE rb_fbai; VALUE gotrain(VALUE self) { train();//run a single training epoch. return self; } VALUE reinit(VALUE self) { init_ai();// clear the weights and start over. return self; } VALUE valueat(VALUE self, VALUE testnum) { int testx = NUM2INT(testnum); //convert VALUE to int int returnval = gotest(testx);// get the AI output for this int. return INT2NUM(returnval);//convert it back to a VALUE }
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails // define interface methods between Ruby and C void Init_fbai() { rb_fbai = rb_define_class("Fbai", rb_cObject); rb_define_method(rb_fbai, "gotrain", gotrain, 0); rb_define_method(rb_fbai, "valueat", valueat, 1); rb_define_method(rb_fbai, "reinit", reinit, 0); init_ai(); } //################################################################################ // the patterns are the training data. It's an array of 3 values 0 if it's just x, 1 if it's %3, 2 if it's %5, and 3 if it's %3&%5 // these are stored in three values for three sets of training patterns. void patterns() {
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails void patterns() { memset(expected, 0.0, NNS * NUMPATTERNS+1); // all zeros first for(int x = 1; x <= 100; x++) { if(x % 3 == 0 && x % 5 == 0) { expected[FIZZBUZZ][x] = 1.0; // set expexted[3][x] = 1.0 the rest are zeros. } else if(x % 5 == 0) { expected[BUZZ][x] = 1.0; } else if(x % 3 == 0) { expected[FIZZ][x] = 1.0; } else { expected[NORM][x] = 1.0; } } } //################################################################################ // clear all the weights and randomize them to learn the problem or learn it again. void init_ai() { int nn,hid,i;
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails //////////////////////////////////////////////////////////////////////////////// // init nn memset(Output, 0.0, NNS * (NUMPATTERNS+1)); // all zeros for outputs. memset(Hidden, 0.0, NNS * (NUMPATTERNS+1) * (NUMHIDDEN+1)); for(nn = 0; nn < NNS; nn++) { // loop through all neural nets for( hid = 0 ; hid < NUMHIDDEN ; hid++ ) { /* initialize WeightIH and DeltaWeightIH */ for( i = 0; i <= 1; i++) { DeltaWeightIH[nn][i][hid] = 0.0 ; WeightIH[nn][i][hid] = 2.0 * ( randd() - 0.5 ) * smallwt ; } } /* initialize WeightHO and DeltaWeightHO */ for( hid = 0 ; hid < NUMHIDDEN ; hid++ ) { DeltaWeightHO[nn][hid] = 0.0 ; WeightHO[nn][hid] = 2.0 * ( randd() - 0.5 ) * smallwt ; } } patterns(); }
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails } patterns(); } //############################################# // Returns -1 if the output is wrong otherwise it will return 0-3 as the output. int gotest(int x) { double max = 0.0; int nn, maxx = 0; int correct = 0; for(nn = 0; nn < NNS; nn++) { if(Output[nn][x] > max) { max = Output[nn][x]; maxx = nn; if(1.0 == expected[nn][x]) correct = 1; } } return (1 == correct ? maxx : -1); }
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails //################################################################################ //################################################################################ //################################################################################ // training run for the AI. // This code was downloaded from the internet many years ago and modifed for my other AI project ai-stocktrading.com
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails // I've simplifed it for this small demo. void train() {
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails int hid, nn, p, epoch; for(nn = 0; nn < NNS; nn++) { // loop through both neural nets for( epoch = 0 ; epoch < PASSES ; epoch++) { Error = 0.0; for( p = 1 ; p < NUMPATTERNS+1 ; p++ ) { /* repeat for all the training patterns */ for( hid = 1 ; hid <= NUMHIDDEN ; hid++ ) { /* compute hidden unit activations */ SumH[nn][p][hid] = WeightIH[nn][0][hid] ;// bias against input 0 SumH[nn][p][hid] += expected[nn][p] * WeightIH[nn][1][hid]; //double np is the input 1-100 Hidden[nn][p][hid] = 1.0/(1.0 + exp(-SumH[nn][p][hid])) ; }
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails /* compute output unit activations and errors */ SumO[nn][p] = WeightHO[nn][0]; // bias for( hid = 1 ; hid <= NUMHIDDEN ; hid++ ) { SumO[nn][p] += Hidden[nn][p][hid] * WeightHO[nn][hid] ; } // Sigmoidal Outputs Output[nn][p] = 1.0/(1.0 + exp(-SumO[nn][p])); //Sigmoidal Outputs, SSE DeltaO[nn] = (expected[nn][p] - Output[nn][p]) * Output[nn][p] * (1.0 - Output[nn][p]) ; for( hid = 1 ; hid <= NUMHIDDEN ; hid++ ) { /* 'back-propagate' errors to hidden layer */ SumDOW[nn][hid] = WeightHO[nn][hid] * DeltaO[nn]; DeltaH[nn][hid] = SumDOW[nn][hid] * Hidden[nn][p][hid] * (1.0 - Hidden[nn][p][hid]) ; } for( hid = 1; hid <= NUMHIDDEN ; hid++ ) { /* update weights WeightIH */ DeltaWeightIH[nn][0][hid] = eta * DeltaH[nn][hid] + alpha * DeltaWeightIH[nn][0][hid] ; WeightIH[nn][0][hid] += DeltaWeightIH[nn][0][hid] ;
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails DeltaWeightIH[nn][1][hid] = eta * expected[nn][p] * DeltaH[nn][hid] + alpha * DeltaWeightIH[nn][1][hid]; WeightIH[nn][1][hid] += DeltaWeightIH[nn][1][hid] ; } /* update weights WeightHO */ DeltaWeightHO[nn][0] = eta * DeltaO[nn] + alpha * DeltaWeightHO[nn][0] ; WeightHO[nn][0] += DeltaWeightHO[nn][0] ; for( hid = 1 ; hid <= NUMHIDDEN ; hid++ ) { DeltaWeightHO[nn][hid] = eta * Hidden[nn][p][hid] * DeltaO[nn] + alpha * DeltaWeightHO[nn][hid] ; WeightHO[nn][hid] += DeltaWeightHO[nn][hid] ; } }//for num patterns } // for epochs }//for nns
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails }// train index_controller.rb require 'fbai' class IndexController < ApplicationController layout false # I need the AI to survive between calls to the testit function. $ai = Fbai.new def index #reset the AI $ai.reinit(); end # this will return a string of numbers and their value (x,fizz,buzz,fizzbuzz) def testit ret = ''; for x in 1..100 data = $ai.valueat(x).to_i ret << "#{x}=" if(-1 == data) ret << '-err-' elsif(0 == data) ret << "#{x}" elsif(2 != data) ret << 'FIZZ' end if(1 < data) ret << 'BUZZ' end ret << " " end render html: ret, layout: false end
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails # this tells the AI to do one training pass. Then the testit function is called again to read the results. def trainmore $ai.gotrain() render plain: 'success' end end index.html.erb <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <style> div { width:80px; height:30px; float:left; border:1px solid black; margin:1px; } .clearleft { width:0px; clear: left; border: none; } </style> </head> <body> <h2>Neural Network leaning the FizzBuzz problem...</h2> <h3>Training run #<span id="runnumber">0</span></h3> <% for x in 0..99 if x % 5 == 0 %> <div class="clearleft"></div> <% end %> <div id="val<%=x+1%>"><%=x%></div> <% end %> <%= javascript_tag do %> const donere = /err/; var run = 0; callnext_number(); const timeit = setInterval(callnext_number, 2000);
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails callnext_number(); const timeit = setInterval(callnext_number, 2000); async function callnext_number() { var ret = ''; promi = new Promise(fillin => {jQuery.ajax({ url: "index/testit", type: "GET", success: function(data){ var vals = data.split(' '); console.log(vals); for(let x = 1; x <= 100; x++) { let ans = vals[x-1].split('='); $('#val'+x).html(ans[1]); if(donere.exec(ans[1])) { $('#val'+x).css("background-color","#ff3333"); } else { $('#val'+x).css("background-color","white"); } } if(donere.exec(data)) { jQuery.ajax({url: "index/trainmore",type: "GET"}); } else { clearInterval(timeit); alert('done'); } $('#runnumber').html(++run); }, error: function(data) { alert(data); }//return }); } ); await promi; return; }//call next <% end %> </body> </html>
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails return; }//call next <% end %> </body> </html> Answer: General Observations I can't comment on the ruby portion of the code because I don't know ruby. There are no classes in C but you could use a struct for the same purpose. Try to keep line length under 100 characters, all IDEs support more than 80 characters these days, but not all IDEs and editors provide line wrap by default. Try to keep function length to one screen, functions that are larger than that are hard to understand and maintain. Avoid Global Variables It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C and C++ global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The answers in this stackoverflow question provide a fuller explanation. It isn't clear that the global variable Error is ever used, although it is finally assigned in the void train() function. If Error and eta are truly constants, modern C now supports constant declarations: const double Error = 1; const double eta = 0.1; Declare the Variables as Needed In the original version of C back in the 1970s and 1980s variables had to be declared at the top of the function. That is no longer the case, and a recommended programming practice to declare the variable as needed. In C the language doesn't provide a default initialization of the variable so variables should be initialized as part of the declaration. For readability and maintainability each variable should be declared and initialized on its own line. Modern versions of C allow initialization of loop variables in the loop: void train() { size_t hid; for (size_t nn = 0; nn < NNS; nn++) { // loop through both neural nets for (size_t epoch = 0; epoch < PASSES; epoch++) {
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails for (size_t p = 1; p < NUMPATTERNS + 1; p++) { /* repeat for all the training patterns */ for (hid = 1; hid <= NUMHIDDEN; hid++) { /* compute hidden unit activations */ SumH[nn][p][hid] = WeightIH[nn][0][hid];// bias against input 0 SumH[nn][p][hid] += expected[nn][p] * WeightIH[nn][1][hid]; //double np is the input 1-100 Hidden[nn][p][hid] = 1.0 / (1.0 + exp(-SumH[nn][p][hid])); } Prefer size_t Over int for Array Indexes The size_t type is preferable over int for indexing arrays, it is an unsigned type so it can't go negative, it will also be properly sized (either int or long) based on the compiler and operating system to index the largest possible arrays. The size_t type was substituted for int in the above example of local declarations. Function Complexity The void train() function is too complex, it can be broken up into smaller functions, one obvious example is the following code: SumO[nn][p] = WeightHO[nn][0]; // bias for (hid = 1; hid <= NUMHIDDEN; hid++) { SumO[nn][p] += Hidden[nn][p][hid] * WeightHO[nn][hid]; } There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c, ruby-on-rails that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function. Comments I personally prefer the original C style comments for block comments: /* Fbai class. * A C program that learns the Fizz Buzz problem. * I used my neural network code that I downloaded years ago and modified. * I have simplified the neural network code to make it only has complicated as * it needs to be to solve this simple problem. One hidden layer and four separate * networks is all it takes to solve the FB problem in 5-10 learning runs. */ For other comments I prefer the newer // comment style. Which ever style you use, be consistent, don't mix the types within the code blocks, as done in the void train() function. It isn't clear why you have 3 line code separator comments: //################################################################################ //################################################################################ //################################################################################
{ "domain": "codereview.stackexchange", "id": 44088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, ruby-on-rails", "url": null }
c++, c++20 Title: Execute Shell commands in Python code Question: I wrote a little C++ program that lets me transpile a syntax that allows running Shell in Python to legal Python and then execute it. Here is an example input: filename = f'./data/lines.txt' n_lines = int(`wc -l {filename}`.split()[0]) print(n_lines, 'lines in file') This is transpiled to: import subprocess filename = f'./data/lines.txt' _ = subprocess.run(f'wc -l {filename}'.split(), capture_output=True).stdout.decode('utf-8').strip() n_lines = int(_.split()[0]) print(n_lines, 'lines in file') and then executed. My main code is: main.py #include <regex> #include <string> #include <vector> #include <sstream> #include <cctype> #include <memory> #include <fstream> #include <cstdlib> #include <stdlib.h> #include <iostream> #include <filesystem> #include "formatter.h" /** Process a single line. * * @param line - The line to process * @return The processed Python code */ std::string process_line(std::string& line) { std::ostringstream generated; // Parse template args in the string. if (line.find("`") != std::string::npos) { // Find all indices. std::vector<size_t> cmd_idx; size_t cur_tick_idx = 0; size_t next_tick_idx; // Find all backticks while ((next_tick_idx = line.find("`", cur_tick_idx)) != std::string::npos) { // First, check that it is not escaped. if (next_tick_idx <= 0 || line[next_tick_idx - 1] != '\\') cmd_idx.push_back(next_tick_idx); cur_tick_idx = next_tick_idx + 1; } // Ensure we have an even number of indices if (cmd_idx.size() % 2 == 1) throw "Invalid number of template quotes"; // Begin substitution using formatters. for (size_t i{}, j{1}; i < cmd_idx.size(); i += 2, j += 2) { std::string substr = line.substr(cmd_idx[i] + 1, cmd_idx[j] - cmd_idx[i] - 1);
{ "domain": "codereview.stackexchange", "id": 44089, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 generated << "_ = subprocess.run(f'" << substr << "'.split(), capture_output=True).stdout.decode('utf-8').strip()\n"; // Check for formatters if (cmd_idx[i] > 0 && (std::isalnum(line[cmd_idx[i] - 1]) || line[cmd_idx[i] - 1] == '_')) { size_t k; for (k = cmd_idx[i] - 2; k >= 0; --k) { if (!std::isalnum(line[k]) && line[k] != '_') break; } std::string format = line.substr(k + 1, cmd_idx[i] - k - 1); // Apply formatter // If "str", do nothing. if (format != "str") { std::unique_ptr<type_formatter> formatter = std::make_unique<type_formatter>(format); generated << formatter->format(); } } // Now, replace the part in quotes with our variable generated << line.replace(cmd_idx[i], cmd_idx[j] - cmd_idx[i] + 1, "_"); } } else { generated << line; } return generated.str(); } int main(int argc, char* argv[]) { // TODO: Change this to a filename input std::ifstream fin(argv[1]); std::ofstream fout("out.py"); fout << "import subprocess\n\n"; std::string line; while (std::getline(fin, line)) { fout << process_line(line) << std::endl; } fout.close(); // Run the code const char* path = std::getenv("PATH"); std::filesystem::path cur_path = std::filesystem::current_path(); std::string new_path = std::string(path) + ":" + cur_path.string(); if (setenv("PATH", new_path.c_str(), 1) != 0) throw "Failed to set PATH"; std::system("python out.py"); return 0; } and my formatter code is pretty simple: formatter.cpp #include "formatter.h" type_formatter::type_formatter(const std::string& fmt) { this->fmt = fmt; }
{ "domain": "codereview.stackexchange", "id": 44089, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 type_formatter::type_formatter(const std::string& fmt) { this->fmt = fmt; } /** * Returns Python code that checks whether the string * can be safely casted to the desired type. * * TODO: Check indent level */ std::string type_formatter::get_safe_formatter() { std::string check_cast_code = "try:\n\t" "_ = " + fmt + "(_)\nexcept ValueError:\n\t" "raise"; return check_cast_code; } std::string type_formatter::format() { if (fmt == "int" || fmt == "float") return get_safe_formatter(); if (fmt == "list") return "_ = _.split('\\n')\n"; if (fmt.starts_with("list.")) { std::string list_type = fmt.substr(5); return "_ = [" + list_type + "(x) for x in _.split('\\n')]\n"; } throw "Formatter for type does not exist."; }; formatter.h #ifndef FORMATTER_H #define FORMATTER_H #include <string> /** * The base class for formatters. This is an abstract class * and should be extended to implement specific formatters. * Formatters must implement the `format()` function, which * should return a std::string containing Python code to process * a variable called _, which will contain the output from shell * code in the transpiled program. As a template, the code should * end up assigning _ to the correct type. The Python code should * end in a newline. */ class basic_formatter { public: basic_formatter() = default; virtual std::string format() = 0; }; class type_formatter : public basic_formatter { std::string fmt; std::string get_safe_formatter(); public: type_formatter(const std::string&); type_formatter() = delete; virtual std::string format(); }; #endif I primarily work with JS and Python, so I'm trying to understand how I can write better C++ code, what norms I've broken, what I could do better, etc. I'm using C++20.
{ "domain": "codereview.stackexchange", "id": 44089, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 Answer: Code that's ready for review shouldn't have any outstanding TODO comments. You should resolve those. Instead of including both <cstdlib> and <stdlib.h>, use just the C++ header, and namespace-qualify std::size_t where it's used. Class basic_formatter is intended for use as a base class. You should provide a virtual destructor so that subclasses are correctly destroyed when deleted via a base-class pointer: basic_formatter() = default; virtual ~basic_formatter() = default; In type_formatter, I don't think we want implicit conversion from strings, so mark that constructor with explicit. Use the constructor's initializer-list to populate fmt, rather than letting it default-construct and then overwriting in the body. And if we pass by value, we can avoid an extra copy in many cases. explicit type_formatter(const std::string fmt) : fmt{std::move(fmt)} {} It's not necessary to declare a deleted no-args constructor - just omit this, as the above constructor inhibits generation of a default constructor. The format() method should be declared override instead of virtual{ std::string format() override; Consider whether you really want to allow format() to modify the formatter - perhaps it should be const? When we construct a formatter, we make a smart pointer. But we don't need to do that, as we can construct and use it directly: if (format != "str") { type_formatter formatter{format}; generated << formatter.format(); } We have a logic error here: std::size_t k; for (k = cmd_idx[i] - 2; k >= 0; --k) {
{ "domain": "codereview.stackexchange", "id": 44089, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 That's an infinite loop, because k >= 0 can never be false. That's a sign of not enabling sufficient compiler warnings, and perhaps also of insufficient unit-testing. When throwing, we should use appropriate subclasses of std::exception. C++ allows us to throw a string literal, but that is generally considered a poor practice. And we never catch anything we throw - that needs to be fixed. process_line() shouldn't need to write to a string-stream and stringify the result, given that when we call it, we immediately write its result to another stream. Just pass the output stream into the function (as a reference) and write to it directly. The search for matching backquote characters is flawed. A preceding backslash doesn't escape a backquote if the backslash itself is quoted - we'll need a smarter parser to give us real robustness here. Lots of ways in which main() can misbehave, none of which give any diagnostic or exit status: input filename isn't readable unable to create or overwrite out.py in current directory (consider using mktemp() or similar to get somewhere safe to write) writing fails later (e.g. disk full) python is not on the path (likely in systems where the interpreters are called python2 and/or python3). We lose the exit status of the invoked Python program. It's probably better to exec() rather than std::system() on POSIX systems, so that the caller gets the full exit status (including signal and core-dump information if appropriate). Where only standard-library functions are available, consider using the return value from std::system() to determine what to return from main().
{ "domain": "codereview.stackexchange", "id": 44089, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c, strings, parsing Title: Function to skip characters Question: A very simple function that can be used such that it returns a pointer to the first character on which func returned 0. However, it also handles escaped lines. Needless to say this could be very useful in my cases, for example skipping spaces when converting a csv to an array. /** Skip characters from @src * @func: isspace, isdigit, isalpha, etc can be used */ char *skip (const char *src, int(*func)(int)) { char* p = NULL; for(p = src; *p != '\0'; p++) { if(!func(*p)) { if(*p == '\\') { p++; if(*p == '\r') /* Will probably have to deal with annoying MS-style line endings when the source string is loaded from a file */ { p++; } if(*p == '\n') { continue; } } break; } } return p; } Example test usage: int ishspace (char ch) { return(ch == ' ' || ch == '\t'); } int main (void) { char* p = skip(" \t \\\n \t Hello World\n", ishspace); printf("%s", p); return 0; } Output: > Hello World >
{ "domain": "codereview.stackexchange", "id": 44090, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, strings, parsing", "url": null }
c, strings, parsing printf("%s", p); return 0; } Output: > Hello World > Answer: Compilation problems NULL isn't defined - either use the constant 0 or include <stddef.h> before skip(). Alternatively, just initialise p = src instead of this dead store. Type mismatch assigning src to p - we should make them point to the same kind of object, either both const char or both char. (In C++, we would overload the function with two variants, each accepting and returning the same type; in C we need to give the two functions different names). In the test program, printf is undefined - include <stdio.h> to fix this. We can't pass ishspace() to skip() as it has type int(*)(char) but we need an int(*)(int). That's easily fixed by making it accept int instead. ishspace is a reserved identifier that might conflict with future library versions of <ctype.h>. Choose a name that's allowed for user functions (simply inserting _ after is is sufficient). Design issues The comment advertises that the is…() functions from <ctype.h> can be used, but that's dangerous with the present implementation because these functions accept only positive characters (or EOF). We need to cast to unsigned char before widening to int when calling these. When func() returns true for '\\', the backslash-newline concatenation doesn't occur. I think that's the wrong choice, as conceptually, joining continuation lines is usually the first step in parsing. In either case, we should document this in comments. When we see a backslash not followed by newline, we return a pointer to the character immediately after the backslash (or after the carriage-return immediately following). That seems wrong to me; I would expect the return value to point at the backslash itself. A single test is nowhere near enough for this function. I'd like to see a variety of input strings and predicates that together test the entire specification of the function. Some things that are not tested:
{ "domain": "codereview.stackexchange", "id": 44090, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, strings, parsing", "url": null }
c, strings, parsing the empty string input strings with backslash not followed by newline (including some with the backslash at the end of the string). input strings containing consecutive escaped newlines ("\\\n\\\n") input strings containing carriage returns input strings with escaped and non-escaped CRLF predicate function that always returns true predicate functions that return true for '\\' predicate functions that return true for newline or carriage-return We should make the tests self-checking - return a non-zero value from main() if any test returns the wrong result. Modified code I renamed src to s as we don't need the separate p variable. /** Skip characters from @src until @func returns false * This function skips over escaped newlines before applying @func * @func: isspace, isdigit, isalpha, etc can be used * @return: a pointer into @src or to its terminating null character */ const char *skip (const char *s, int(*func)(int)) { for (;;) { /* first skip escaped newlines */ if (*s == '\\') { if (s[1] == '\n') { s += 2; continue; } if (s[1] == '\r' && s[2] == '\n') { s += 3; continue; } } /* then test whether we're looking at a skippable character */ if (!*s || !func((unsigned char)*s)) { return s; } /* next character */ ++s; } } /* skip() for mutable strings */ char *skip_m (char *src, int(*func)(int)) { return (char*)skip(src, func); } I've made only minor changes to the test. You should really replace this with a full unit-test suite. #include <stdio.h> int is_hspace(int ch) { return ch == ' ' || ch == '\t'; } int main(void) { const char* p = skip("\\ \t \\\n \t Hello World", is_hspace); printf("%s\n", p); }
{ "domain": "codereview.stackexchange", "id": 44090, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, strings, parsing", "url": null }
c#, strings, integer Title: Mapping bunch of integers to some strings with less repetition Question: I have this switch case statement which maps an integer to a string. There can be multiple integers that maps to same string. objective here is to not to duplicate the string value and retrive the string value by passing the id. public const int Product1 = 111; public const int Product2 = 112; public const int Product3 = 113; public const int Product4 = 114; public const int Product5 = 115; public const int Product11 = 133; public const int Product12 = 134; public const int Product13 = 135; public const int Product14 = 136; public const int Product15 = 137; public static string GetName(int productId) { switch (productId) { case Product1: case Product11: return "Lorem ipsum dolor sit amet"; case Product2: case Product12: return "Consectetur adipiscing elit"; case Product3: case Product13: return "Ut eu dui ut lorem scelerisque tempo"; case Product4: case Product14: return "Sed feugiat magna sed vestibulum euismod"; case Product5: case Product15: return "Duis ornare libero sed massa dictum"; default: return string.Empty; } } Is there any other ways I can accomplish this task with zero repetition with a nice and tidy code? Answer: Constants Move your name constants into dedicated const fields private const string Name1 = "Lorem ipsum dolor sit amet"; private const string Name2 = "Consectetur adipiscing elit"; private const string Name3 = "Ut eu dui ut lorem scelerisque tempo"; private const string Name4 = "Sed feugiat magna sed vestibulum euismod"; private const string Name5 = "Duis ornare libero sed massa dictum";
{ "domain": "codereview.stackexchange", "id": 44091, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, strings, integer", "url": null }
c#, strings, integer Or simply just private const string Name1 = "Lorem ipsum dolor sit amet", Name2 = "Consectetur adipiscing elit", Name3 = "Ut eu dui ut lorem scelerisque tempo", Name4 = "Sed feugiat magna sed vestibulum euismod", Name5 = "Duis ornare libero sed massa dictum"; Define mappings between ProductIds and Names private static readonly ImmutableDictionary<int, string> ProductNameMappings = new Dictionary<int, string> { { Product1, Name1 }, { Product11, Name1 }, { Product2, Name2 }, { Product12, Name2 }, { Product3, Name3 }, { Product13, Name3 }, { Product4, Name4 }, { Product14, Name4 }, }.ToImmutableDictionary(); I've defined it as a static, readonly immutable collection to prevent any unintentional change in these steady, changeless mappings Use the mappings to perform a simple lookup public static string GetName(int productId) => ProductNameMappings.TryGetValue(productId, out var name) ? name : string.Empty; UPDATE #1 lets say we have 20 products and 10 of them have the same name. but it takes 20 lines to add them to this dictionary. As it said by QuasiStellar there is no such rule which prevents you to define more than 1 dictionary entry in a single line, like private static readonly ImmutableDictionary<int, string> ProductNameMappings = new Dictionary<int, string> { { Product1, Name1 }, { Product2, Name2 }, { Product3, Name3 }, { Product4, Name4 }, { Product11, Name1 }, { Product12, Name2 }, { Product13, Name3 },{ Product14, Name4 }, }.ToImmutableDictionary(); Or if you have a handful of products which should be mapped to the same name then you can do something like this as well private static readonly Dictionary<int, string> Name1Mappings = new[] { Product1, Product12 , ... }.ToDictionary(p => p, _ => Name1);
{ "domain": "codereview.stackexchange", "id": 44091, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, strings, integer", "url": null }
c#, strings, integer private static readonly ImmutableDictionary<int, string> ProductNameMappings = new Dictionary<int, string> { { Product2, Name2 }, { Product12, Name2 }, ..., } .Union(Name1Mappings) .ToImmutableDictionary();
{ "domain": "codereview.stackexchange", "id": 44091, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, strings, integer", "url": null }
c, time-limit-exceeded Title: LeetCode Daily Problem: Remove adjacent duplicated elements Question: I was doing an exercise from LeetCode in which consisted in repeatedly deleting any adjacent pairs of duplicate elements from a string, until there are only unique characters adjacent to each other. With some help I made a function that can solve most test cases and optimized it a little bit, but the input string length can be up to 10⁵. My solution exceeds the time limit, so I'm in need of some tips on how I can optimize it. My code #include <io.stream> char res[100000]; //[string limit] char * removeDuplicates(char * s){ int lenght = strlen(s); //int that verifies if any char from the string can be deleted int ver = 0; //do while loop that reiterates to eliminate the duplicates do { int j = 0; ver = 0; //for loop that if there are duplicates adds one to ver and deletes the duplicate for (int i = 0; i < lenght ; i++){ if (s[i] == s[i + 1]){ i++; j--; ver++; } else { res[j] = s[i]; } j++; } //copying the res string into the s to redo the loop if necessary strcpy(s,res); lenght = lenght - 2 * ver; //clear the res string for (int k = 0; k < j; k++){ res[k] = '\0'; } } while (ver > 0); return s; } One possible testcase is "abbaca", which should return "ca". The code can't pass a speed test that has a string that has around the limit (10⁵) length; I won't put it here because it's a really big text, but if you want to check it, it is the 104 testcase from the LeetCode Daily Problem. With some help in StackOverflow I did some optimizations like moving the strlen() function out of the loop and removing a memset() call but it is still too slow. Answer: Use proper formatting. This may be very basic, but the impact on readability is hard to overstate.
{ "domain": "codereview.stackexchange", "id": 44092, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, time-limit-exceeded", "url": null }
c, time-limit-exceeded Compile your code with an appropriate warning-level. Trying will weed out many errors, and point out many questionable constructs. main.c:1:10: fatal error: io.stream: No such file or directory 1 | #include <io.stream> | ^~~~~~~~~~~ compilation terminated. main.c: In function 'removeDuplicates': main.c:7:18: warning: implicit declaration of function 'strlen' [-Wimplicit-function-declaration] 7 | int lenght = strlen(s); | ^~~~~~ main.c:1:1: note: include '<string.h>' or provide a declaration of 'strlen' +++ |+#include <string.h> 1 | //#include <stdio.h> main.c:7:18: warning: incompatible implicit declaration of built-in function 'strlen' [-Wbuiltin-declaration-mismatch] 7 | int lenght = strlen(s); | ^~~~~~ main.c:7:18: note: include '<string.h>' or provide a declaration of 'strlen' main.c:31:5: warning: implicit declaration of function 'strcpy' [-Wimplicit-function-declaration] 31 | strcpy(s,res); | ^~~~~~ main.c:31:5: note: include '<string.h>' or provide a declaration of 'strcpy' main.c:31:5: warning: incompatible implicit declaration of built-in function 'strcpy' [-Wbuiltin-declaration-mismatch] main.c:31:5: note: include '<string.h>' or provide a declaration of 'strcpy' /usr/lib/x86_64-linux-gnu/crt1.o: In function `_start': (.text+0x20): undefined reference to `main' collect2: error: ld returned 1 exit status Avoid mutable global state. Just trying to keep in mind all the places it could be modified is a recipe for disaster. And you don't really need it anyway. If you won't modify an argument, make it const. This way you properly document your interface and get the compiler to enforce compliance. In your case, I think you depend on the argument passed being the start of the global, so fix that. Exercise your code with a test-suite. As Knuth famously said: "Beware of bugs in the above code; I have only proved it correct, not tried it.".
{ "domain": "codereview.stackexchange", "id": 44092, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, time-limit-exceeded", "url": null }
c, time-limit-exceeded Returning the passed argument is just about the most useless thing you could do. How about returning the results length instead, as you will have that anyway? There is no reason to copy the rest and start from the beginning after every elimination. Doing so makes for a quadratic algorithm, which is bad. Instead, do one pass eliminating pairs and backing up as needed. size_t removeDuplicates(char* const s) { size_t n = 0; for (char* p = s; *p; ++p) if (n && s[n - 1] == *p) --n; else s[n++] = *p; s[n] = 0; return n; }
{ "domain": "codereview.stackexchange", "id": 44092, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, time-limit-exceeded", "url": null }
python Title: Automate the Boring Stuff Chapter 13 - Spreadsheet to Text Files Question: The project outline: Write a program that performs the tasks of the previous program in reverse order: the program should open a spreadsheet and write the cells of column A into one text file, the cells of column B into another text file, and so on. My solution: # A program to read a spreadsheet and write it to a text file with one text file per column # Usage: python spreadsheet_to_text.py "spreadsheet path" "folder to save .txt files" import sys, openpyxl from pathlib import Path from openpyxl.utils import get_column_letter def main(spreadsheet_path, save_folder): workbook = openpyxl.load_workbook(spreadsheet_path) sheet = workbook.active for column_index in range(1, sheet.max_column + 1): file_path = save_folder / f"Text for column {get_column_letter(column_index)}.txt" with open(file_path, "w", encoding="utf-8") as text_file: for row_index in range(1, sheet.max_row + 1): cell = sheet.cell(row=row_index, column=column_index) if not cell.value: text_file.write("\n") else: text_file.write(str(cell.value) + "\n") if __name__ == "__main__": spreadsheet_path = Path(sys.argv[1]) # The location of the spreadsheet to open save_folder = Path(sys.argv[2]) # The path of the folder to save the .txt files in main(spreadsheet_path, save_folder) I decided to copy the formulas themselves rather than the result because the outline doesn't specify and the chapter doesn't discuss it.
{ "domain": "codereview.stackexchange", "id": 44093, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python Answer: Use PEP8 to format your code. Two blank lines between functions, and two between imports and the first function (main). In the main function, save_folder seems to be a Path object, but that's not obvious from reading the code until you use the / notation. Maybe use the type hints in the function definition. def main(spreadsheet_path: Path, save_folder: Path): # Your code here Your main function is crowded--add in blank lines (e.g. before the outermost for loop) to make it easier to read. It's possible for things like the file open to fail, if, for example, the program does not have the necessary permissions--consider using a try-except block to handle such cases. It's possible your main function could be simplified using pandas, unless you were not allowed. The main code should check that you have 2 arguments passed to begin with, that the paths exist, and other such conditions.
{ "domain": "codereview.stackexchange", "id": 44093, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
javascript, ecmascript-6 Title: Filter the array of values from array of another value Question: I am doing the filter declaring a final array. it seems that the codes are much. it can be shortened? code : const lookup = [ { hfsUserCountryId: 2895, countryCd: 140, }, { hfsUserCountryId: 2895, countryCd: 1301, }, ]; const countries = [ { "defaultOrder" : 0, "label" : "data.Code.Country_Cd.Code_Desc.US", "codeId" : 140, "code" : "US", "codeDesc" : "USA", "codeQualifier" : "Country_Cd" }, { "defaultOrder" : null, "label" : "data.Code.Country_Cd.Code_Desc.AE", "codeId" : 1301, "code" : "AE", "codeDesc" : "United Arab Emirates", "codeQualifier" : "Country_Cd" }, { "defaultOrder" : 1, "label" : "data.Code.Country_Cd.Code_Desc.AL", "codeId" : 1086, "code" : "AL", "codeDesc" : "Albania", "codeQualifier" : "Country_Cd" }, { "defaultOrder" : null, "label" : "data.Code.Country_Cd.Code_Desc.DZ", "codeId" : 2615, "code" : "DZ", "codeDesc" : "Algeria", "codeQualifier" : "Country_Cd" } ]; const final = [] const result = countries.filter(item =>{ const {codeId} = item; const r = lookup.filter(look => { if( look.countryCd === codeId){ final.push(item) } } ); }); console.log('reuslt', final); Live Demo Answer: If you also want to improve performance. And that should only concern you if the lookup array is actually much larger than the one you provided. Consider converting the lookup array to a lookup map where keys would be the value of countryCd (or possibly create just a set of all countryCd values). Then you can do: const codeIds = new Set(lookup.map((v) => v.countryCd)) const final = countries.filter((c) => codeIds.has(c.codeId)) Let m be the size of lookup array and n be the size of countries array. Time complexity of your original code, as well as @An Nguyen's, is O(n × m). My version is O(n + m).
{ "domain": "codereview.stackexchange", "id": 44094, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, ecmascript-6", "url": null }
c++, performance, recursion, comparative-review, mathematics Title: Recursively calculating powers by squaring Question: Consider the following function that implements optimised O(log n) exponentiation by squaring: #include <cstdint> // uintmax // log-n optimised integer power function. Computes x to the power of y constexpr std::uintmax_t pow(std::uintmax_t x, std::uintmax_t y) { // base cases for efficiency and guaranteed termination switch (y) { case 0: return 1; case 1: return x; case 2: return x * x; case 3: return x * x * x; } // OTHERWISE: std::uintmax_t square_root = pow(x, y / 2); // otherwise, work out if y is a multiple of 2 or not if (y % 2 == 0) { return square_root * square_root; } else { return square_root * square_root * x; } } The base cases switch could be rewritten to take advantage of deliberate fallthrough between the various cases to "aggregate" the exponentiation of x from the 0th up to the 3rd power: // log-n optimised integer power function. Computes x to the power of y constexpr std::uintmax_t pow(std::uintmax_t x, std::uintmax_t y) { // base cases for efficiency and guaranteed termination std::uintmax_t result = 1; switch (y) { case 3: result *= x; [[fallthrough]]; case 2: result *= x; [[fallthrough]]; case 1: result *= x; [[fallthrough]]; case 0: return result; } // OTHERWISE: std::uintmax_t square_root = pow(x, y / 2); // otherwise, work out if y is a multiple of 2 or not if (y % 2 == 0) { return square_root * square_root; } else { return square_root * square_root * x; } }
{ "domain": "codereview.stackexchange", "id": 44095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, recursion, comparative-review, mathematics", "url": null }
c++, performance, recursion, comparative-review, mathematics Now, I am aware that the general consensus is that such use of fallthrough in a switch-case is seen as a cardinal sin. I am also aware that the function would work if base cases were provided for just the zeroth and first power (or even just for the zeroth!). The reason I provide base cases up to the third is that it feels just a bit of a waste of a function call to recur into to calculate such simple powers, although perhaps to the third power is a bit overkill..? So my question is primarily: Is such use of deliberate fallthrough justifiable here, or could it be justifiable for a similarly-structured example that's a bit more elaborate than chaining multiplication but which still has the commutative chaining as a property? Secondarily: What do you think about the number of base cases provided here? Is this astute use of deliberately avoiding recursive calls for such simple cases, or is it premature optimisation? Answer: Firstly, I wouldn't call the function pow - that's confusingly similar to std::pow, which can be invoked with the same arguments. In both cases, I expect the usual (iterative) binary exponentiation to be both faster and easier for readers to follow than this recursive implementation. Given that the question tags mention performance is important, I encourage you to benchmark both recursive and iterative functions. Here's a simple implementation of the iterative method: #include <concepts> template<typename T> constexpr T unit_value = 1; // Return xⁿ // If calculation overflows, behaviour may be undefined! template<typename T> constexpr auto ipow(const T x, std::unsigned_integral auto n) requires requires(T t) { t *= t; } { auto result = unit_value<T>; for (auto y = x; true; y *= y) { if (n % 2 == 1) { result *= y; } if ((n /= 2) == 0) { break; } } return result; }
{ "domain": "codereview.stackexchange", "id": 44095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, recursion, comparative-review, mathematics", "url": null }
c++, performance, recursion, comparative-review, mathematics The infinite loop with break is used rather than testing n > 0 in the for condition to avoid an unnecessary y *= y in the last iteration. I provided the unit_value template so that it can be used with non-arithmetic types (complex numbers, square matrices, etc) by specialising that value with the appropriate multiplicative identity. For example: #include <complex> template<typename T> constexpr std::complex<T> unit_value<std::complex<T>> = {1, 0}; (This one isn't strictly needed, since there's implicit conversion from T to complex<T>, but it demonstrates the point).
{ "domain": "codereview.stackexchange", "id": 44095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, recursion, comparative-review, mathematics", "url": null }
ballerina Title: Joining data of two record types Question: The code combines data from two Ballerina table data structures. The program prints the following expected and correct results (edited for readability): [ {"fooId":1,"barId":2,"data":"foo 1;bar 2"}, {"fooId":1,"barId":4,"data":"foo 1;bar 4"}, {"fooId":3,"barId":4,"data":"foo 3;bar 4"}, {"fooId":3,"barId":6,"data":"foo 3;bar 6"}, {"fooId":5,"barId":6,"data":"foo 5;bar 6"} ] However I'm looking here other ways to implement/improve the data join as I feel this way is a rather clumsy (3 foreach loops and 1 query expression). I had several failed attempts to use a single query expression that IMO is the idiomatic Ballerina way. Note that answers that modify the record definitions can not be accepted. I'm aware of an option to refactor the relationships to an associative (or junction) table as I would do in the database but unfortunately, it's not an option in this case (the record definitions can't be changed). This is Ballerina 2201.2.0 (Swan Lake Update 2) import ballerina/io; // the record definitions can't be changed type Foo record {| readonly int id; string data; int[] barIds; |}; type FooTable table<Foo> key(id); type Bar record {| readonly int id; string data; |}; type BarTable table<Bar> key(id); public function main() { FooTable foos = table [ {id: 1, data: "foo 1", barIds: [2, 4]}, {id: 3, data: "foo 3", barIds: [4, 6]}, {id: 5, data: "foo 5", barIds: [6]} ]; BarTable bars = table [ {id: 2, data: "bar 2"}, {id: 4, data: "bar 4"}, {id: 6, data: "bar 6"} ]; table<record {|int fooId; int barId; string data;|}> fooBars = table []; // the code below can be changed foreach var foo in foos { table <record {|int id;|}> barIds = table []; foreach var barId in foo.barIds { barIds.add({id: barId}); }
{ "domain": "codereview.stackexchange", "id": 44096, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "ballerina", "url": null }
ballerina var temps = from var barId in barIds join var bar in bars on barId.id equals bar.id select { fooId: foo.id, barId: barId.id, data: string`${foo.data};${bar.data}` } ; foreach var temp in temps { fooBars.add(temp); } } io:println(fooBars); Answer: You can do the combining part like this: table<record {|int fooId; int barId; string data;|}> fooBars2 = table key(fooId, barId) from var foo in foos from var barId in foo.barIds where bars.hasKey(barId) let Bar bar = bars.get(barId) select { fooId: foo.id, barId: barId, data: foo.data + ";" + bar.data }; Here we use nested from clauses where the inner from clause will iterate over the barIds in a Foo record.
{ "domain": "codereview.stackexchange", "id": 44096, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "ballerina", "url": null }
python, python-3.x Title: Order a string of colors by the last element which is an integer Question: I have solved the coding problem written here. In summary: Input: str = "red2 blue5 black4 green1 gold3" Output: "green red gold black blue" Here is my code: def order_color(str1): #Split string using the whitespaces and send to a list #Sort elements within the list by the number str2 = sorted(str1.split(), key=lambda color: color[-1]) #Convert the list to a string and erase the number str3 = ' '.join([str(colo[: -1]) for colo in str2]) return str3 Is there a way to make the code more elegant, "pythonic" (Ex. To impress a MAANG inteviewer). Thanks Answer: Comments Don't use comments to describe what your code does. Any developer can see that by reading the code itself. Comments are there to clarify why your codes does certain things if that is not immediately clear. Docstrings In order to document your code, use docstrings on modules, classes and functions. Type hints Using type hints can simplify determining the parameter and return types of functions. Use existing library code It might not be a big deal in your case, but lambda color: color[-1] can be substituted by using operator.itemgetter. Useless casting The casting to a string at str(colo[: -1]) is unnecessary, since slicing a str will return a str again. Useless comprehension You don't need to create a list in a comprehension at ' '.join([str(colo[: -1]) for colo in str2]). str.join will happily take a generator expression. Useless local variable Assigning an expression to str3 and then immediately returning it is useless. Just return the expression instead. Naming I hope we can all agree, that str{1,2,3} are suboptimal names. Call variables for what they represent. Putting it together: from operator import itemgetter
{ "domain": "codereview.stackexchange", "id": 44097, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x def order_colors(colors: str) -> str: """Order a whitespace separated string of colors ending with an single digit index by that index and return a string of the ordered colors without that index. """ return ' '.join( color[:-1] for color in sorted(colors.split(), key=itemgetter(-1)) )
{ "domain": "codereview.stackexchange", "id": 44097, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
haskell, unit-testing, mocks Title: Unit testing and alternative to mocking in Haskell Question: Let's say you have a simple pure function that applies a discount of 30% if the total price of a list of Items is over 30.00 (let's not delve into the fact that I'm using a Float to indicate the price): promoGet30PercentOff :: [Item] -> Float promoGet30PercentOff xs | total > 30.0 = total * 0.7 | otherwise = total where total = sum $ map itemPrice xs and Item and itemPrice are defined as follows: data Item = Apple | Banana deriving Show itemPrice :: Item -> Float itemPrice x = case x of Apple -> 5.9 Banana -> 3.0 I'd now like to test promoGet30PercentOff at the boundary. As I come from Python, my natural reaction would be to mock Item and create some that are priced at 30.0, 30.1 and 0.0, for instance. I believe, this is not possible in Haskell (but correct me if I'm wrong). How would you go about it then? Answer: You can untangle your promo function from the Item data type promoGet30PercentOffWith :: (a -> Float) -> [a] -> Float promoGet30PercentOffWith price xs | total > 30.0 = total * 0.7 | otherwise = total where total = sum $ map price xs promoGet30PercentOff :: [Item] -> Float promoGet30PercentOff = promoGet30PercentOffWith itemPrice Because promoGet30PercentOffWith is polymorphic, there is a free theorem that all functions of its type satisfy: promoGet30PercentOffWith f xs = promoGet30PercentOffWith id (map f xs) This means that the general behavior of that function is entirely determined by its specialized behavior when the first argument is id---so the list argument has type [Float]. Thus, mocking items with artificial prices is as simple as giving the list of prices to the function. shouldPromo :: [Float] -> IO () shouldPromo xs = promoGet30PercentOffWith id xs === sum xs * 0.7 shouldNotPromo :: [Float] -> IO () shouldNotPromo xs = promoGet30PercentOffWith id xs === sum xs
{ "domain": "codereview.stackexchange", "id": 44098, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "haskell, unit-testing, mocks", "url": null }
haskell, unit-testing, mocks shouldNotPromo :: [Float] -> IO () shouldNotPromo xs = promoGet30PercentOffWith id xs === sum xs (===) :: Eq a => a -> a -> IO () x === y = if x == y then return () else error "assertion failed" test :: IO () test = do shouldPromo [30.1] shouldNotPromo [30.0] shouldNotPromo [0]
{ "domain": "codereview.stackexchange", "id": 44098, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "haskell, unit-testing, mocks", "url": null }
python, object-oriented, tkinter, gui Title: TKinter using OOP approach Question: I'm starting to build an application for automated network troubleshooting. It's going without any issues so far. I'm using an OOP approach @ which i create the widgets in the init method. what's bothering me is that when the application starts getting more complex (Ex: Adding way more widgets); the init method will get more crowded limiting the visibility of the code. Is there a better way to create the widgets without crowding the init() method? from tkinter import * import customtkinter class App(customtkinter.CTk): def __init__(self): super().__init__() self.title("Automated TShooting Application") self.geometry("587x450+500+50") self.iconbitmap("Sharingan.ico") self.resizable(False, False) self.mainframe = customtkinter.CTkFrame(self, width=400, height=400) self.mainframe.grid(row=0, column=0, padx=20, pady=(20, 20)) self.username_label = customtkinter.CTkLabel(self.mainframe, text="Username") self.username_label.grid(row=0, column=0, padx=20, pady=(20, 0)) self.username_entry = customtkinter.CTkEntry(self.mainframe) self.username_entry.grid(row=1, column=0, padx=20) self.password_label = customtkinter.CTkLabel(self.mainframe, text="Password") self.password_label.grid(row=2, column=0) self.password_entry = customtkinter.CTkEntry(self.mainframe) self.password_entry.grid(row=3, column=0, padx=20, pady=(0, 20)) if __name__ == "__main__": customtkinter.set_appearance_mode("light") app = App() app.mainloop()
{ "domain": "codereview.stackexchange", "id": 44099, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, object-oriented, tkinter, gui", "url": null }
python, object-oriented, tkinter, gui app = App() app.mainloop() Answer: Using classes in the code doesn't automatically make it OOP. In this case you're not using any of its advantages (encapsulation, inheritance, polymorphism, composition, etc.) so there is no point in having all those labels and entries as fields of the App class. Generally, if you're planning on expanding the app, it would be a good idea to extract LoginForm and PasswordForm into their own classes. However I'm not sure if the library you're using allows that. Even the "complex example" written by the author(!) of the lib uses the wall-of-text approach, so it doesn't look like OOP approach is even supported.
{ "domain": "codereview.stackexchange", "id": 44099, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, object-oriented, tkinter, gui", "url": null }
collections, c++20, circular-list Title: A not so simple C++20 circular queue Question: This container reduces the number of memory allocations on queue-type operations (push + pop) compared to std::deque. Basic performance tests indicates a performance similar to std::deque where main cost is the calculation of index ((mFront+pos)%mReserved). A first review was done by G.Sliepen. I tried to solve almost all reported issues and replaced the system-managed memory (based on std::unique_ptr) by a user-managed memory. The big game started. Playing with soap in the prison shower! Great chances that mistakes or errors are presents in the code. I will appreciate you comments and suggestions. Here is cqueue.hpp #pragma once #include <memory> #include <limits> #include <utility> #include <concepts> #include <algorithm> #include <stdexcept> namespace gto { /** * @brief Circular queue. * @details Iterators are invalidated by: * push(), push_front(), emplace(), pop(), pop_back(), reserve(), * shrink_to_fit(), reset() and clear(). * @see https://en.wikipedia.org/wiki/Circular_buffer * @see https://github.com/torrentg/cqueue * @note This class is not thread-safe. * @version 1.0.0 */ template<std::copyable T, typename Allocator = std::allocator<T>> class cqueue { public: // declarations // Aliases using value_type = T; using reference = value_type &; using const_reference = const value_type &; using pointer = T *; using const_pointer = const pointer; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using allocator_type = Allocator; using const_alloc_reference = const allocator_type &;
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list //! cqueue iterator. class iterator { public: using iterator_category = std::random_access_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = value_type *; using reference = value_type &; private: cqueue *queue = nullptr; difference_type pos = 0; private: size_type cast(difference_type n) const { return (n < 0 ? queue->size() : static_cast<size_type>(n)); } difference_type size() const { return static_cast<difference_type>(queue->size()); } public: explicit iterator(cqueue *o, difference_type p = 0) : queue(o), pos(p < 0 ? -1 : (p < size() ? p : size())) {} reference operator*() { return queue->operator[](cast(pos)); } pointer operator->() { return &(queue->operator[](cast(pos))); } reference operator[](difference_type rhs) const { return (queue->operator[](cast(pos + rhs))); } bool operator==(const iterator &rhs) const { return (queue == rhs.queue && pos == rhs.pos); } bool operator!=(const iterator &rhs) const { return (queue != rhs.queue || pos != rhs.pos); } bool operator >(const iterator &rhs) const { return (queue == rhs.queue && pos > rhs.pos); } bool operator <(const iterator &rhs) const { return (queue == rhs.queue && pos < rhs.pos); } bool operator>=(const iterator &rhs) const { return (queue == rhs.queue && pos >= rhs.pos); } bool operator<=(const iterator &rhs) const { return (queue == rhs.queue && pos <= rhs.pos); } iterator& operator++() { pos = (pos + 1 < size() ? pos + 1 : size()); return *this; } iterator& operator--() { pos = (pos < 0 ? -1 : pos -1); return *this; } iterator operator++(int) { iterator tmp(queue, pos); operator++(); return tmp; } iterator operator--(int) { iterator tmp(queue, pos); operator--(); return tmp; }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list iterator operator--(int) { iterator tmp(queue, pos); operator--(); return tmp; } iterator& operator+=(difference_type rhs) { pos = (pos + rhs < size() ? pos + rhs : size()); return *this; } iterator& operator-=(difference_type rhs) { pos = (pos - rhs < 0 ? -1 : pos - rhs); return *this; } iterator operator+(difference_type rhs) const { return iterator(queue, pos + rhs); } iterator operator-(difference_type rhs) const { return iterator(queue, pos - rhs); } friend iterator operator+(difference_type lhs, const iterator &rhs) { return iterator(rhs.queue, lhs + rhs.pos); } friend iterator operator-(difference_type lhs, const iterator &rhs) { return iterator(rhs.queue, lhs - rhs.pos); } difference_type operator-(const iterator &rhs) const { return (pos - rhs.pos); } };
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list //! cqueue const iterator. class const_iterator { public: using iterator_category = std::random_access_iterator_tag; using value_type = const T; using difference_type = std::ptrdiff_t; using pointer = value_type *; using reference = value_type &; private: const cqueue *queue = nullptr; difference_type pos = 0; private: size_type cast(difference_type n) const { return (n < 0 ? queue->size() : static_cast<size_type>(n)); } difference_type size() const { return static_cast<difference_type>(queue->size()); } public: explicit const_iterator(const cqueue *o, difference_type p = 0) : queue(o), pos(p < 0 ? -1 : (p < size() ? p : size())) {} reference operator*() { return queue->operator[](cast(pos)); } pointer operator->() { return &(queue->operator[](cast(pos))); } reference operator[](difference_type rhs) const { return (queue->operator[](cast(pos + rhs))); } bool operator==(const const_iterator &rhs) const { return (queue == rhs.queue && pos == rhs.pos); } bool operator!=(const const_iterator &rhs) const { return (queue != rhs.queue || pos != rhs.pos); } bool operator >(const const_iterator &rhs) const { return (queue == rhs.queue && pos > rhs.pos); } bool operator <(const const_iterator &rhs) const { return (queue == rhs.queue && pos < rhs.pos); } bool operator>=(const const_iterator &rhs) const { return (queue == rhs.queue && pos >= rhs.pos); } bool operator<=(const const_iterator &rhs) const { return (queue == rhs.queue && pos <= rhs.pos); } const_iterator& operator++() { pos = (pos + 1 < size() ? pos + 1 : size()); return *this; } const_iterator& operator--() { pos = (pos < 0 ? -1 : pos -1); return *this; } const_iterator operator++(int) { const_iterator tmp(queue, pos); operator++(); return tmp; }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list const_iterator operator--(int) { const_iterator tmp(queue, pos); operator--(); return tmp; } const_iterator& operator+=(difference_type rhs) { pos = (pos + rhs < size() ? pos + rhs : size()); return *this; } const_iterator& operator-=(difference_type rhs) { pos = (pos - rhs < 0 ? -1 : pos - rhs); return *this; } const_iterator operator+(difference_type rhs) const { return const_iterator(queue, pos + rhs); } const_iterator operator-(difference_type rhs) const { return const_iterator(queue, pos - rhs); } friend const_iterator operator+(difference_type lhs, const const_iterator &rhs) { return const_iterator(rhs.queue, lhs + rhs.pos); } friend const_iterator operator-(difference_type lhs, const const_iterator &rhs) { return const_iterator(rhs.queue, lhs - rhs.pos); } difference_type operator-(const const_iterator &rhs) const { return (pos - rhs.pos); } };
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list private: // static members //! Capacity increase factor. static constexpr size_type GROWTH_FACTOR = 2; //! Default initial capacity (power of 2). static constexpr size_type DEFAULT_RESERVED = 8; private: // members //! Memory allocator. [[no_unique_address]] allocator_type mAllocator; //! Buffer. pointer mData = nullptr; //! Buffer size. size_type mReserved = 0; //! Maximum number of elements (always > 0). size_type mCapacity = 0; //! Index representing first entry (0 <= mFront < mReserved). size_type mFront = 0; //! Number of entries in the queue (empty = 0, full = mReserved). size_type mLength = 0; private: // methods //! Convert from pos to index (throw exception if out-of-bounds). constexpr size_type getCheckedIndex(size_type pos) const noexcept(false); //! Convert from pos to index. constexpr size_type getUncheckedIndex(size_type pos) const noexcept; //! Compute memory size to reserve. constexpr size_type getNewMemoryLength(size_type n) const noexcept; //! Resize buffer. constexpr void resizeIfRequired(size_type n); //! Resize buffer. void resize(size_type n); //! Clear and dealloc memory (preserve capacity and allocator). void reset() noexcept; public: // static methods //! Maximum capacity the container is able to hold. static constexpr size_type max_capacity() noexcept { return (std::numeric_limits<difference_type>::max()); } public: // methods
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list public: // methods //! Constructor. constexpr explicit cqueue(const_alloc_reference alloc = Allocator()) : cqueue(0, alloc) {} //! Constructor (capacity=0 means unlimited). constexpr explicit cqueue(size_type capacity, const_alloc_reference alloc = Allocator()); //! Copy constructor. constexpr cqueue(const cqueue &other); //! Copy constructor with allocator. constexpr cqueue(const cqueue &other, const_alloc_reference alloc); //! Move constructor. constexpr cqueue(cqueue &&other) noexcept { this->swap(other); } //! Move constructor. constexpr cqueue(cqueue &&other, const_alloc_reference alloc); //! Destructor. ~cqueue() noexcept { reset(); }; //! Copy assignment. constexpr cqueue & operator=(const cqueue &other); //! Move assignment. constexpr cqueue & operator=(cqueue &&other) { this->swap(other); return *this; } //! Return container allocator. [[nodiscard]] constexpr allocator_type get_allocator() const noexcept { return mAllocator; } //! Return queue capacity. [[nodiscard]] constexpr size_type capacity() const noexcept { return (mCapacity == max_capacity() ? 0 : mCapacity); } //! Return the number of items. [[nodiscard]] constexpr size_type size() const noexcept { return mLength; } //! Current reserved size (numbers of items). [[nodiscard]] constexpr size_type reserved() const noexcept { return mReserved; } //! Check if there are items in the queue. [[nodiscard]] constexpr bool empty() const noexcept { return (mLength == 0); }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list //! Return the first element. [[nodiscard]] constexpr const_reference front() const { return operator[](0); } //! Return the first element. [[nodiscard]] constexpr reference front() { return operator[](0); } //! Return the last element. [[nodiscard]] constexpr const_reference back() const { return operator[](mLength-1); } //! Return the last element. [[nodiscard]] constexpr reference back() { return operator[](mLength-1); } //! Insert an element at the end. constexpr void push(const T &val); //! Insert an element at the end. constexpr void push(T &&val); //! Insert an element at the front. constexpr void push_front(const T &val); //! Insert an element at the front. constexpr void push_front(T &&val); //! Construct and insert an element at the end. template <class... Args> constexpr void emplace(Args&&... args); //! Remove the front element. constexpr bool pop(); //! Remove the back element. constexpr bool pop_back(); //! Returns a reference to the element at position n. [[nodiscard]] constexpr reference operator[](size_type n) { return mData[getCheckedIndex(n)]; } //! Returns a const reference to the element at position n. [[nodiscard]] constexpr const_reference operator[](size_type n) const { return mData[getCheckedIndex(n)]; }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list //! Returns an iterator to the first element. [[nodiscard]] constexpr iterator begin() noexcept { return iterator(this, 0); } //! Returns an iterator to the element following the last element. [[nodiscard]] constexpr iterator end() noexcept { return iterator(this, static_cast<difference_type>(size())); } //! Returns an iterator to the first element. [[nodiscard]] constexpr const_iterator begin() const noexcept { return const_iterator(this, 0); } //! Returns an iterator to the element following the last element. [[nodiscard]] constexpr const_iterator end() const noexcept { return const_iterator(this, static_cast<difference_type>(size())); } //! Clear content. void clear() noexcept; //! Swap content. constexpr void swap (cqueue &x) noexcept; //! Ensure buffer size. constexpr void reserve(size_type n); //! Shrink reserved memory to current size. constexpr void shrink_to_fit(); }; } // namespace gto /** * @param[in] capacity Container capacity. * @param[in] alloc Allocator to use. */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator>::cqueue(size_type capacity, const_alloc_reference alloc) : mAllocator(alloc), mData{nullptr}, mReserved{0}, mCapacity{max_capacity()}, mFront{0}, mLength{0} { if (capacity > max_capacity()) { throw std::length_error("cqueue max capacity exceeded"); } else { mCapacity = (capacity == 0 ? max_capacity() : capacity); } } /** * @param[in] other Queue to copy. */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator>::cqueue(const cqueue &other) : mAllocator{std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.get_allocator())}, mData{nullptr}, mReserved{0}, mCapacity{other.mCapacity}, mFront{0}, mLength{0} { resizeIfRequired(other.mLength); for (size_type i = 0; i < other.size(); ++i) { push(other[i]); } }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list /** * @param[in] other Queue to copy. * @param[in] alloc Allocator to use. */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator>::cqueue(const cqueue &other, const_alloc_reference alloc) : mAllocator{alloc}, mData{nullptr}, mReserved{0}, mCapacity{other.mCapacity}, mFront{0}, mLength{0} { resizeIfRequired(other.mLength); for (size_type i = 0; i < other.size(); ++i) { push(other[i]); } } /** * @param[in] other Queue to copy. * @param[in] alloc Allocator to use */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator>::cqueue(cqueue &&other, const_alloc_reference alloc) : mData{nullptr}, mReserved{0}, mCapacity{max_capacity()}, mFront{0}, mLength{0} { if (alloc == other.mAllocator) { this->swap(other); } else { mAllocator = alloc; mCapacity = other.mCapacity; resizeIfRequired(other.mLength); for (size_type i = 0; i < other.size(); ++i) { push(std::move(other[i])); } other.reset(); other.mCapacity = 0; } } /** * @param[in] other Queue to copy. */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator> & gto::cqueue<T, Allocator>::operator=(const cqueue &other) { if (this != &other) { cqueue tmp(other); this->swap(tmp); } return *this; } /** * @param[in] num Element position. * @return Index in buffer. */ template<std::copyable T, typename Allocator> constexpr typename gto::cqueue<T, Allocator>::size_type gto::cqueue<T, Allocator>::getUncheckedIndex(size_type pos) const noexcept { return ((mFront + pos) % (mReserved == 0 ? 1 : mReserved)); }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list /** * @param[in] num Element position. * @return Index in buffer. * @exception std::out_of_range Invalid position. */ template<std::copyable T, typename Allocator> constexpr typename gto::cqueue<T, Allocator>::size_type gto::cqueue<T, Allocator>::getCheckedIndex(size_type pos) const noexcept(false) { if (pos >= mLength) { throw std::out_of_range("cqueue access out-of-range"); } else { return getUncheckedIndex(pos); } } /** * @details Remove all elements. */ template<std::copyable T, typename Allocator> void gto::cqueue<T, Allocator>::clear() noexcept { for (size_type i = 0; i < mLength; ++i) { size_type index = getUncheckedIndex(i); std::allocator_traits<allocator_type>::destroy(mAllocator, mData + index); } mFront = 0; mLength = 0; } /** * @details Remove all elements and frees memory. */ template<std::copyable T, typename Allocator> void gto::cqueue<T, Allocator>::reset() noexcept { clear(); std::allocator_traits<allocator_type>::deallocate(mAllocator, mData, mReserved); mData = nullptr; mReserved = 0; } /** * @details Swap content with another same-type cqueue. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::swap(cqueue &other) noexcept { if (this == &other) { return; } if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_swap::value) { std::swap(mAllocator, other.mAllocator); } std::swap(mData, other.mData); std::swap(mFront, other.mFront); std::swap(mLength, other.mLength); std::swap(mReserved, other.mReserved); std::swap(mCapacity, other.mCapacity); }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list /** * @brief Compute the new buffer size. * @param[in] n New queue size. */ template<std::copyable T, typename Allocator> constexpr typename gto::cqueue<T, Allocator>::size_type gto::cqueue<T, Allocator>::getNewMemoryLength(size_type n) const noexcept { size_type ret = (mReserved == 0 ? std::min(mCapacity, DEFAULT_RESERVED) : mReserved); while (ret < n) { ret *= GROWTH_FACTOR; } return std::min(ret, mCapacity); } /** * @param[in] n Expected future queue size. * @exception std::length_error Capacity exceeded. * @exception ... Error throwed by move contructors. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::resizeIfRequired(size_type n) { if (n < mReserved) { [[likely]] return; } else if (n > mCapacity) { [[unlikely]] throw std::length_error("cqueue capacity exceeded"); } else { size_type len = getNewMemoryLength(n); resize(len); } } /** * @param[in] n Expected future queue size. * @exception std::length_error Capacity exceeded. * @exception ... Error throwed by move contructors. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::reserve(size_type n) { if (n < mReserved) { return; } else if (n > mCapacity) { throw std::length_error("cqueue capacity exceeded"); } else { resize(n); } } /** * @details Memory is not shrink if current length below DEFAULT_RESERVED. * @exception std::length_error Capacity exceeded. * @exception ... Error throwed by move contructors. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::shrink_to_fit() { if (mLength == 0 || mLength == mReserved || mLength <= DEFAULT_RESERVED) { return; } else { resize(mLength); } }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list /** * @param[in] n New reserved size. * @details Provides strong exception guarantee. * @see https://en.cppreference.com/w/cpp/language/exceptions#Exception_safety * @exception ... Error throwed by move contructors. */ template<std::copyable T, typename Allocator> void gto::cqueue<T, Allocator>::resize(size_type len) { pointer tmp = std::allocator_traits<allocator_type>::allocate(mAllocator, len); if constexpr (std::is_nothrow_move_constructible<T>::value) { // move elements from mData to tmp for (size_type i = 0; i < mLength; ++i) { size_type index = getUncheckedIndex(i); std::allocator_traits<allocator_type>::construct(mAllocator, tmp + i, std::move(mData[index])); } } else { // copy elements from mData to tmp size_type i = 0; try { for (i = 0; i < mLength; ++i) { size_type index = getUncheckedIndex(i); std::allocator_traits<allocator_type>::construct(mAllocator, tmp + i, mData[index]); } } catch (...) { for (size_type j = 0; j < i; ++j) { std::allocator_traits<allocator_type>::destroy(mAllocator, tmp + j); } std::allocator_traits<allocator_type>::deallocate(mAllocator, tmp, len); throw; } } // destroy mData elements for (size_type j = 0; j < mLength; ++j) { size_type index = getUncheckedIndex(j); std::allocator_traits<allocator_type>::destroy(mAllocator, mData + index); } // deallocate mData std::allocator_traits<allocator_type>::deallocate(mAllocator, mData, mReserved); // assign new content mData = tmp; mReserved = len; mFront = 0; }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list // assign new content mData = tmp; mReserved = len; mFront = 0; } /** * @param[in] val Value to add. * @exception std::length_error Number of values exceed queue capacity. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::push(const T &val) { resizeIfRequired(mLength + 1); size_type index = getUncheckedIndex(mLength); std::allocator_traits<allocator_type>::construct(mAllocator, mData + index, val); ++mLength; } /** * @param[in] val Value to add. * @exception std::length_error Number of values exceed queue capacity. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::push(T &&val) { resizeIfRequired(mLength + 1); size_type index = getUncheckedIndex(mLength); std::allocator_traits<allocator_type>::construct(mAllocator, mData + index, std::move(val)); ++mLength; } /** * @param[in] val Value to add. * @exception std::length_error Number of values exceed queue capacity. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::push_front(const T &val) { resizeIfRequired(mLength + 1); size_type index = (mLength == 0 ? 0 : (mFront == 0 ? mReserved : mFront) - 1); std::allocator_traits<allocator_type>::construct(mAllocator, mData + index, val); mFront = index; ++mLength; } /** * @param[in] val Value to add. * @exception std::length_error Number of values exceed queue capacity. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::push_front(T &&val) { resizeIfRequired(mLength + 1); size_type index = (mLength == 0 ? 0 : (mFront == 0 ? mReserved : mFront) - 1); std::allocator_traits<allocator_type>::construct(mAllocator, mData + index, std::move(val)); mFront = index; ++mLength; }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list /** * @param[in] args Arguments of the new item. * @exception std::length_error Number of values exceed queue capacity. */ template<std::copyable T, typename Allocator> template <class... Args> constexpr void gto::cqueue<T, Allocator>::emplace(Args&&... args) { resizeIfRequired(mLength + 1); size_type index = getUncheckedIndex(mLength); std::allocator_traits<allocator_type>::construct(mAllocator, mData + index, std::forward<Args>(args)...); ++mLength; } /** * @return true = an element was erased, false = no elements in the queue. */ template<std::copyable T, typename Allocator> constexpr bool gto::cqueue<T, Allocator>::pop() { if (mLength == 0) { return false; } std::allocator_traits<allocator_type>::destroy(mAllocator, mData + mFront); mFront = getUncheckedIndex(1); --mLength; return true; } /** * @return true = an element was erased, false = no elements in the queue. */ template<std::copyable T, typename Allocator> constexpr bool gto::cqueue<T, Allocator>::pop_back() { if (mLength == 0) { return false; } size_type index = getUncheckedIndex(mLength - 1); std::allocator_traits<allocator_type>::destroy(mAllocator, mData + index); --mLength; return true; } Answer: Tests I'm disappointed that you didn't include the tests in the review - that's usually the best way to see how the code is intended to behave, and to determine whether anything has been overlooked. (I did, exceptionally, pull the the tests from your Git repo, but I obviously can't comment on them as they are not in the review).
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list Iterators Looking through the interface, I see that there are completely separate parallel implementations of iterator and const_iterator. It's possible to use a single implementation for these; the one tricky part is that bit that's currently missing - implicit conversion from iterator to const_iterator - we'll need constraints to ensure that appears in only the one class. The size comparison operators can be reduced to a single <=> (provided your target supports all of C++20). The addition and subtraction operators only test for overflow in one direction, and ignore overflow when adding or subtracting negative values. We can use std::clamp() for constraining the result (and in the constructor). Consider using [[nodiscard]] on the post-increment operators to encourage use of the more efficient pre-increment operators where the result isn't needed. With those changes, I arrived at private: template<typename U> class iter { public: using iterator_category = std::random_access_iterator_tag; using value_type = U; using difference_type = std::ptrdiff_t; using pointer = value_type *; using reference = value_type &; private: friend class iter<std::add_const_t<value_type>>; using size_type = std::size_t; using queue_type = std::conditional_t<std::is_const_v<value_type>, const cqueue, cqueue>; queue_type *queue = nullptr; difference_type pos = 0;
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list queue_type *queue = nullptr; difference_type pos = 0; auto cast(difference_type n) const { return (n < 0 ? queue->size() : static_cast<size_type>(n)); } auto size() const { return static_cast<difference_type>(queue->size()); } auto clamp(difference_type p) const { return std::clamp<difference_type>(p, -1, size()); } public: explicit iter(queue_type *o, difference_type p = 0) : queue{o}, pos{clamp(p)} {} iter(const iter<std::remove_const_t<value_type>>& other) requires std::is_const_v<value_type> : queue{other.queue}, pos{other.pos} {} iter(const iter<value_type>& other) = default; reference operator*() { return queue->operator[](cast(pos)); } pointer operator->() { return &(queue->operator[](cast(pos))); } reference operator[](difference_type rhs) const { return queue->operator[](cast(pos + rhs)); }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list auto operator<=>(const iter &rhs) const { return queue == rhs.queue ? pos <=> rhs.pos : std::partial_ordering::unordered; } iter& operator++() { return *this += 1; } iter& operator--() { return *this += -1; } [[nodiscard]] iter operator++(int) { iter tmp{queue, pos}; ++*this; return tmp; } [[nodiscard]] iter operator--(int) { iter tmp{queue, pos}; --*this; return tmp; } auto& operator+=(difference_type rhs) { pos = clamp(pos + rhs); return *this; } auto& operator-=(difference_type rhs) { pos = clamp(pos - rhs); return *this; } auto operator+(difference_type rhs) const { return iter{queue, pos + rhs}; } auto operator-(difference_type rhs) const { return iter{queue, pos - rhs}; } friend iter operator+(difference_type lhs, const iter &rhs) { return iter{rhs.queue, lhs + rhs.pos}; } friend iter operator-(difference_type lhs, const iter &rhs) { return iter{rhs.queue, lhs - rhs.pos}; } auto operator-(const iter &rhs) const { return pos - rhs.pos; } }; public: using iterator = iter<T>; using const_iterator = iter<const T>;
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list public: using iterator = iter<T>; using const_iterator = iter<const T>; Queue interface We seem to have a mix of snake_case and camelCase identifiers. Prefer to stick with a single convention - since this looks like a standard container, I recommend snake_case to match the standard container functions. I don't think [[nodiscard]] adds value anywhere you've used it. All those functions are idempotent, and the discarded value can be recomputed at any time. Prefer to reserve this attribute for functions where ignoring the result will lead to program misbehaviour (the canonical example is std::scanf() - the return value is the only way to know whether the pointers were written to, and there's no way to recover that information if it's ignored). Consider adding cbegin() and cend() and also the reversed begin/end iterator functions. It's a good idea to initialise all fields, even if default initialisation will do what we want. For example: constexpr cqueue(cqueue &&other) noexcept { this->swap(other); } g++ -Weffc++ wants us to initialise mAllocator in this constructor. That's easily done using a default initialiser: allocator_type mAllocator = {}; I don't think we need to overload functions such as push() - if we accept our argument by value, then std::move() it into place, we should be able to avoid unnecessary copies: template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::push(T val) { resizeIfRequired(mLength + 1); size_type index = getUncheckedIndex(mLength); std::allocator_traits<allocator_type>::construct(mAllocator, mData + index, std::move(val)); ++mLength; } We're missing a public resize(), but have a private resize() that does something different from standard containers' resize(). I suggest renaming this, and possibly implementing the expected resize().
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }
collections, c++20, circular-list Implementation (general) I see we're using std::allocator_traits<allocator_type> quite a lot in the implementation; it probably makes sense to make a private alias for this. Constructors We have quite a lot of duplication. For example: /** * @param[in] other Queue to copy. */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator>::cqueue(const cqueue &other) : mAllocator{std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.get_allocator())}, mData{nullptr}, mReserved{0}, mCapacity{other.mCapacity}, mFront{0}, mLength{0} { resizeIfRequired(other.mLength); for (size_type i = 0; i < other.size(); ++i) { push(other[i]); } } /** * @param[in] other Queue to copy. * @param[in] alloc Allocator to use. */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator>::cqueue(const cqueue &other, const_alloc_reference alloc) : mAllocator{alloc}, mData{nullptr}, mReserved{0}, mCapacity{other.mCapacity}, mFront{0}, mLength{0} { resizeIfRequired(other.mLength); for (size_type i = 0; i < other.size(); ++i) { push(other[i]); } } Instead of writing out that body twice, one constructor can simply forward to the other: /** * @param[in] other Queue to copy. */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator>::cqueue(const cqueue &other) : cqueue{other, allocator_traits::select_on_container_copy_construction(other.get_allocator())} { } /** * @param[in] other Queue to copy. * @param[in] alloc Allocator to use. */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator>::cqueue(const cqueue &other, const_alloc_reference alloc) : mAllocator{alloc}, mCapacity{other.mCapacity} { resizeIfRequired(other.mLength); for (size_type i = 0; i < other.size(); ++i) { push(other[i]); } }
{ "domain": "codereview.stackexchange", "id": 44100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "collections, c++20, circular-list", "url": null }