text
stringlengths
1
2.12k
source
dict
php, strings, regex Are there any flaws with this regex and are there foreseeable issues where it would fail with what I need? Is there a way to simplify it further? Any other assumptions I should be making because this comes from user-input? I'm a little unsure of the '\Ks, but it made it so that I only got the 4 parts I needed (i.e. no whitespace in between groups was also matched on (regardless of being captured) Answer: I've gone back to the drawing board with your pattern. I personally never use named capture groups in PHP because they only bloat the pattern and the output array. If you need named keys, just assign them from the matches array. When using pattern modifier i, you don't need to list upper and lower case letters in your character class. There is no benefit to your pattern by inserting \K to restart the fullstring match -- just omit those. Use non-capturing groups and the zero or one quantifier to make subsequent capture groups optional. Instead of using .*? to lazily match the LINE data, match non-whitespace characters delimited by one or more whitespaces -- this will improve pattern performance by reducing the amount of backtracking that is necessary. Instead of loosely validating a predictable LINE_DATA substring pattern with [\d\s,\(\)]+?, explicitly validate each delimited segment of that group. This improves the validation strength of your pattern. Admittedly, my linebreaks, subpattern tabbing, and inline commenting is excessively long and wide -- certainly violating PSR-12 guidelines. This is a sacrifice that I am making to explain in great detail how the pattern works. Few development teams are 100% comprised of regex gurus, so it is important that you aim to inform the weakest regex user who might read your script. I often include a link to a regex101.com demo with a battery of test cases in my professional projects because I want my team to be very sure about how it works and how extensively it was tested.
{ "domain": "codereview.stackexchange", "id": 42941, "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": "php, strings, regex", "url": null }
php, strings, regex Working Code (Demo) Regex101 Demo $regex = <<<REGEX ~ ^ # start of string anchor (CONF|ESD|TRACKING) # start capture group 1 KEY, three literal words (?: # start non-capturing group 1 \h*[:;'\h]\h* # require a listed punctuation or space with optional leading or trailing spaces (\S+(?:\h+\S+)*?) # start capture group 2 LINE, require one or more non-whitespace characters then lazily match zero or more repetitions of whitespace then non-whitespace substrings (?: # start non-capturing group 2 \h*L\h*[:;'\h]\h* # require literal L then a listed punctuation or space with optional leading or trailing spaces ( # start capture group 3 LINE_DATA (?:\d+(?:\(\d+\))?) # require a number optionally followed by another number in parentheses (?:\h*,\h*\d+(?:\(\d+\))?)* # optionally match zero or more repetitions of the previous expression if separated by an optionally space-padded comma ) # end capture group 3 and make it optional )? # end non-capturing group 2 (?: # start non-capturing group 3 \h* # match zero or more whitespaces ( # start capture group 4 INITIALS \*[.a-z]+ # match literal asterisk, then one or more dots and letters ) # end capture group 4 )? # end non-capturing group 3 and make it optional )? # end non-capturing group 2 and make it optional \h* # allow trailing whitespaces $ # end of string anchor ~ix REGEX;
{ "domain": "codereview.stackexchange", "id": 42941, "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": "php, strings, regex", "url": null }
php, strings, regex $tests = [ "esd hedf L:1,2,3 *sm ", "CONF: FEDEX 12345 L: 12(2),2(9),32 *SM", "Tracking *cool", "ESD: 12/12/92 L: ", "tRacking' my data L: 1,2,3(4) ", "conf something *asterisk", "tracking", "ConF''' something '' L: 6", "esd test 24(7)", ]; foreach ($tests as $i => $test) { if (preg_match($regex, $test, $m, PREG_UNMATCHED_AS_NULL)) { var_export([ "test index" => $i, "KEY" => $m[1], "LINE" => $m[2] ?? null, "LINE_DATA" => $m[3] ?? null, "INITIALS" => $m[4] ?? null ]); echo "\n"; } } Output: array ( 'test index' => 0, 'KEY' => 'esd', 'LINE' => 'hedf', 'LINE_DATA' => '1,2,3', 'INITIALS' => '*sm', ) array ( 'test index' => 1, 'KEY' => 'CONF', 'LINE' => 'FEDEX 12345', 'LINE_DATA' => '12(2),2(9),32', 'INITIALS' => '*SM', ) array ( 'test index' => 2, 'KEY' => 'Tracking', 'LINE' => '*cool', 'LINE_DATA' => NULL, 'INITIALS' => NULL, ) array ( 'test index' => 3, 'KEY' => 'ESD', 'LINE' => '12/12/92 L:', 'LINE_DATA' => NULL, 'INITIALS' => NULL, ) array ( 'test index' => 4, 'KEY' => 'tRacking', 'LINE' => 'my data', 'LINE_DATA' => '1,2,3(4)', 'INITIALS' => NULL, ) array ( 'test index' => 5, 'KEY' => 'conf', 'LINE' => 'something', 'LINE_DATA' => NULL, 'INITIALS' => '*asterisk', ) array ( 'test index' => 6, 'KEY' => 'tracking', 'LINE' => NULL, 'LINE_DATA' => NULL, 'INITIALS' => NULL, ) array ( 'test index' => 7, 'KEY' => 'ConF', 'LINE' => '\'\' something \'\'', 'LINE_DATA' => '6', 'INITIALS' => NULL, ) array ( 'test index' => 8, 'KEY' => 'esd', 'LINE' => 'test 24(7)', 'LINE_DATA' => NULL, 'INITIALS' => NULL, )
{ "domain": "codereview.stackexchange", "id": 42941, "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": "php, strings, regex", "url": null }
python Title: Julian Date Distance Calculator (First Project) Question: I have watched a few youtube videos, and I am trying to learn a little bit more by doing. I had a blast trying to figure this out. I know it has issues such as not being able to go below 2001 and using an average for months. I'm not seeking to improve its capabilities, although i would certainly appreciate any ideas, seeking a review of the code and ways to improve. Thank you! The code works sd = input("Starting Julien Date (Enter as '00-000')") ed = input("Ending Julian Date (Enter as '00-000')") # This section gives you days from sd to ed cy = int(ed[:2]) cd = int(ed[3:]) subyear = int(sd[:2]) yeardaycount = (cy - subyear) * 365 subdays = int(sd[3:]) daycount = cd - subdays finalcount = yeardaycount + daycount # This breaks the Finalcount into day, month, year. y = finalcount / 365 y = int(y) m = (finalcount - (y * 365)) / 30.4166666667 m = int(m) d = finalcount - ((y * 365) + (m * 30.4166666667)) d = int(d) print("From %s to %s, ~on average~, it has beeen %s days, %s months, and %s years." % (sd, ed, d, m, y)) Answer: Apply datetime — Basic date and time types and third-party package dateutil as follows (given a script with hard-coded initial values): sd = '03-023' # input("Starting Julien Date (Enter as 'yy-ddd')") ed = '22-088' # input("Ending Julian Date (Enter as 'yy-ddd')") # This section gives you days from sd to ed cy = int(ed[:2]) cd = int(ed[3:]) subyear = int(sd[:2]) yeardaycount = (cy - subyear) * 365 subdays = int(sd[3:]) daycount = cd - subdays finalcount = yeardaycount + daycount # This breaks the Finalcount into day, month, year. y = finalcount / 365 y = int(y) m = (finalcount - (y * 365)) / 30.4166666667 m = int(m) d = finalcount - ((y * 365) + (m * 30.4166666667)) d = int(d) print("From %s to %s, ~on average~, it has beeen %s days, %s months, and %s years." % (sd, ed, d, m, y)) ### using libraries: from datetime import datetime from dateutil import relativedelta
{ "domain": "codereview.stackexchange", "id": 42942, "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 ### using libraries: from datetime import datetime from dateutil import relativedelta date_a = datetime.strptime( sd, "%y-%j") date_b = datetime.strptime( ed, "%y-%j") diff = relativedelta.relativedelta( date_b, date_a) ms = diff.months ys = diff.years ds = diff.days print("From %s to %s, ~ exactly~, it has beeen %s days, %s months, and %s years." % (sd, ed, ds, ms, ys)) Output: .\CR\273990.py From 03-023 to 22-088, ~on average~, it has beeen 4 days, 2 months, and 19 years. From 03-023 to 22-088, ~ exactly~, it has beeen 6 days, 2 months, and 19 years.
{ "domain": "codereview.stackexchange", "id": 42942, "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 }
html, css Title: Default CSS styling to use with new projects Question: I have a set of default styles I use with new projects and want to know whether there are any issues or imperfections with them. Can anyone see anything that could be detrimental or bad in any way? Be as picky as you like. * { margin: 0; padding: 0; box-sizing: border-box; } html { font-size: 62.5% /* makes 1rem 10px */ } body { font-size: 1.6em; /* default font of 16px */ font-family: 'Verdana', 'Arial', sans-serif; line-height: 1.3; color: #373737; } /* fonts */ h1 { font-size: 3rem } h2 { font-size: 2.4rem } h3 { font-size: 2rem } h4, li, label, input, textarea, select, p { font-size: 1.8rem; } h5 { font-size: 1.6rem } h6 { font-size: 1.4rem } ol, ul { padding-left: 2em } a { text-decoration: underline; color: blue; } a:hover { color: pink } a:focus { color: orange } a:active { color: red } a:visited { color: purple } Additionally I may also add the following: button, textarea, input, select, label { all: unset } I'd be curious to know your thoughts or any feedback. Answer: Body font size: There doesn't seem much point in setting the body element's font size to 1.6em if you're going to set paragraphs and other typographic tags to 1.8rem. Would recommend just setting the body to 1.8em and removing the rulesets for the typographic tags. Color accessibility: Some of your link colors styles will be hard to read and fail accessibility standards on white backgrounds. Regular-sized text needs a color contrast ratio of at least 4.5:1 to be accessible. Pink on white is barely legible with a contrast ratio of 1.4:1 Orange on white also fails, with a contrast ratio of 1.97:1
{ "domain": "codereview.stackexchange", "id": 42943, "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": "html, css", "url": null }
html, css There's not much benefit to overriding in a boilerplate the default link colors that people are used to, so I'd recommend removing. If you want to keep them, choose more accessible colors. Margin and padding: Many elements have useful default margins and paddings from user-agents, and removing them (as you do in the first ruleset) will make elements look strange or unrecognizable. Some examples would be: figure, dl, blockquote—and your paragraphs will run together without some kind of margin. Would recommend only removing the padding/margin from the body element and leaving other elements' default margin/padding until you override them. Font family: Tachyons CSS has a really nice font stack that defaults to system fonts with a lot of good fallbacks. A little nicer than Verdana. Text color: Would recommend going slightly darker with the default text color. All of these changes, plus some formatting tweaks and semicolons, would look like this: * { box-sizing: border-box; } html { font-size: 62.5%; } /* makes 1rem 10px */ body { margin: 0; padding: 0; font-size: 1.8em; font-family: -apple-system, BlinkMacSystemFont, 'avenir next', avenir, 'helvetica neue', helvetica, ubuntu, roboto, noto, 'segoe ui', arial, sans-serif; line-height: 1.3; color: #292929; } /* headings */ h1 { font-size: 3rem; } h2 { font-size: 2.4rem; } h3 { font-size: 2rem; } h4 { font-size: 1.8rem; } h5 { font-size: 1.6rem; } h6 { font-size: 1.4rem; }
{ "domain": "codereview.stackexchange", "id": 42943, "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": "html, css", "url": null }
java, junit, binary-search-tree Title: Binary Search tree, leaves method Question: I have written a code of Binary Search tree that extends comparable and implements an interface. The code for leaves and the helper method countLeaves, makes sure that all of the test goes through except for one, heightIsLogOfNumLeavesTreeIsPerfect(). // TODO: Look at the Leaves and helper method in the tree class and see how I should change it so that this test goes through aswell. //EDIT: Added the whole testclass I have also included the message i get when the test does not go through and the test in the test class java.lang.AssertionError: Expected: <2> but: was <0> Expected :<2> Actual :<0> import org.junit.Test; import org.junit.Before; import org.junit.Rule; import org.junit.rules.Timeout; import static org.junit.Assert.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.CoreMatchers.*; import java.util.Arrays; import java.util.stream.IntStream; /** * Test class for a tree. * * @author Melissa Saber Tehrani * @version 2022-02-12 */ public class TreeTest{ @Rule public Timeout globalTimeout = Timeout.seconds(5); Tree<Integer> tree; int[] elementsInTree; int[] elementsNotInTree; @Before public void setUp() { /** * This tree should look like this: * * 8 * / \ * 3 10 * / \ \ * 1 6 14 * / \ / * 4 7 13 */ tree = new Tree<>(); elementsInTree = new int[] {8, 10, 14, 13, 3, 1, 6, 4, 7}; for (int elem : elementsInTree) { tree.insert(elem); } elementsNotInTree = new int[] {34, -3, -10, 12, 74, 5}; }
{ "domain": "codereview.stackexchange", "id": 42944, "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": "java, junit, binary-search-tree", "url": null }
java, junit, binary-search-tree // Tests for height @Test public void heightIsZeroWhenTreeIsEmpty() { // Arrange Tree<Integer> emptyTree = new Tree<>(); // Act int height = emptyTree.height(); // Assert assertThat(height, equalTo(0)); } @Test public void heightIsZeroWhenTreeHasOnlyRoot() { // Arrange Tree<Integer> rootOnlyTree = new Tree<>(); rootOnlyTree.insert(1338); // Act int height = rootOnlyTree.height(); // Assert assertThat(height, equalTo(0)); } @Test public void heightIsLogOfNumLeavesTreeIsPerfect() { // For a perfect tree, tree.height() == log2(tree.leaves() // Arrange Tree<Integer> tree = new Tree<>(); int[] elements = new int[] {8, 3, 10, 1, 6, 9, 14}; int numLeaves = 4; int logNumLeaves = (int) Math.round(Math.log(numLeaves) / Math.log(2)); for (int elem : elements) { tree.insert(elem); } // Act int height = tree.height(); // Assert assertThat(height, equalTo(logNumLeaves)); } } /** * An interface describing a generic Comparable */ public interface BSTInterface <T>{ boolean search(T elem); boolean insert(T elem); int size(); int height(); int leaves(); } /** * An Binary Search tree implementation of the comparable interface. * @param <T> */ public class Tree <T extends Comparable <T>> implements BSTInterface <T>{ private int size; private Node root; public class Node{ private Node Left; private Node Right; private T data; public Node(T data){ this.data = data; } public Node getRight(){ return Right; } public Node getLeft() { return Left; }
{ "domain": "codereview.stackexchange", "id": 42944, "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": "java, junit, binary-search-tree", "url": null }
java, junit, binary-search-tree public Node getLeft() { return Left; } public T getData() { return data; } } public Tree (){ size = 0; root = null; } /** * Test for presence of a value. * @param elem * @return true/false */ @Override public boolean search(T elem) { if(root == null ||elem == null){ return false; } Node node = root; while(true){ if(node.data.compareTo(elem) > 0){ if(node.Right == null){ return false; } else{ node = node.Right; } } else if(node.data.compareTo(elem) == 0){ break; } else{ if(node.Left== null){ return false; } else{ node = node.Left; } } } return true; } /** * Add value to tree; duplicates are not allowed. * Return true if the element is not already present (and is thus inserted), * false otherwise. * * @param elem * @return true/false */ @Override public boolean insert(T elem) { if (elem == null){ return false; } if (root == null){ root = new Node(elem); size++; return true; } Node node = root; while (true){ if (node.data.compareTo(elem) > 0) { if (node.Right == null){ node.Right = new Node(elem); size++; break; } else { node = node.Right; }
{ "domain": "codereview.stackexchange", "id": 42944, "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": "java, junit, binary-search-tree", "url": null }
java, junit, binary-search-tree } else if (node.data.compareTo(elem) == 0) { return false; } else { if (node.Left == null){ node.Left = new Node(elem); size++; break; } else { node = node.Left; } } } return true; } /** * the number of elements in the tree * @return size. */ @Override public int size() { return size; } /** * The height of the tree. * The empty tree and the tree with only the root node both have height 0. * @return the height of the tree. */ @Override public int height() { return countHeight(root); } /** * Helper method for height */ private int countHeight(Node node){ if(node == null) { return 0; } int rightHeight = countHeight(node.Right); int leftHeight = countHeight(node.Left);; int height = Math.max(leftHeight, rightHeight); return height; } /** * The number of leaves in the tree. * @return the amount of leaves the tree have. */ @Override public int leaves() { return countLeaves(root); } /** * Helper method for leaves */ private int countLeaves(Node node) { if (node == null) { return 0; } if (node.Right == null && node.Left == null) { return 1; } int count = 0; count += countLeaves(node.Left); count += countLeaves(node.Right); return count; } /** * A string describing the tree * @return */ public String toString(){ String str = "[" + helpToString(root); if (str.length() > 1) { str = str.substring(0, str.length() - 2); } return str + "]"; }
{ "domain": "codereview.stackexchange", "id": 42944, "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": "java, junit, binary-search-tree", "url": null }
java, junit, binary-search-tree /** * Helper method for toString */ private String helpToString(Node node) { String str = ""; if (node != null) { str += helpToString(node.Right); str += node.data + ", "; str += helpToString(node.Left); } return str; } } Answer: Advice 1 int logNumLeaves = (int) Math.round(Math.log(numLeaves) / Math.log(2)); The above formula assumes that the tree is balanced. Your implementation (and a test tree) is not. Not sure about the math part. Advice 2 public int height() { return countHeight(root); } private int countHeight(Node node){ if(node == null) { return 0; } int rightHeight = countHeight(node.Right); int leftHeight = countHeight(node.Left);; int height = Math.max(leftHeight, rightHeight); return height; } Will always return 0. You need instead: public int height() { return countHeight(root); } private int countHeight(Node<E> node) { if (node == null) { return 0; } return 1 + Math.max(countHeight(node.getLeftChild()), countHeight(node.getRightChild())); }
{ "domain": "codereview.stackexchange", "id": 42944, "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": "java, junit, binary-search-tree", "url": null }
c++, template, c++20 Title: function template for string_view-to-integer conversion Question: I want to make the following function a function template that supports all the integral types: #include <iostream> #include <utility> #include <charconv> #include <string_view> #include <concepts> #include <limits> #include <optional> // header file std::optional<int> to_integer( std::string_view token, const std::pair<int, int> acceptableRange = { std::numeric_limits<int>::min( ), std::numeric_limits<int>::max( ) } ) noexcept; std::optional<int> to_integer( const char* const token, const std::pair<int, int> acceptableRange = { std::numeric_limits<int>::min( ), std::numeric_limits<int>::max( ) } ) noexcept = delete; // source file std::optional<int> to_integer( std::string_view token, const std::pair<int, int> acceptableRange ) noexcept { if ( token.empty( ) ) { return { }; } if ( token.size( ) > 1 && token[ 0 ] == '+' && token[ 1 ] != '-' ) { token.remove_prefix( 1 ); } int value; const auto [ ptr, ec ] { std::from_chars( token.begin( ), token.end( ), value, 10 ) }; const auto& [ minAcceptableValue, maxAcceptableValue ] { acceptableRange }; if ( ec != std::errc( ) || ptr != token.end( ) || value < minAcceptableValue || value > maxAcceptableValue ) { return { }; } return value; } Here is my version: // header file template < std::integral T > std::optional<T> to_integer( std::string_view token, const std::pair<T, T> acceptableRange = { std::numeric_limits<T>::min( ), std::numeric_limits<T>::max( ) } ) noexcept; template < std::integral T > std::optional<T> to_integer( const char* const token, const std::pair<T, T> acceptableRange = { std::numeric_limits<T>::min( ), std::numeric_limits<T>::max( ) } ) noexcept = delete; // source file
{ "domain": "codereview.stackexchange", "id": 42945, "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++, template, c++20", "url": null }
c++, template, c++20 // source file template < std::integral T > std::optional<T> to_integer( std::string_view token, const std::pair<T, T> acceptableRange ) noexcept { if ( token.empty( ) ) { return { }; } if ( token.size( ) > 1 && token[ 0 ] == '+' && token[ 1 ] != '-' ) { token.remove_prefix( 1 ); } T value; const auto [ ptr, ec ] { std::from_chars( token.begin( ), token.end( ), value, 10 ) }; const auto& [ minAcceptableValue, maxAcceptableValue ] { acceptableRange }; if ( ec != std::errc( ) || ptr != token.end( ) || value < minAcceptableValue || value > maxAcceptableValue ) { return { }; } return value; } // call site int main( ) { const std::string_view sv { "-100" }; const auto retVal { to_integer<unsigned int>( sv, { 0, 100 } ) }; std::cout << retVal.value_or( -1 ) << '\n'; } Does my implementation have any flaws? Can it fail in some cases? How would you write it to make it better? It somehow returns 4294967295 when passing e.g. "-100" as can be seen in the main function. Why? How can I fix that? I expect it to return an empty optional since -100 is out of range of unsigned int.
{ "domain": "codereview.stackexchange", "id": 42945, "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++, template, c++20", "url": null }
c++, template, c++20 Answer: Don't delete the overload that takes a const char* I don't understand why you delete the overload that takes a const char* as the first parameter. If you don't delete it, the one that takes a std::string_view is a viable candidate, because there is an implicit conversion from const char* to std::string_view. And it does exactly what you want. Consider removing the check for a leading +-sign I would remove the check for a leading +-sign, and rely solely on std::from_chars() to determine the validity of the input. This makes your function behave more like other standard library functions, and thus avoids potentially surprising behavior. If you do need such functionality, consider putting it into a separate function, so the caller can choose whether to make use of that or not. The case of the return value 4294967295 This is not because of any flaw in to_integer(), rather it is because you are using std::optional's value_or(). The int -1 you pass in will be static_casted to the value type of the optional before it is returned. Since the value type is unsigned int, the -1 will be converted to 4294967295.
{ "domain": "codereview.stackexchange", "id": 42945, "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++, template, c++20", "url": null }
c++ Title: Optimizing reading and storing a text file C++ Question: I am fairly new to C++ but ran into a bit of a performance issue. To counter this I am trying to optimize parts of my code. This part is reading a text file and storing the first two values of a line foreach line in the file. This works but I was wondering if it is possible to do it faster and cleaner. See code below: vector<pair<double, double>> createList(string path) { ifstream file (path, ios::binary); vector<pair<double, double>> file_lines; string value; double token; string delimiter = "\t"; size_t pos = 0; int rowCount = 0; while(std::getline(file, value)) { int count = 0; pair<double, double> values; while ((pos = value.find(delimiter)) != string::npos && count < 2) { token = std::stod(value.substr(0, pos)); if(count == 0){ values.first = token; }else{ values.second = token; } value.erase(0, pos + delimiter.length()); count++; } file_lines.push_back(values); rowCount++; } return file_lines } Answer: It looks like you're missing some crucial #include lines, and several using declarations (or a using directive - you should really avoid that). I'd probably split the function into two parts: one that handles filesystem stuff, and one that's unit-testable, accepting a std::istream&. That looks like this (after fixing the syntax error on the return statement): #include <istream> #include <string> #include <utility> #include <vector> auto createList(std::istream& file) { std::vector<std::pair<double, double>> file_lines; std::string value; double token; std::string delimiter = "\t"; std::size_t pos = 0; int rowCount = 0;
{ "domain": "codereview.stackexchange", "id": 42946, "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++", "url": null }
c++ while(std::getline(file, value)) { int count = 0; std::pair<double, double> values; while ((pos = value.find(delimiter)) != std::string::npos && count < 2) { token = std::stod(value.substr(0, pos)); if(count == 0){ values.first = token; }else{ values.second = token; } value.erase(0, pos + delimiter.length()); count++; } file_lines.push_back(values); rowCount++; } return file_lines; } We can write our first test. I'll use the GoogleTest framework, but you can use whatever suits you best. #include <gtest/gtest.h> #include <sstream> TEST(CreateList, Empty) { std::istringstream is{""}; EXPECT_EQ(createList(is), (std::vector<std::pair<double, double>>{})); } We can add some more tests, now. It's good to start with tests of invalid input: TEST(CreateList, NonNumeric) { std::istringstream is{"abcde"}; EXPECT_EQ(createList(is), (std::vector<std::pair<double, double>>{})); } I had hoped that the function would ignore the invalid line, but no, it's treated as 0.0: [ RUN ] CreateList.NonNumeric 274028.cpp:49: Failure Expected equality of these values: createList(is) Which is: { (0, 0) } (std::vector<std::pair<double, double>>{}) Which is: {} [ FAILED ] CreateList.NonNumeric (0 ms) That's probably not what we want. Consider throwing an exception when input doesn't match expectation. We can add some tests where we expect conversions (be careful to use exact floating-point values, not ones with infinite binary representation such as 0.1). I'll use a function and a small macro to help reduce repetition. #include <sstream> static auto createListFromString(std::string s) { std::istringstream is{s}; return createList(is); }
{ "domain": "codereview.stackexchange", "id": 42946, "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++", "url": null }
c++ #define EXPECT_CREATELIST_EQ(str, ...) \ static const std::vector<std::pair<double, double>> expected{__VA_ARGS__}; \ EXPECT_EQ(createListFromString(str), expected); TEST(CreateList, TwoValues) { EXPECT_CREATELIST_EQ("1.5\t-2\t\n", {1.5, -2}); } TEST(CreateList, TwoLines) { EXPECT_CREATELIST_EQ("1.5\t-2\t\n" "-1.0\t5.5\t", {1.5, -2}, {-1, 5.5}); } With some tests in place, it's time to look at the code. We can start by getting rid of rowCount, as it's only ever written to, and never read. Some of the other names are confusing - I'd choose line rather than value, and value instead of token. Several of the variables can be reduced in scope, and delimiter can be a char instead of a string. That gets us to: auto createList(std::istream& file) { std::vector<std::pair<double, double>> file_lines; static const char delimiter = '\t'; std::string line; while(std::getline(file, line)) { std::pair<double, double> values; std::size_t pos = 0; for (int count = 0; (pos = line.find(delimiter)) != std::string::npos && count < 2; ++count) { double value = std::stod(line.substr(0, pos)); if(count == 0){ values.first = value; }else{ values.second = value; } line.erase(0, pos + 1); } file_lines.push_back(values); } return file_lines; }
{ "domain": "codereview.stackexchange", "id": 42946, "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++", "url": null }
c++ Now we can start looking at the performance. The first thing that jumps out at me is the line.erase(0, pos + 1);. Erasing from the start of a string can be an expensive operation, as it requires moving the rest of the string forwards. This is even more wasteful second time around the loop, when we won't be using the string again. It's better to keep the string unchanged, and instead change where we look into it. While we're doing that, we can unroll the loop which executes only twice, and has half its body conditional on the loop counter. auto createList(std::istream& file) { std::vector<std::pair<double, double>> file_lines; static const char delimiter = '\t'; std::string line; while(std::getline(file, line)) { auto first_len = line.find(delimiter); auto second_delim = line.find(delimiter, first_len+1); if (second_delim == line.npos) { // invalid line; ignore it continue; } auto second_len = second_delim - first_len; std::size_t end; double first_val = stod(line.substr(0, first_len), &end); if (end != first_len) { // junk between number and delimiter continue; } double second_val = stod(line.substr(first_len, second_len), &end); if (end != second_len) { // junk between number and delimiter continue; } file_lines.emplace_back(first_val, second_val); } return file_lines; } Now our main inefficiencies come down to reading entire lines when we're only interested in the beginning, and copying substrings rather than using views. We can avoid both of those by using formatted input functions (namely >>), especially if we can be sure that our lines always have at least two strings at the start. That looks like auto createList(std::istream& file) { std::vector<std::pair<double, double>> file_lines;
{ "domain": "codereview.stackexchange", "id": 42946, "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++", "url": null }
c++ file.exceptions(file.badbit); for (;;) { double first, second; file >> first >> second; if (!file) { if (file.eof()) { // done return file_lines; } // failure throw std::ios_base::failure("createList parse error"); } // now skip past the rest of the line file_lines.emplace_back(first, second); if (!file.ignore(std::numeric_limits<std::streamsize>::max(), '\n')) { return file_lines; } } } Modified code Full replacement code, with tests: #include <filesystem> #include <fstream> #include <limits> #include <string> #include <utility> #include <vector> auto createList(std::istream& file) { std::vector<std::pair<double, double>> file_lines; file.exceptions(file.badbit); for (;;) { double first, second; file >> first >> second; if (!file) { if (file.eof()) { // done return file_lines; } // failure throw std::ios_base::failure("createList parse error"); } // now skip past the rest of the line file_lines.emplace_back(first, second); if (!file.ignore(std::numeric_limits<std::streamsize>::max(), '\n')) { return file_lines; } } } auto createList(std::filesystem::path path) { std::ifstream is{path}; return createList(is); } #include <gtest/gtest.h> #include <sstream> static auto createListFromString(std::string s) { std::istringstream is{s}; return createList(is); } #define EXPECT_CREATELIST_EQ(str, ...) \ static const std::vector<std::pair<double, double>> expected{__VA_ARGS__}; \ EXPECT_EQ(createListFromString(str), expected); TEST(CreateList, Empty) { EXPECT_CREATELIST_EQ(""); } TEST(CreateList, NonNumeric) { EXPECT_THROW(createListFromString("abcde"), std::ios_base::failure); }
{ "domain": "codereview.stackexchange", "id": 42946, "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++", "url": null }
c++ TEST(CreateList, TwoValues) { EXPECT_CREATELIST_EQ("1.5 -2 .other stuff\n", {1.5, -2}); } TEST(CreateList, TwoLines) { EXPECT_CREATELIST_EQ("1.5\t-2\n" "-1.0\t5.5\t\n", {1.5, -2}, {-1, 5.5}); }
{ "domain": "codereview.stackexchange", "id": 42946, "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++", "url": null }
c++, median, constrained-templates Title: Generic implementation of median #2: Follow up Question: Follow on from this codereview: generic implementation of median As before the vector2 class is just for illustrative purposes and not the focus. I have incorporated all the excellent feedback from G.Sliepen from previous codereview linked above: 2 versions median() and median_in_place(). The former makes a copy. constrain inputs with concepts simpler syntax for default input parameters provides overloads which accept a range uses a projection parameter - no more extract uses std::invoke to support member functions uses std::midpoint for a safer average Two main questions: Use of concepts: It is "best/preferable" to constrain each of the wrappers as shown below, ie median() wraps median_in_place() and concepts are used at both levels. This is somewhat repetitive, but has subtle differences. Or would it be better, to use Duck typing for the wrappers and only put concept constraints on the main, inner function. Discuss. Would it be helpful to specify the return types using trailing return syntax? If so, I was unable to find a syntax which works. I suspect, I failed because I needed one or more of std::remove_cv or std::remove_const or std::decay. How to do that? Or not worth it? Discuss. #include <algorithm> #include <cmath> #include <exception> #include <iostream> #include <iterator> #include <numeric> #include <ostream> #include <ranges> #include <stdexcept> #include <vector> #include <list> template <typename T> class vector2 { public: T x{}; T y{}; constexpr vector2(T x_, T y_) : x(x_), y(y_) {} constexpr vector2() = default; [[nodiscard]] T mag() const { return std::hypot(x, y); } [[nodiscard]] vector2 norm() const { return *this / this->mag(); } [[nodiscard]] double dot(const vector2& rhs) const { return x * rhs.x + y * rhs.y; }
{ "domain": "codereview.stackexchange", "id": 42947, "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++, median, constrained-templates", "url": null }
c++, median, constrained-templates // clang-format off vector2& operator+=(const vector2& obj) { x += obj.x; y += obj.y; return *this; } vector2& operator-=(const vector2& obj) { x -= obj.x; y -= obj.y; return *this; } vector2& operator*=(const double& scale) { x *= scale; y *= scale; return *this; } vector2& operator/=(const double& scale) { x /= scale; y /= scale; return *this; } // clang-format on friend vector2 operator+(vector2 lhs, const vector2& rhs) { return lhs += rhs; } friend vector2 operator-(vector2 lhs, const vector2& rhs) { return lhs -= rhs; } friend vector2 operator*(vector2 lhs, const double& scale) { return lhs *= scale; } friend vector2 operator*(const double& scale, vector2 rhs) { return rhs *= scale; } friend vector2 operator/(vector2 lhs, const double& scale) { return lhs /= scale; } friend std::ostream& operator<<(std::ostream& os, const vector2& v) { return os << '[' << v.x << ", " << v.y << ']'; } }; using vec2 = vector2<double>; using vec2I = vector2<int>; template <typename RandomAccessIter, typename Comp = std::ranges::less, typename Proj = std::identity> requires std::random_access_iterator <RandomAccessIter> && std::sortable<RandomAccessIter, Comp, Proj> auto median_in_place(RandomAccessIter first, RandomAccessIter last, const Comp& comp = {}, const Proj& proj = {}) { auto size = std::distance(first, last); if (size == 0) throw std::domain_error("Can't find median of an empty range."); auto middle = first + (size / 2); std::ranges::nth_element(first, middle, last, comp, proj); if (size % 2 == 1) return std::invoke(proj, *middle); auto below_middle = std::ranges::max_element(first, middle, comp, proj); return std::midpoint(std::invoke(proj, *middle), std::invoke(proj, *below_middle)); }
{ "domain": "codereview.stackexchange", "id": 42947, "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++, median, constrained-templates", "url": null }
c++, median, constrained-templates return std::midpoint(std::invoke(proj, *middle), std::invoke(proj, *below_middle)); } template <typename RandomAcccessRange, typename Comp = std::less<>, typename Proj = std::identity> requires std::ranges::random_access_range<RandomAcccessRange> && std::sortable<typename RandomAcccessRange::iterator, Comp, Proj> auto median_in_place(RandomAcccessRange& range, const Comp& comp = {}, const Proj& proj = {}) { return median_in_place(range.begin(), range.end(), comp, proj); } template <typename InputIter, typename Comp = std::ranges::less, typename Proj = std::identity> requires std::input_iterator<InputIter> && std::sortable<typename std::vector<std::iter_value_t<InputIter>>::iterator, Comp, Proj> auto median(InputIter first, InputIter last, const Comp& comp = {}, const Proj& proj = {}) { std::vector<std::iter_value_t<InputIter>> input_copy(first, last); // always make a copy return median_in_place(input_copy.begin(), input_copy.end(), comp, proj); } template <typename InputRange, typename Comp = std::less<>, typename Proj = std::identity> requires std::ranges::input_range<InputRange> && std::sortable<typename std::vector<std::ranges::range_value_t<InputRange>>::iterator, Comp, Proj> auto median(const InputRange& range, const Comp& comp = {}, const Proj& proj = {}) { return median(range.begin(), range.end(), comp, proj); } template <typename T> void print(const std::vector<T>& v) { std::cout << "["; char delim[2]{}; // NOLINT char[] OK here for (const auto& e: v) { std::cout << static_cast<char*>(delim) << e; delim[0] = ','; } std::cout << "]\n"; } template <typename T> void print(const std::list<T>& v) { std::cout << "["; char delim[2]{}; // NOLINT char[] OK here for (const auto& e: v) { std::cout << static_cast<char*>(delim) << e; delim[0] = ','; } std::cout << "]\n"; }
{ "domain": "codereview.stackexchange", "id": 42947, "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++, median, constrained-templates", "url": null }
c++, median, constrained-templates int main() { { const std::vector<int> ints{9, 8, 7, 6, 5, 4, 3, 2, 1}; print(ints); std::cout << "median(ints) = " << median(ints) << "\n"; print(ints); } { std::vector<int> ints{9, 8, 7, 6, 5, 4, 3, 2, 1}; print(ints); std::cout << "median_in_place(ints) = " << median_in_place(ints) << "\n"; print(ints); } { const std::list<vec2> vec2s{{9, 8}, {7, 6}, {5, 4}, {3, 2}}; print(vec2s); std::cout << "median(mag(vec2)) = " << median(vec2s, {}, &vec2::mag) << "\n"; print(vec2s); } { std::vector<vec2> vec2s{{9, 8}, {7, 6}, {5, 4}, {3, 2}}; print(vec2s); std::cout << "median_in_place(mag(vec2)) using lambda = " << median_in_place(vec2s, {}, [](const auto& v) { return v.mag(); }) << "\n"; print(vec2s); } { std::vector<vec2> vec2s{{9, 8}, {7, 6}, {5, 4}, {3, 2}}; print(vec2s); std::cout << "median_in_place(mag(vec2) using iters) = " << median_in_place(vec2s.begin(), vec2s.end(), {}, [](const auto& v) { return v.mag(); }) << "\n"; print(vec2s); } } Answer: Be as generic as possible Your median() and median_in_place() functions don't work on all things that are ranges, because you didn't use generic functions/types everywhere. Consider for example trying to get the median of a plain array: double values[] = {1, 2, 3, 4, 5, 6, 7, 8}; std::cout << median(values) << '\n'; This will fail because you are using range.begin() and range.end() instead of std::ranges::begin(range) and std::ranges::end(range). Fixing that, there still is an issue if you use median_in_place(), since you constrained it to: std::sortable<typename RandomAcccessRange::iterator, Comp, Proj> This should be: std::sortable<std::ranges::iterator_t<RandomAcccessRange>, Comp, Proj>
{ "domain": "codereview.stackexchange", "id": 42947, "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++, median, constrained-templates", "url": null }
c++, median, constrained-templates This should be: std::sortable<std::ranges::iterator_t<RandomAcccessRange>, Comp, Proj> There's also a problem with your print() function. Instead of making it a template on the value type, and have explicit overloads for the different containers, make it a template on the container type (or rather, range) instead: template <std::ranges::input_range T> void print(const T& v) { std::cout << "["; const char *delim = ""; for (const auto& e: v) { std::cout << delim << e; delim = ", "; } std::cout << "]\n"; } Now you can even print a plain array. And as Toby Speight did in his answer, even avoid it always printing to std::cout, and have it take a std::ostream reference parameter. Answers to your questions Use of concepts: It is "best/preferable" to constrain each of the wrappers as shown below, ie median() wraps median_in_place() and concepts are used at both levels. This is somewhat repetitive, but has subtle differences. Or would it be better, to use Duck typing for the wrappers and only put concept constraints on the main, inner function. For the most concise error messages, it's best to add concepts to all public functions. Would it be helpful to specify the return types using trailing return syntax? If so, I was unable to find a syntax which works. I suspect, I failed because I needed one or more of std::remove_cv or std::remove_const or std::decay. How to do that? Or not worth it? I personally don't see the need to specify a return type at all. Just let it be automatically deduced. If you do want it though, then it probably should be this: template <...> requires ... auto median_in_place(RandomAccessIter first, RandomAccessIter last, const Comp& comp = {}, const Proj& proj = {}) -> std::decay_t<std::invoke_result_t<Proj, std::iter_value_t<RandomAccessIter>>> { ... }
{ "domain": "codereview.stackexchange", "id": 42947, "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++, median, constrained-templates", "url": null }
c++, median, constrained-templates The std::iter_value_t is required to get the value type of the range, then you need to get the result type after Proj is applied, but since that might be a reference (especially if it's std::identity), you also need to use std::decay_t on that.
{ "domain": "codereview.stackexchange", "id": 42947, "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++, median, constrained-templates", "url": null }
c#, sql, .net-core, entity-framework-core Title: RawSqlQuery minimizing risk of field name confusion Question: Is there a way to make the following code more maintainable? public static DtoNumOrderedNumDone GetNumOrderedNumDone(int jobTaskId) { const string selectList = "Quantity, NumDone"; var sql = @$"select convert(int,numordered) as Quantity , convert(int,sum(isnull(numDone,0))) as NumDone from task k left outer join taskdone d on k.jobtaskid = d.jobtaskid inner join job j on k.jobid = j.jobid where k.jobtaskid = {jobTaskId} group by k.jobtaskid, j.NumOrdered"; var tokens = selectList.Tokenize(); var quantityOrdinal = Array.IndexOf(tokens, "Quantity"); var numdoneOrdinal = Array.IndexOf(tokens, "NumDone"); var dtos = DataHelpers.RawSqlQuery(sql, x => new DtoNumOrderedNumDone() { NumDone = x.GetInt32(numdoneOrdinal), Quantity = x.GetInt32(quantityOrdinal) } ); var dto = dtos.FirstOrDefault(); return dto; }
{ "domain": "codereview.stackexchange", "id": 42948, "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#, sql, .net-core, entity-framework-core", "url": null }
c#, sql, .net-core, entity-framework-core I aren't worried about sql injection because jobTaskId is an int, however I am worried that the code is vulnerable to being altered later and the field order being made incorrect. [Update] The helper code is public static class DataHelpers { public static List<T> RawSqlQuery<T>(string query, Func<DbDataReader, T> map, params SqlParameter[] parameters) { try { using var context = MakeDbContext(); return RunQuery(context, query, map, parameters); } catch (Exception e) { Console.WriteLine(e); throw; } } public static List<T> RunQuery<T>(MyDbContext context, string query, Func<DbDataReader, T> map, params SqlParameter[] parameters) { try { var cn = context.Database.GetDbConnection(); var oldState = cn.State; if (cn.State.Equals(ConnectionState.Closed)) cn.Open(); using var command = cn.CreateCommand(); command.CommandText = query; command.CommandType = CommandType.Text; foreach (var param in parameters) command.Parameters.Add(param); if (cn.State.Equals(ConnectionState.Closed)) cn.Open(); var entities = new List<T>(); using (var result = command.ExecuteReader()) { while (result.Read()) { var r = map(result); entities.Add(r); } } if (oldState.Equals(ConnectionState.Closed) && cn.State == ConnectionState.Open) cn.Close(); return entities; } catch (Exception e) { MessageBox.Show($"RunQuery inner: {e.InnerException}, ex:{e} \r\n {query}"); Console.WriteLine(e); throw; } } [Update] Exploring ISR5's answer I get
{ "domain": "codereview.stackexchange", "id": 42948, "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#, sql, .net-core, entity-framework-core", "url": null }
c#, sql, .net-core, entity-framework-core } [Update] Exploring ISR5's answer I get Answer: If you look at the GetNumOrderedNumDone method then you can see that you have repeated the column names three times. It can cause problem when you need to rename one of them, because you have to update it in multiple places. There are several ways to fix this: Define consts for column names Define a custom attribute, decorate the DTO's properties and use reflection to retrieve column names etc. I will show you the first approach, but in order to get there we need to do some refactoring. 1st iteration As discussed in the comments section if you change the RunQuery to receive a Func<DbDataReader, List<T>> parameter then the column indexes can be cached (on the map function implementation side) and be reused public static List<T> RunQuery<T>(MyDbContext context, string query, Func<DbDataReader, List<T>> map, params SqlParameter[] parameters) { try { //... if (cn.State.Equals(ConnectionState.Closed)) cn.Open(); using var reader = command.ExecuteReader(); var entities = reader.HasRows ? map(reader) : new List<T>(); if (oldState.Equals(ConnectionState.Closed) && cn.State == ConnectionState.Open) cn.Close(); return entities; } catch (Exception e) { //... } } Since some responsibility has been shifted to the consumer of your helper method that's why the DbDataReader usage became cleaner I've added here the HasRows check to avoid calling map function unnecessary if there is nothing to map
{ "domain": "codereview.stackexchange", "id": 42948, "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#, sql, .net-core, entity-framework-core", "url": null }
c#, sql, .net-core, entity-framework-core Then your GetNumOrderedNumDone can be rewritten like this: public static DtoNumOrderedNumDone GetNumOrderedNumDone(int jobTaskId) { const string QuantityColumnName = "Quantity", NumDoneColumnName = "NumDone"; var sql = @$"select convert(int,numordered) as {QuantityColumnName} , convert(int,sum(isnull(numDone,0))) as {NumDoneColumnName} from task k left outer join taskdone d on k.jobtaskid = d.jobtaskid inner join job j on k.jobid = j.jobid where k.jobtaskid = {jobTaskId} group by k.jobtaskid, j.NumOrdered"; var dtos = DataHelpers.RawSqlQuery(sql, reader => { int quatityColumnIndex = reader.GetOrdinal(QuantityColumnName); int numDoneColumnIndex = reader.GetOrdinal(NumDoneColumnName); return reader.Cast<IDataRecord>().Select(record => new DtoNumOrderedNumDone { NumDone = record.GetInt32(quatityColumnIndex), Quantity = record.GetInt32(numDoneColumnIndex) }).ToList(); } ); var dto = dtos.FirstOrDefault(); return dto; } I've defined two constants that are storing the column names Since you are already using string interpolation for your query it is really convenient to use these there as well Inside the RawSqlQuery first I've cached the column indexes to be able to reuse them multiple times The second part of the map implementation is a bit tricker If you have a DbDataReader then you can use the Read method to iterate through it or you can treat it as IEnumerable If you are unaware of this capability then I highly recommend to read these SO topics: 1, 2 So, after we have converted the DbDataReader to IEnumerable<IDataRecord> we can use Linq
{ "domain": "codereview.stackexchange", "id": 42948, "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#, sql, .net-core, entity-framework-core", "url": null }
c#, sql, .net-core, entity-framework-core So, after we have converted the DbDataReader to IEnumerable<IDataRecord> we can use Linq 2nd iteration What is the problem with the first one? The RunQuery is generic enough to be used for queries which might return 0, 1 or multiple rows. In your particular case the cardinality is 0..1. So, calling the ToList inside the RawSqlQuery then calling the FirstOrDefault on the returned collection seems a bit overkill. So, if you introduce an overload for the RunQuery (and for the RawSqlQuery as well) which can return 0 or 1 entity then the usage could be more streamlined. Let's start with the RunQuery public static T RunQuery<T>(MyDbContext context, string query, Func<DbDataReader, T> map, params SqlParameter[] parameters) { try { //... if (cn.State.Equals(ConnectionState.Closed)) cn.Open(); using var reader = command.ExecuteReader(); T entity = reader.Cast<IDataRecord>().Count() switch { 1 => map(reader), 0 => default, _ => throw new InvalidOperationException("Query returned more than 1 rows") }; if (oldState.Equals(ConnectionState.Closed) && cn.State == ConnectionState.Open) cn.Close(); return entity; } catch (Exception e) { //... } } Here I've used the Count() instead of HasRows to be able to handle each cases accordingly If there is only one record then it should call the map function If there is zero matching record then it should return default(T) If there are more than one matching records then it should throw exception
{ "domain": "codereview.stackexchange", "id": 42948, "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#, sql, .net-core, entity-framework-core", "url": null }
c#, sql, .net-core, entity-framework-core The usage could be simplified like this public static DtoNumOrderedNumDone GetNumOrderedNumDone(int jobTaskId) { const string QuantityColumnName = "Quantity", NumDoneColumnName = "NumDone"; var sql = @$"select convert(int,numordered) as {QuantityColumnName} , convert(int,sum(isnull(numDone,0))) as {NumDoneColumnName} from task k left outer join taskdone d on k.jobtaskid = d.jobtaskid inner join job j on k.jobid = j.jobid where k.jobtaskid = {jobTaskId} group by k.jobtaskid, j.NumOrdered"; return DataHelpers.RawSqlQuery(sql, reader => reader.Cast<IDataRecord>().Select(record => new DtoNumOrderedNumDone { NumDone = record.GetInt32(record.GetOrdinal(QuantityColumnName)), Quantity = record.GetInt32(record.GetOrdinal(NumDoneColumnName)) }).FirstOrDefault() ); } For the sake of brevity I've omitted the exception handling but you should do that Since we know that the Select will be called only once that's why we do not need to cache the column indices UPDATE #1: map(reader) problem I have to confess that I have rarely used DbDataReader in the past decade so I have forgotten that Cast<IDataRecrod> creates a forward-only iterator. There is no real Reset function which can rewind that IEnumerable. So, after calling the Count method the iteration reaches its end. That's why it can't be reiterated. There are several workarounds for that, like: Issue two select statements where the 2nd is SELECT @@ROWCOUNT and then use NextResult to move the iterator to next result set Load the DataReader into a DataTable and pass that around Use SingleOrDefault on the map implementation side to enforce 0..1 cardinality Pass IDataRecord to map instead of DbDataReader etc.
{ "domain": "codereview.stackexchange", "id": 42948, "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#, sql, .net-core, entity-framework-core", "url": null }
c#, sql, .net-core, entity-framework-core Let me show you the last two options SingleOrDefault public static T RunQuery<T>(MyDbContext context, string query, Func<DbDataReader, T> map, params SqlParameter[] parameters) { try { //... if (cn.State.Equals(ConnectionState.Closed)) cn.Open(); using var reader = command.ExecuteReader(); var entity = map(reader); if (oldState.Equals(ConnectionState.Closed) && cn.State == ConnectionState.Open) cn.Close(); return entity; } catch (Exception e) { //... } } The RunQuery is simplified since the cardinality enforcement is shifted to the map function public static DtoNumOrderedNumDone GetNumOrderedNumDone(int jobTaskId) { const string QuantityColumnName = "Quantity", NumDoneColumnName = "NumDone"; var sql = @$"select convert(int,numordered) as {QuantityColumnName} , convert(int,sum(isnull(numDone,0))) as {NumDoneColumnName} from task k left outer join taskdone d on k.jobtaskid = d.jobtaskid inner join job j on k.jobid = j.jobid where k.jobtaskid = {jobTaskId} group by k.jobtaskid, j.NumOrdered"; return DataHelpers.RawSqlQuery(sql, reader => reader.Cast<IDataRecord>().Select(record => new DtoNumOrderedNumDone { NumDone = record.GetInt32(record.GetOrdinal(QuantityColumnName)), Quantity = record.GetInt32(record.GetOrdinal(NumDoneColumnName)) }).SingleOrDefault() ); } IDataRecord NOTE: I have tested this approach with sqlite, but I hope this approach works as well with MSSQL as well. public static T RunQuery<T>(MyDbContext context, string query, Func<IDataRecord, T> map, params SqlParameter[] parameters) { try { //... if (cn.State.Equals(ConnectionState.Closed)) cn.Open();
{ "domain": "codereview.stackexchange", "id": 42948, "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#, sql, .net-core, entity-framework-core", "url": null }
c#, sql, .net-core, entity-framework-core using var reader = command.ExecuteReader(); var rawEntities = reader.Cast<IDataRecord>().ToList(); T entity = rawEntities.Count switch { 1 => map(rawEntities.First()), 0 => default, _ => throw new InvalidOperationException("Query returned more than 1 rows") }; if (oldState.Equals(ConnectionState.Closed) && cn.State == ConnectionState.Open) cn.Close(); return entity; } catch (Exception e) { //... } } Here we retrieve the IDataRecords into a helper variable and make the branching on its Count property Please note that here we are passing the IDataRecord to the map function not the reader public static DtoNumOrderedNumDone GetNumOrderedNumDone(int jobTaskId) { const string QuantityColumnName = "Quantity", NumDoneColumnName = "NumDone"; var sql = @$"select convert(int,numordered) as {QuantityColumnName} , convert(int,sum(isnull(numDone,0))) as {NumDoneColumnName} from task k left outer join taskdone d on k.jobtaskid = d.jobtaskid inner join job j on k.jobid = j.jobid where k.jobtaskid = {jobTaskId} group by k.jobtaskid, j.NumOrdered"; return DataHelpers.RawSqlQuery(sql, record => new DtoNumOrderedNumDone { NumDone = record.GetInt32(record.GetOrdinal(QuantityColumnName)), Quantity = record.GetInt32(record.GetOrdinal(NumDoneColumnName)) }); } I suggest the second approach since You can't enforce the map implementor to call SingleOrDefault instead of First or FirstOrDefault The map implementation is way more concise compare to the SingleOrDefault approach You are not leaking implementation detail (DataReader) so the map implementor for example can't dispose the reader Your intent is better expressed since you are passing a single record to map to an entity type
{ "domain": "codereview.stackexchange", "id": 42948, "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#, sql, .net-core, entity-framework-core", "url": null }
c#, sql, .net-core, entity-framework-core UPDATE #2: Share RawSqlQuery method public static T RawSqlQuery<T>(string query, Func<IDataRecord, T> map, params SqlParameter[] parameters) { try { using var context = MakeDbContext(); return RunQuery(context, query, map, parameters); } catch (Exception e) { Console.WriteLine(e); throw; } }
{ "domain": "codereview.stackexchange", "id": 42948, "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#, sql, .net-core, entity-framework-core", "url": null }
c++, median Title: Find median of values without copying Question: For practice, I've been playing with calculating median values. This time, I wanted to make something that works well without copying the input values (perhaps because they are bulky, or of a type that's not copyable) and without reordering the container. My implementation is split into two parts - find iterators to the central value(s), and combine the two values. This allows the advanced user to combine the central values in interesting ways if needed (extracting fields from composite objects, for example). But the simple median::value() interface is intended to be easy to use, and works for any type with a midpoint() function (found by ADL, or falling back to std::midpoint()). The user can override the arithmetic type used for midpoint - that's useful when we want to get a fractional value rather than rounding for integer midpoint. The principle is straightforward - an external partial sort on a parallel container of iterators, using std::nth_element, and std::max_element() where needed. This parallel operation means that we can be quite generous in the types we accept - we only need a forward range, where most implementations require a random-access range. I'll present the tests first (using GoogleTest framework), as they show how the functions are used. They use containers of int, for simplicity, even though copying values rather than iterators is normally more efficient for these. #include <gtest/gtest.h> #include <array> #include <forward_list> #include <vector> template<std::ranges::forward_range Container = std::vector<int>> static void test_values(Container const& values, int first, int second) { auto const its = median::iterators(values); EXPECT_EQ(*its.first, first); EXPECT_EQ(*its.second, second); } TEST(Median, Empty) { EXPECT_THROW(median::iterators(std::array<bool,0>{}), std::domain_error); }
{ "domain": "codereview.stackexchange", "id": 42949, "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++, median", "url": null }
c++, median TEST(Median, OneElement) { SCOPED_TRACE(""); test_values({100}, 100, 100); } TEST(Median, TwoElements) { SCOPED_TRACE(""); test_values({100, 200}, 100, 200); SCOPED_TRACE(""); test_values({200, 100}, 100, 200); } TEST(Median, ThreeElements) { SCOPED_TRACE(""); test_values({1, 3, 2}, 2, 2); } TEST(Median, FourElements) { SCOPED_TRACE(""); test_values({8, 2, 6, 4}, 4, 6); SCOPED_TRACE(""); test_values({4, 4, 6, 4}, 4, 4); } TEST(Median, FiveElements) { SCOPED_TRACE(""); test_values({8, 2, 6, 4, 0}, 4, 4); } TEST(Median, PlainArray) { SCOPED_TRACE(""); const int arr[] = { 2, 1, 3}; test_values(arr, 2, 2); } TEST(Median, CustomSort) { auto const values = std::array{20, 91, 92, 63, 54}; // sort by last digit auto const compare = [](int a, int b){ return a % 10 < b % 10; }; EXPECT_EQ(median::value(values, compare), 92); } TEST(Median, Value) { auto const values = std::forward_list{0, 1, 2, 3}; auto const iters = median::iterators(values); EXPECT_EQ(median::midval(iters), 1); // integer arithmetic EXPECT_EQ(median::midval<double>(iters), 1.5); // Same, but using convenience functions EXPECT_EQ(median::value(values), 1); EXPECT_EQ(median::value<double>(values), 1.5); // And with reverse sort (causing integer std::midpoint() to round upwards) EXPECT_EQ(median::value(values, std::greater<int>{}), 2); EXPECT_EQ(median::value<double>(values, std::greater<int>{}), 1.5); } namespace test { struct moveonly_int { int value; moveonly_int(int i) : value{i} {} moveonly_int(const moveonly_int&) = delete; moveonly_int(moveonly_int&&) = default; void operator=(const moveonly_int&) = delete; moveonly_int& operator=(moveonly_int&&) = default; bool operator<(const moveonly_int& other) const { return value < other.value; } };
{ "domain": "codereview.stackexchange", "id": 42949, "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++, median", "url": null }
c++, median double midpoint(const moveonly_int& a, const moveonly_int& b) { double av = a.value; double bv = b.value; return std::midpoint(av, bv); } } TEST(Median, MoveOnly) { std::array<test::moveonly_int, 4> values{0, 1, 2, 3}; EXPECT_EQ(median::value(values), 1.5); } Here's the implementation: #include <algorithm> #include <concepts> #include <functional> #include <iterator> #include <numeric> #include <ranges> #include <utility> #include <vector> namespace median { // Return a pair of iterators to the two median values // If the input is of even length, an identical pair is returned template<std::ranges::forward_range Range, typename Compare = std::less<>> auto iterators(const Range& values, Compare compare = {}) -> std::pair<std::ranges::iterator_t<const Range>, std::ranges::iterator_t<const Range>> { auto const begin = std::ranges::begin(values); auto const end = std::ranges::end(values); auto const size = std::distance(begin, end); switch (size) { case 0: throw std::domain_error("Attempting median of empty range"); case 1: return {begin, begin}; case 2: auto a = begin; auto b = a; ++b; if (!compare(*a, *b)) { std::swap(a, b); } return {a, b}; } auto const it_cmp = [compare](auto a, auto b){ return compare(*a, *b); }; std::vector<std::ranges::iterator_t<const Range>> iters; iters.reserve(size); for (auto it = begin; it != end; ++it) { iters.push_back(it); } auto upper = iters.begin() + size / 2; std::ranges::nth_element(iters, upper, it_cmp); auto lower = size % 2 ? upper : std::max_element(iters.begin(), upper, it_cmp); return {*lower, *upper}; }
{ "domain": "codereview.stackexchange", "id": 42949, "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++, median", "url": null }
c++, median auto midval(auto iter_pair) requires requires{ *iter_pair.first; *iter_pair.second; } { using std::midpoint; auto const [a, b] = iter_pair; return midpoint(*a, *b); } template<typename ArithType> auto midval(auto iter_pair) requires requires(ArithType v){ v = *iter_pair.first; v = *iter_pair.second; } { using std::midpoint; ArithType const a = *iter_pair.first; ArithType const b = *iter_pair.second; return midpoint(a, b); } template<typename ArithType> auto value(const auto& values) { return midval<ArithType>(iterators(values)); } template<typename ArithType> auto value(const auto& values, auto compare) { return midval<ArithType>(iterators(values, compare)); } auto value(const auto& values) { return midval(iterators(values)); } auto value(const auto& values, auto compare) { return midval(iterators(values, compare)); } } I've compiled with plenty of warnings, and run the tests under Valgrind to eliminate any silly dangling-iterator problems. Some specific concerns: Have I omitted any useful tests? Do I really need four overloads of median::value? I accept that the two midval() implementations are different enough that they are necessary. Is throwing std::domain_error an appropriate reaction to empty input? Is passing compare by value the correct choice? The standard algorithms do so, and I guess one can use a std::reference_wrapper to override that (if we're gathering execution statistics, perhaps). Have I missed any useful constraints on the template types? Anything else worthy of note.
{ "domain": "codereview.stackexchange", "id": 42949, "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++, median", "url": null }
c++, median I started off with a different implementation using std::multiset (passing the same test suite), which only needs to store only half as many iterators (but I suspect that set overheads, and the possibility of three O(log n) set operations per element in the second half, probably wipe out any space and time advantages, respectively). Here it is, anyway (we need to include <cassert> and <set> instead of <algorithm> and <vector>): std::multiset<std::ranges::iterator_t<const Range>, decltype(it_cmp)> sorted(it_cmp); auto const halfway = begin + size/2 + 1u; for (auto it = begin; it != halfway; ++it) { sorted.insert(it); } for (auto it = halfway; it != end; ++it) { auto last = sorted.end(); --last; if (it_cmp(it, *sorted.begin())) { // before first sorted.erase(last); } else if (it_cmp(it, *last)) { // before last sorted.erase(last); sorted.erase(sorted.begin()); sorted.insert(it); } else { // after last sorted.erase(sorted.begin()); } } // sorted contains one element for odd-length input, or two // elements for even-length input. assert(sorted.size() == 1u + !(size % 2)); auto m = sorted.begin(); auto n = sorted.end(); return {*m, *--n}; Although I'm not using this version, please do feel free to review it - I'm always looking to learn! Answer: Answers to your questions Have I omitted any useful tests? Yes. While you did test the edge case of an empty range, there are other edge cases and extreme values that you should test. For example, the median of {INT_MIN, INT_MAX} for example. Also, consider the median of something with plus and/or minus infinity, and the median of some array with a few NaNs randomly scattered in.
{ "domain": "codereview.stackexchange", "id": 42949, "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++, median", "url": null }
c++, median Do I really need four overloads of median::value? I accept that the two midval() implementations are different enough that they are necessary. You can easily get rid of one by having the first templated one use a default value for the comparator: template<typename ArithType, typename Compare = std::less<>> auto value(const auto& values, Compare compare = {}) { return midval<ArithType>(iterators(values, compare)); } If you could provide a default value for ArithType, you wouldn't need the untemplated overloads. However, you can't, unless you use a hack like: template<typename ArithType = void, typename Compare = std::less<>> auto value(const auto& values, Compare compare = std::less<>{}) { if constexpr (std::is_same_v<ArithType, void>) return midval(iterators(values, compare)); else return midval<ArithType>(iterators(values, compare)); } Is throwing std::domain_error an appropriate reaction to empty input? I would allow it, although one might also argue that std::invalid_argument is more appropriate. Is passing compare by value the correct choice? The standard algorithms do so, and I guess one can use a std::reference_wrapper to override that (if we're gathering execution statistics, perhaps). I would copy the semantics of the STL. Have I missed any useful constraints on the template types? Yes. I would require that the value type of the range and the comparator satisfy the std::strict_weak_order concept. Basically, that ensures that you can sort the values. You could also define a concept that checks that midpoint() can be applied, so that trying to get the median of an array of std::strings will result in a better error message, but on the other hand some people might argue that that would be too specific a concept. Ideally, std::is_arithmetic would be a good choice, except it only allows built-in types. Anything else worthy of note.
{ "domain": "codereview.stackexchange", "id": 42949, "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++, median", "url": null }
c++, median Anything else worthy of note. See below. It might be more expensive to sort iterators than to copy the range A std::vector of iterators might be a lot more expensive to sort than to just copy the values themselves into a new std::vector, especially if you just want the median of ints, floats or doubles. The iterator type of some containers can be quite large, and you pay for the extra indirection. On the other hand, your solution works well even if the input is a container of uncopyable and unmovable types, or if the value type itself is very large (for example, bignums). Consider adding a projection parameter Using a custom midpoint() function works if ADL works. But consider that I want to get the median of std::complex<double> numbers, sorted on their absolute value. The only way to make this work with your code is to inject an overload for std::midpoint() into namespace std, which is not so nice. Having a projection parameter avoids this issue.
{ "domain": "codereview.stackexchange", "id": 42949, "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++, median", "url": null }
c#, bitwise Title: Calculate Hamming distance between integers with bitwise operations Question: I recently learned about the Hamming distance. The use-case I found it through was actually working with integers instead of strings, yet its implementation was using string comparison. I was pretty sure it could be done with bitwise operations, and from what I can tell, my implementation is successful. public int HammingDistance(int x, int y) { int xor = x ^ y; int distance = 0; while (xor > 0) { distance++; xor &= xor - 1; } return distance; } However, I can't help but wonder if this makes the code harder to understand for others. Additionally, is there a way to eliminate the while loop but still count the number of set bits in the xor result in a more efficient manner? Feel free to test it out on .NET Fiddle. Answer: I was pretty sure it could be done with bitwise operations You are right. my implementation is successful No. Think of negative x (or negative y). The loop would terminate immediately. if this makes the code harder to understand for others No. Anybody who understands Hamming distance shall understand this bit-fiddling. is there a way to eliminate the while loop I don't know a portable way. For the native integral datatypes, all major architectures have a popcount instruction. gcc offers it as a __builtin_popcount. c++20 offers std::popcount. In all mainstream architectures both map to a single instruction. I am sure that c# does not lag. For the integral larger than native (like BigInteger and the family), the answer is no.
{ "domain": "codereview.stackexchange", "id": 42950, "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#, bitwise", "url": null }
php Title: array_reduce() for calculating totals Question: Below is a snippet that uses array_reduce() to calculate totals from a detailed dataset. The data shown is representative of a larger dataset. This code outputs the expected results. I'm seeking some peer input on how this array_reduce() is written because this is my first time using it in PHP. I'm more familiar with JavaScript .reduce() function. Is there a more concise way to write this? <?php $data = [ 'header' => [ 'customerId' => 28449, 'locationId' => 1278, 'orderId' => 764, 'orderDate' => '2022-02-01' ], 'detail' => [ '0' => [ 'itemId' => 210711, 'orderQuantity' => 10, 'fillQuantity' => 8, 'unitPrice' => 120.54 ], '1' => [ 'itemId' => 582284, 'orderQuantity' => 151, 'fillQuantity' => 144, 'unitPrice' => 85.68 ], '2' => [ 'itemId' => 476537, 'orderQuantity' => 87, 'fillQuantity' => 87, 'unitPrice' => 25.75 ] ] ]; $initialValues = array_fill_keys(['itemCount', 'orderQuantity', 'fillQuantity'], 0); $totals = []; $totals = array_reduce($data['detail'], function ($result, $item) { $result['itemCount']++; $result['orderQuantity'] += $item['orderQuantity']; $result['fillQuantity'] += $item['fillQuantity']; return $result; }, $initialValues); echo '<pre>' . print_r(['data' => $data, 'totals' => $totals], 1) . '</pre>'; ?> Here is the 'totals' output, which is correct: [totals] => Array ( [itemCount] => 3 [orderQuantity] => 248 [fillQuantity] => 239 )
{ "domain": "codereview.stackexchange", "id": 42951, "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": "php", "url": null }
php Answer: I don't see anything to improve inside the callback body. I do prefer to eliminate single-only variable declarations unless the declaration improves readability or breaks up excessively wide lines of code. From PHP7.4, concise "arrow function syntax" (fn() => ...) is available, but it cannot be used with array_reduce() because the syntax does not allow multiline bodies. (Although there is a proposal to accommodate multiline bodies with less syntax -- PHP RFC: Auto-capturing multi-statement closures) If you are going to write function parameters on multiple lines, then write all parameters on separate lines for easier (human) reading. Declaring $total as an empty array then immediately and unconditionally overwriting it is not needed -- just omit the empty declaration. Suggested code: $totals = array_reduce( $data['detail'], function ($result, $item) { ++$result['itemCount']; $result['orderQuantity'] += $item['orderQuantity']; $result['fillQuantity'] += $item['fillQuantity']; return $result; }, array_fill_keys(['itemCount', 'orderQuantity', 'fillQuantity'], 0) );
{ "domain": "codereview.stackexchange", "id": 42951, "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": "php", "url": null }
php, laravel Title: Retrieve config values using custom helper Question: I've stored a set of theme related configuration in a config file. config/theme.php // ... $component = [ 'componentA' = [ 'size' => 'componentDefaultSize', 'color' => [ 'default' => 'componentDefaultColor', 'success' => 'componentSuccessColor', ] 'background' => [ 'light' => 'componentLightBackground', 'dark' => 'componentDarkBackground', ] ] ]; return [ // ... 'component' => $component, ]; This helper function below retrieve related values should the parameters match with keys from theme.php. The parameters are as below string $type // Type of theme. string $component // Name of component. array $properties // Optional properties key name. If not defined, retrieve first array value. function getTheme(string $type, string $component, array $properties = null) { $theme = null; $styles = config("theme.$type.$component"); foreach ($styles as $style) { if (is_array($style)) { // If $properties exist retrieve match key value, else retrieve first value of array if (isset($properties)) { foreach ($style as $key => $class ) { foreach ($properties as $property) { if ($key == $property) { $theme .= $class.' '; } } } } else { $theme .= $style[0].' '; } } else { $theme .= $style.' '; } } return $theme; } I'm trying to reduce the deep nesting for helper function above but I'm not sure how to achieve that. Example usage of the helper: // Without properties $theme = getTheme('component', 'componentA'); // Return all values and first value of an array // With properties $color = 'success'; $theme = getTheme('component', 'componentA', [$color]); // With multiple properties $color = 'success'; $background = 'dark'; $theme = getTheme('component', 'componentA', [$color, $background]);
{ "domain": "codereview.stackexchange", "id": 42952, "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": "php, laravel", "url": null }
php, laravel Assistance is much appreciated. Edited: 1st Attempt: Toby's comment gave me an idea. function getTheme(string $type, string $component, array $keys = null) { $theme = null; $properties = config("theme.$type.$component"); foreach ($properties as $property) { if (is_array($property) && isset($keys)) { if(array_intersect(array_keys($property), $keys)){ foreach($keys as $key){ $theme .= $property[$key].' '; } } else { $theme .= reset($property).' '; } } else if (is_array($property)) { $theme .= reset($property).' '; } else { $theme .= $property.' '; } } return $theme; } I switched $properties to $keys for better readability. I still don't like $theme .= reset($property).' '; is called twice. 2nd attempt: I've managed to refactor it to as below: function getTheme(string $type, string $component, array $keys = null) { $theme = null; $properties = config("theme.$type.$component"); foreach ($properties as $property) { if (is_array($property) && isset($keys)) { $theme .= implode(' ', array_values(array_intersect_key($property, array_fill_keys($keys, '')))).' '; } else if (is_array($property)) { $theme .= reset($property).' '; } else { $theme .= $property.' '; } } return $theme; } Works fine for now but $theme .= implode(' ', array_values(array_intersect_key($property, array_fill_keys($keys, '')))).' '; is a bit of a stretch. Answer: I'll review your 2nd and most recent refactor.
{ "domain": "codereview.stackexchange", "id": 42952, "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": "php, laravel", "url": null }
php, laravel Answer: I'll review your 2nd and most recent refactor. Your function getTheme() builds a space-delimited string of class values. Your current function name is clear about the intent, but perhaps a little unclear on the data that it returns. You might consider a more descriptive name or declaring the return type. On the topic of the return type, your function is returning a nullable string. Is there a benefit to returning null? Would you be just as happy to return an empty string? I prefer to reduce the total number of returnable data types so that dependent scripts don't need to juggle as much. I don't ever use nullable array types. An empty array is falsey and I rely on that fact to make functionless conditional checks which makes nullability unnecessary. Because you are using concatenation and appending a space after every class name, you will have a result string with a dangling space. This means your string will either not be perfectly clean, or a trim() call will be necessary. I would, instead, use a temporary array, then implode before returning the value. When writing your looped condition block, handle the easier, negative outcomes first. Processing the non-array $property in the first branch means that you won't need to check the data type again in subsequent branches. As mentioned earlier, you can use !$keys to determine if an array is empty. To mutate the $keys values to keys, you can just flip the array instead of assigning values which will never be used. Do this only once before looping the properties. Use a variadic push array_merge() to merge your filtered associative array of classnames into the temporary array. Oh, and elseif is one word in PHP.
{ "domain": "codereview.stackexchange", "id": 42952, "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": "php, laravel", "url": null }
php, laravel Oh, and elseif is one word in PHP. Code: function getTheme( string $type, string $component, array $keys = [] ): string { $classNames = []; $properties = config("theme.$type.$component"); $whitelist = array_flip($keys); foreach ($properties as $property)) { if (!is_array($property) { $classNames[] = $property; } elseif (!$keys) { $classNames[] = reset($property); } else { $classNames = array_merge( $classNames, array_intersect_key($property, $whitelist) ); } } return implode(' ', $classNames); }
{ "domain": "codereview.stackexchange", "id": 42952, "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": "php, laravel", "url": null }
python, python-3.x, csv, formatting, ascii-art Title: Create an ASCII table from CSV Question: The following code convert csv to ascii table. #!/usr/bin/env python3 import sys import argparse import logging import prettytable import csv parser = argparse.ArgumentParser() parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), default=sys.stdin) parser.add_argument( '-d', '--debug', help="Print lots of debugging statements", action="store_const", dest="loglevel", const=logging.DEBUG, default=logging.WARNING, ) parser.add_argument( '-v', '--verbose', help="Be verbose", action="store_const", dest="loglevel", const=logging.INFO, ) args = parser.parse_args() # taking input from stdin which is empty, so there is neither a stdin nor a file as argument if sys.stdin.isatty() and args.infile.name == "<stdin>": sys.exit("Please give some input") logging.basicConfig(level=args.loglevel) # # Business Logic Here table = None content = csv.reader(args.infile, delimiter=',', quotechar='"') for row in content: if table is None: table = prettytable.PrettyTable(row) else: table.add_row(row) print(table) Please let me know how I can make this code better. Answer: I don't understand the point of this test: if sys.stdin.isatty() and args.infile.name == "<stdin>": sys.exit("Please give some input") We want to disallow a particular file name, but only if we're connected to a tty? If you want to prompt when input is coming from stdin, then we shouldn't be testing the file name, but instead its properties. And I don't see why we should exit in this case (e.g. we might want to type directly, or copy-paste input). I suggest: if args.infile.isatty(): print("Please enter your data:") We might want to add a hint such as Finish with control-D - I'll leave it as an exercise to discover the terminal's control bindings and print the correct keystroke.
{ "domain": "codereview.stackexchange", "id": 42953, "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, csv, formatting, ascii-art", "url": null }
python, python-3.x, csv, formatting, ascii-art We don't need to read one row at a time. prettytable can do that for us: table = prettytable.from_csv(args.infile) However, it requires the stream to be seekable, so if it's not, we'll need to read it into memory and pass that as a stream: if not args.infile.seekable(): from io import StringIO args.infile = StringIO(args.infile.read()) table = prettytable.from_csv(args.infile) It's probably a good idea to print only the message from any exceptions, rather than an entire backtrace (unless the user asks for the extra detail): try: if not args.infile.seekable(): from io import StringIO args.infile = StringIO(args.infile.read()) print(prettytable.from_csv(args.infile)) except Exception as e: logging.error(e, exc_info=(args.loglevel<=logging.DEBUG)) exit(1) Modified code #!/usr/bin/env python3 import sys import argparse import logging import prettytable import csv parser = argparse.ArgumentParser() parser.add_argument( "infile", nargs="?", type=argparse.FileType("r"), default=sys.stdin ) parser.add_argument( '-d', '--debug', help="Print lots of debugging statements", action="store_const", dest="loglevel", const=logging.DEBUG, default=logging.WARNING, ) parser.add_argument( '-v', '--verbose', help="Be verbose", action="store_const", dest="loglevel", const=logging.INFO, ) args = parser.parse_args() logging.basicConfig(level=args.loglevel) if args.infile.isatty(): print("Please enter your data:") try: if not args.infile.seekable(): from io import StringIO args.infile = StringIO(args.infile.read()) table = prettytable.from_csv(args.infile) print(table) except Exception as e: logging.error(e, exc_info=(args.loglevel<=logging.INFO)) exit(1)
{ "domain": "codereview.stackexchange", "id": 42953, "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, csv, formatting, ascii-art", "url": null }
performance, php, sql, php7, yii Title: Archiving / Moving Data from one database server to another database server Question: I am working on an SMS marketing project based on Yii2 Framework (PHP 7.3 & MariaDb (innodb engine)) where we have to move the logs from different tables to the archive db, which is total a different DB server from the live one. The log tables keep growing and we had to setup an automated job which runs 3 times a week at midnight and will keep filtering out the logs that are older than 45 days and move them to another database. I decided to use the Range partitioning and then use EXCHANGE PARTITION to move all the related data to a separate new table so that i keep the main/live table locked for partition process only and keep the copying/moving process that involves Select operation on a different table. So I divided the whole process into 2 different processes. Partitioning Archiving The partition process is further divided into Drop any Previously created Backup tables Create a new backup table like live table Create Partition on live table Exchange the partition with the backup table Remove the partition from the live table.
{ "domain": "codereview.stackexchange", "id": 42954, "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": "performance, php, sql, php7, yii", "url": null }
performance, php, sql, php7, yii My main focus is on the partition process if it can be improved to work more efficiently and less time. Currently I have the following stats for the partition process; I am only adding for one of the large tables Transaction History table stats Rows : total 172,899,990 rows approx Time to Partition : 1472.429115057 secs(24.54048525095 Mins) with total rows in the partition (12,937,902) Exchange partition : 0.062991857528687 secs Removed Partition : 1293.8012390137 secs.(21.56335398356167 Mins) Transaction History Schema CREATE TABLE `transaction_history` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `amount` decimal(19,6) NOT NULL, `description` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, `transaction_type` varchar(30) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'blast', `remaining_balance` decimal(19,6) NOT NULL, `created_at` timestamp NOT NULL DEFAULT current_timestamp(), `updated_at` timestamp NULL DEFAULT NULL ON UPDATE current_timestamp(), PRIMARY KEY (`id`,`created_at`), KEY `transaction_type` (`transaction_type`), KEY `user_id_transaction_type` (`user_id`,`transaction_type`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci The code is for the Yii2 console app. <?php namespace console\controllers; use Yii; use DateTime; use Exception; use DateInterval; use yii\helpers\Console; use yii\console\Controller; use yii\helpers\ArrayHelper; use console\controllers\traits\ArchiveTraits;
{ "domain": "codereview.stackexchange", "id": 42954, "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": "performance, php, sql, php7, yii", "url": null }
performance, php, sql, php7, yii class PartitionController extends Controller { use ArchiveTraits; /** * Contains array of tables and their range column to be used for partition * in the key=>value format like [table_name=>range_column_name] * * Note: before you add any new table to the below list make sure you have * added the range column to unique index or part of the primary key */ const BACKUP_TABLES = [ 'message_inbound' => 'created_at', 'transaction_history' => 'created_at', 'sms_api_log' => 'created_at', 'balance_history' => 'created_on', 'buy_number_logs' => 'created_at', 'destination_delivery' => 'created_at', 'message_delivery' => 'created_at', 'email_delivery_logs' => 'created_at', 'responder_keywords_logs' => 'created_at', 'sms_alert_logs' => 'created_at', 'suppression_message_logs' => 'created_at', ]; private $_date = null; /** * @var batch size for the * inserts in the database */ const BATCH_SIZE = 10000; /** * @var limit for the rows to be migrated to the * database in one iteration */ const MIGRATE_LIMIT = 50000; public function actionIndex($date = null) { $this->_date = $date; $this->startNotification("Partition Process started", 'partition-start'); ini_set("memory_limit", 0); $this->stdout("Starting Partition Process.\n"); $this->startPartition(); $this->stdout("Completed Partition Process.\n"); $date = date("Y-m-d"); $this->sendSummaryReport("Partitioning Process Complete for {$date}", "partition-complete", "partition"); } /** * @param int $start the start timestamp */ public function end($start) { return microtime(true) - $start; } public function start() { return microtime(true); }
{ "domain": "codereview.stackexchange", "id": 42954, "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": "performance, php, sql, php7, yii", "url": null }
performance, php, sql, php7, yii public function start() { return microtime(true); } /** * Starts the partitioning process for the live DB log tables * * @return null * @throws Exception */ protected function startPartition() { foreach (self::BACKUP_TABLES as $tableName => $rangeColumn) { try { $this->partitionNow($tableName, $rangeColumn); $this->stdout("\n"); } catch (Exception $e) { $this->sendExceptionEmail($tableName, $e, "Exception on Partitioning table", "partition-exception"); $this->stdout("There was an error while trying to archive the {$tableName} .\n"); $this->stdout($e->getMessage() . "\n===============\n"); $this->stdout("Continuing to archive the next table.\n"); } } } /** * Creates the backup for the specified table and the range column * by creating a partition and then exchanging the old data * partition with the backup table and then move the data to the * archive database * * @param string $tableName the name of the table to backup data from live DB * @param string $rangeColumn the name of the column used for the range partition * * @return null */ protected function partitionNow($tableName, $rangeColumn = 'created_at') { $rangeOldPartition = $this->rangeOldPartition(); $backupTableName = $this->generateBackupTableName($tableName); $dbLive = self::_getDsnAttribute('dbname'); //drop backup table if exists $this->dropBackupTables($tableName); $this->stdout("Started Partitioning {$tableName}\n"); $startTime = $this->start();
{ "domain": "codereview.stackexchange", "id": 42954, "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": "performance, php, sql, php7, yii", "url": null }
performance, php, sql, php7, yii $this->stdout("Started Partitioning {$tableName}\n"); $startTime = $this->start(); try { $sql = <<<SQL -- create the backup table and remove partitioning from the backup table CREATE TABLE `{$dbLive}`.{{%{$backupTableName}}} LIKE `{$dbLive}`.{{%{$tableName}}}; -- start partitioning the source table ALTER TABLE `{$dbLive}`.{{%{$tableName}}} PARTITION BY RANGE(UNIX_TIMESTAMP({$rangeColumn})) ( PARTITION oldPt VALUES LESS THAN (UNIX_TIMESTAMP("{$rangeOldPartition}")), PARTITION activePt VALUES LESS THAN (MAXVALUE) ); SQL; $command = Yii::$app->db->createCommand($sql); $command->execute(); //necessary to catch exceptions or errors when // using multiple SQL statements with createcommand while ($command->pdoStatement->nextRowSet()) { //leave blank do nothing } $this->stdout("Partitioned table in {$this->end($startTime)} secs.\n", Console::FG_GREEN); $startTime = $this->start(); $sql = <<<SQL -- exchange the partition with the backup table ALTER TABLE `{$dbLive}`.{{%{$tableName}}} EXCHANGE PARTITION oldPt WITH TABLE `{$dbLive}`.{{%{$backupTableName}}}; SQL; $command = Yii::$app->db->createCommand($sql); $command->execute(); $this->stdout("Completed Exchange partition {$this->end($startTime)} secs\n"); $startTime = $this->start(); $sql = <<<SQL -- remove partition from the source table once data moved to separate table ALTER TABLE `{$dbLive}`.{{%{$tableName}}} REMOVE PARTITIONING; SQL; $command = Yii::$app->db->createCommand($sql); $command->execute();
{ "domain": "codereview.stackexchange", "id": 42954, "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": "performance, php, sql, php7, yii", "url": null }
performance, php, sql, php7, yii $this->stdout("Removed Partition in {$this->end($startTime)} secs.\n"); $this->stdout("Filterd out data from live table.\n"); } catch (Exception $e) { throw $e; } } /** * Takes the source table name ad * * @param $tableName */ protected function dropBackupTables($tableName) { $backupTableName = $this->generateBackupTableName($tableName); $sql = <<<SQL DROP TABLE IF EXISTS {{%{$backupTableName}}}; SQL; Yii::$app->db->createCommand($sql)->execute(); } /** * Generates the backup table name from the source table name * * @param string $tableName the source table to mock the backup table from * * @return string $backupTableName the name of the backup table */ protected function generateBackupTableName($tableName) { $backupTableAlias = 'bkp_' . date('Ymd') . '_'; return "{$backupTableAlias}{$tableName}"; } /** * Returns the create table command for the given table * @param $tableName */ protected function getCreateTable($tableName) { $data = Yii::$app->db->createCommand("show create table {{%{$tableName}}}")->queryOne(); return str_replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS', $data['Create Table']); } /** * @param $tableName */ protected function getPageData($tableName, $offset = 0) { $limit = self::MIGRATE_LIMIT; $sql = <<<SQL SELECT * FROM {{%{$tableName}}} order by id LIMIT {$offset},{$limit} SQL; return Yii::$app->db->createCommand($sql)->queryAll(); }
{ "domain": "codereview.stackexchange", "id": 42954, "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": "performance, php, sql, php7, yii", "url": null }
performance, php, sql, php7, yii /** * @param $tableName */ protected function getRowCount($tableName) { $sql = <<<SQL SELECT COUNT(*) as total FROM {{%{$tableName}}} SQL; $data = Yii::$app->db->createCommand($sql)->queryOne(); $this->stdout("Found {$data['total']} records."); return $data['total']; } /** * Returns the columns names for a table * * @param string $db the database name * @param string $tableName the table name * * @return mixed */ protected function getTableColumns($db, $tableName) { $sql = <<<SQL select COLUMN_NAME from information_schema.columns where table_schema = "{$db}" and table_name="{$tableName}" order by table_name,ordinal_position; SQL; return ArrayHelper::getColumn( Yii::$app->db->createCommand($sql)->queryAll(), 'COLUMN_NAME' ); } /** * Returns the date for the specified interval * to backup default interval is 45 days. * * @return mixed */ protected function rangeOldPartition() { $date = new DateTime(); $date->sub(new DateInterval('P0M45D')); return $date->format("Y-m-d"); }
{ "domain": "codereview.stackexchange", "id": 42954, "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": "performance, php, sql, php7, yii", "url": null }
performance, php, sql, php7, yii /** * Returns the database name after extracting the * specific string from the Dsn property * * @param string $name the name of the property in dsn string. * @param string $target the target connection of the database live|archive, default "live" * * @return mixed */ private static function _getDsnAttribute($name, $target = 'live') { if ($target === 'live') { if (preg_match("/{$name}=([^;]*)/", Yii::$app->getDb()->dsn, $match)) { return $match[1]; } } else { if (preg_match("/{$name}=([^;]*)/", Yii::$app->db_backup->dsn, $match)) { return $match[1]; } } throw new Exception("Unable to extract the db Name"); } } Answer: As I see it, 99% of your code is spent in ALTER TABLE -- both in adding partitioning in REMOVE PARTITIONING, so my answer focuses on how to speed up those steps. The following may eliminate most of that 99%. Adding partitioning to a non-partitioned table takes a long time because it must copy all the data over and reconstruct all the indexes. [In the following example, I am assuming that each partition holds on month's worth of data, and the March, 2022 partition is called p202203.] Leave the table partitioned, then do only ALTER TABLE ... EXCHANGE PARTITION ...` -- fast for removing a partition ALTER TABLE ... REORGANIZE PARTITION future INTO PARTITION p202203 VALUES LESS THAN (TO_DAYS('2022-04-01')), PARTITION future VALUES LESS THAN MAXVALUE;
{ "domain": "codereview.stackexchange", "id": 42954, "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": "performance, php, sql, php7, yii", "url": null }
performance, php, sql, php7, yii Do that right before 04/01, while future is empty (or at least very small); it will take essentially no time. More details and examples: Partitioning and Transportable tablespaces for 5.7+ For your situation, daily partitions and doing the REORGANIZE PARTITION just before midnight is optimal to minimize shoveling data around. DROP PARTITION just after midnight takes care of data for more than 45 days ago. Please provide the main SELECTs, I may have further advice on Indexing. (I worry, especially, about the low cardinality of transaction_type.) A minor change: Do the archiving nightly and have 48 'daily' partitions (see the first link for discussion).
{ "domain": "codereview.stackexchange", "id": 42954, "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": "performance, php, sql, php7, yii", "url": null }
javascript, php, mysql, escaping Title: url encoding and storing (JS, PHP, MySQL) Question: This question is about how best to encode, send and store information between JavaScript, PHP, and MySQL I am doing a GET request from HTML/JavaScript to my PHP server, which is then storing the data in mySQL. My solution in the one case I've been using it in, and I think it should work in all cases (If it won't, please let me know?) I got tripped up for a bit by difference between php and javascript uri/urlencoding. JavaScript encodes spaces as "%20"s, but php encodes spaces with "+". So now what I am doing is converting all spaces to pluses before I uriEncode in JavaScript JavaScript: docTitleInput.value = encodeURI(document.title.replace(/\s/g,"+")); PHP: In PHP I am directly storing the encoded value in MySQL For instance, the string: '"Problems" in myApp' is stored in MySQL as %22Problems%22+in+myApp I thought this might be better than storing the decoded string, as quotes and other special characters can make db querying more difficult, in my experience. On the other hand, it makes data in the db harder to read... Am I wrong in this thinking? Somewhere else I am looking up the hash (in another column) by sending this encoded string to PHP and use PHP to query the DB with exactly what's sent from JavaScript. $stmt = $pdo->prepare("select hash from b where c=? and d=?"); And executed where d is %22Problems%22+in+myApp Is this the best way to do what I am doing? Am I going to come to regret storing document titles in their encoded form? Anyone with experience in these kinds of things, I'd appreciate your insights
{ "domain": "codereview.stackexchange", "id": 42955, "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, php, mysql, escaping", "url": null }
javascript, php, mysql, escaping Answer: Yeah, I have a recommendation that I think will save you a few headaches. Understand what the unencoded string is: where a space is just a space (not a %20 or a +). And importantly, an ampersand is an ampersand (not &amp;&), a is a (not that various encodings of or "\uD83D\uDCA9" or \01f4a9 or %F0%9F%92%A9), etc. When in a programming language, don't carry around an encoding for a different medium-- it gets confusing too fast. PHP and Javascript strings should be able to hold "unencoded" unicode strings, but calling this "unencoded" is deceptive, as they are simply encoded in a specific way, for that language. You could say, "javascript encoded" or "php encoded". If you do that, you see why it's then confusing to say "javascript encoded and then url query parameter encoded". (A tangential point: URL encodings are hard because different pieces of a URL have slightly different encodings.) Once you have your strings in a "native" format for a given programming language, then it becomes clear that you need to encode it appropriately for that medium as you use it. To build a URL, you'll need to use the appropriate function to encode a given piece of the URL. Or, for the database, use the database driver encoding functions, which do the proper thing like escaping quotes and getting unicode in the expected way. Likewise, there will be corresponding tools to decode the pieces when received. Do this as they are marshalled into Javascript or PHP. In this way you are just dealing with one translation of a string at a time. If you later then need to query the database for a given string, it's straightforward how to do this. And, if you're outputting it onto a web page, it's clear that you need to encode the <, >, and sometimes &.
{ "domain": "codereview.stackexchange", "id": 42955, "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, php, mysql, escaping", "url": null }
javascript, php, mysql, escaping Honestly, you're not saving yourself any effort by carrying around URL encoded strings in the database. Also, if you keep it simply like this, when something goes wrong, it's pretty easy to diagnose. With layers of encoding it can be a complex logic puzzle. I hope this helps!
{ "domain": "codereview.stackexchange", "id": 42955, "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, php, mysql, escaping", "url": null }
java, android, calculator Title: Calculator app made in Java (ver2) Question: A few days ago, I uploaded my first version of my calculator app I made in android studio. I got some great some feedback on it and tried to improve my app as much as I could. changes/new featres: Implemented a delete button optimized the way, everything is calculated Made a seperate class for the calculator Here u can see how the app looks 1 Here is the code from the my MainActivity.java package com.example.calculatormk2; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { Calculator calculatorMain = new Calculator(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onNumberClick(View view) { calculatorMain.addDigitToInput(getTextFrom(view)); updateTextView(); } public void onOperatorClick(View view) { calculatorMain.addOperatorToInput(getTextFrom(view)); updateTextView(); } public void onEqualsClick(View v) { TextView mainOutput = findViewById(R.id.mainOutput); mainOutput.setText(calculatorMain.calculate()); } public void onDeleteClick(View v) { calculatorMain.delete(); updateTextView(); } public String getTextFrom(View v) { return ((Button) v).getText().toString(); } public void updateTextView() { TextView mainOutput = findViewById(R.id.mainOutput); mainOutput.setText(calculatorMain.getInput()); } } And here is the code from my Calculator.java package com.example.calculatormk2; import java.util.ArrayList; import java.util.Arrays; public class Calculator { private StringBuilder inputAsText = new StringBuilder(); private ArrayList inputAsArrayList;
{ "domain": "codereview.stackexchange", "id": 42956, "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": "java, android, calculator", "url": null }
java, android, calculator public void addDigitToInput(String digit) { inputAsText.append(digit); } public void addOperatorToInput(String operator) { inputAsText.append(" ").append(operator).append(" "); } public void delete() { if (inputAsText.length() != 0) { if (Character.isWhitespace(inputAsText.charAt(inputAsText.length() - 1))) { inputAsText.deleteCharAt(inputAsText.length() - 1); inputAsText.deleteCharAt(inputAsText.length() - 1); inputAsText.deleteCharAt(inputAsText.length() - 1); } else { inputAsText.deleteCharAt(inputAsText.length() - 1); } } } public void clearInput() { inputAsText.delete(0, inputAsText.length()); inputAsArrayList.clear(); } public String getInput() { return this.inputAsText.toString(); } public String calculate() { String[] tmpArray = inputAsText.toString().split(" "); inputAsArrayList = new ArrayList(Arrays.asList(tmpArray)); inputAsArrayList = calculateFor("x", "÷"); inputAsArrayList = calculateFor("+", "-"); String answer = String.valueOf(inputAsArrayList.get(0)); clearInput(); return answer; } public ArrayList calculateFor(String operator1, String operator2) { while (inputAsArrayList.contains(operator1) || inputAsArrayList.contains(operator2)) { int indexOperator1 = inputAsArrayList.indexOf(operator1); int indexOperator2 = inputAsArrayList.indexOf(operator2); int indexOperatorMain = Math.min(indexOperator1, indexOperator2); if (indexOperator1 == -1) { indexOperatorMain = indexOperator2; } else if (indexOperator2 == -1) { indexOperatorMain = indexOperator1; } String operatorMain = inputAsArrayList.get(indexOperatorMain).toString();
{ "domain": "codereview.stackexchange", "id": 42956, "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": "java, android, calculator", "url": null }
java, android, calculator String operatorMain = inputAsArrayList.get(indexOperatorMain).toString(); double firstNumber = Double.parseDouble(inputAsArrayList.get(indexOperatorMain - 1).toString()); double secondNumber = Double.parseDouble(inputAsArrayList.get(indexOperatorMain + 1).toString()); double answer = calculateSegment(firstNumber, secondNumber, operatorMain); inputAsArrayList.remove(indexOperatorMain - 1); inputAsArrayList.remove(indexOperatorMain - 1); inputAsArrayList.remove(indexOperatorMain - 1); inputAsArrayList.add(indexOperatorMain - 1, answer); } return inputAsArrayList; } public double calculateSegment(double fNumber, double sNumber, String o) { switch (o) { case "x": return fNumber * sNumber; case "÷": return fNumber / sNumber; case "+": return fNumber + sNumber; default: return fNumber - sNumber; } } } Im not sure if I want to make a 3rd version or move on to another project. (after ive learned more about android development) For a 3rd version, I really would like to implement a history that keeps track of all the calculations and answers and possibly also allow the ability to use a square root. One thing I could not figure out, is how to implement multithreading in my app. I wanted to calculate the answers on a different thread. (Start a new thread at the calculate() function) But I didnt know how to return my answer. This probably is useless because the calculations doenst even take 1 second, but it would be some great practise for later projects. Anyways, any feedback/suggestions on my app are welcome. Thanks for reading! (Git repository: https://github.com/PhilipNousPXL/Calculator-mk2.git)
{ "domain": "codereview.stackexchange", "id": 42956, "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": "java, android, calculator", "url": null }
java, android, calculator Answer: thanks for sharing your progress - looks far better than v1, gratulations :-) about history instead of a mere result-history i would advise you to create an input-history. Other people have already struggles with such an challange and created an Command Design Pattern from the GoF (Gang of four). Put your commands on a stack and you have a history - includng undo/redo! side note A Command would help you to stick with the Separation of Concerns since you would put these part of your code together that belong together. A Command would help you to stick with the Open Closed Principle since it would be very easy to create other command (as mentioned from you: a square root command?!) about concurrency if you have a time consuming process that should run aside from your GUI thread (in android) you should have a closer look at the Executors and Handlers (a very small tutorial is found here) - i am sorry that i cannot provide any details before you have tried to implement it. OOP calculator well that might be an never endig story, see this articel about oop calculator. This is a medium difficulty problem in Leetcode. This is medium only if you are talking in terms of algorithm and time complexity. But let’s say you have to build a calculator for an enterprise. The calculator that will be extensible, maintainable and optimized at the same time. So maybe this might be too much for now (since you said you are rather novice, first year? or so?) But with an OOP approach you could at least try to get rid of your input model ArrayList<String> inputAsArrayList - which is really a pain. cool stuff you really did clean up your MainActivity - now it really looks cool and you may be very proud of you in doing it this way!!! keep up that spirit!!
{ "domain": "codereview.stackexchange", "id": 42956, "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": "java, android, calculator", "url": null }
c++, overloading Title: Syntax to Overload the Post-Increment Operator ++ as a Nonmember Function Question: I know this may be a silly question, but... is it really necessary to add the parameter name (int <parameter_name>), instead of just (int) in a definition of an operator function to overload "++" ( post-increment) ? or would it be optional? example: /* function prototype */ friend Cylinder operator++(Cylinder&, int); /* function definition */ Cylinder operator++(Cylinder& n, int u) { Cylinder temp = n; (n.radius)++; (n.height)++; return (temp); } and here it is the same except that it does not have the name of the parameter in the definition function (I only ask, because I am curious, that even though it does not have it, the program still works, and also if it would be good practice to put it or not?): Example: /* function prototype */ friend Cylinder operator++(Cylinder&, int); /* function definition */ Cylinder operator++(Cylinder& n, int) { Cylinder temp = n; (n.radius)++; (n.height)++; return (temp); } Full program: main.cpp #include <iostream> #include <cstdlib> #include "Cylinder.h" using namespace std; int main(void) { Cylinder Cylinder1(5.0, 10.0); //radius = 5.0 and height = 10.0 Cylinder Cylinder2(3.5, 20.0); //radius = 3.5 and height 20.0 Cylinder Cylinder3; Cylinder Cylinder4; Cylinder Cylinder5; cout << "Cylinder1 --- " << Cylinder1 << endl; cout << "Cylinder2 --- " << Cylinder2 << endl; Cylinder3 = Cylinder1 + Cylinder2; cout << "Cylinder1 + Cylinder2 = " << "Cylinder3 --- " << Cylinder3 << endl; Cylinder4 = Cylinder1 - Cylinder2; cout << "Cylinder1 - Cylinder2 = " << "Cylinder4 --- " << Cylinder4 << endl; Cylinder5 = Cylinder1 * Cylinder2; cout << "Cylinder1 * Cylinder2 = " << "Cylinder5 --- " << Cylinder5 << endl;
{ "domain": "codereview.stackexchange", "id": 42957, "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++, overloading", "url": null }
c++, overloading cout << "Compare Cylinder1 > Cylinder2 --- " << endl; if (Cylinder1 > Cylinder2) cout << "Cylinder1 is greater than Cylinder2." << endl; else cout << "Cylinder1 is less than or equal to Cylinder2." << endl << endl; Cylinder1++; cout << "Cylinder1++ --- " << endl; cout << "New dimension of Cylinder1: " << Cylinder1 << endl; Cylinder4 = Cylinder3++; cout << "Cylinder4 = Cylinder3++ --- " << endl; cout << "New dimension of Cylinder3: " << Cylinder3 << endl; cout << "New dimension of Cylinder4: " << Cylinder4 << endl; cout << "Cylinder4 != Cylinder3 --- Cylinder4 is " << (Cylinder4 != Cylinder3 ? "not equal to Cylinder3 " : "equal to Cylinder3") << endl; cout << "Cylinder4 >= Cylinder3 --- Cylinder4 is " << (Cylinder4 >= Cylinder3 ? "greater or equal to Cylinder3 " : "less than Cylinder3 ") << endl; cout << "Cylinder4 == Cylinder3 --- Cylinder4 is " << (Cylinder4 == Cylinder3 ? "equal to Cylinder3 " : "not equal to Cylinder3") << endl; cout << "Cylinder4 < Cylinder3 --- Cylinder4 is " << (Cylinder4 < Cylinder3 ? "less than Cylinder3 " : "greater than or equal to Cylinder3") << endl; cout << "Cylinder4 <= Cylinder3 --- Cylinder4 is " << (Cylinder4 <= Cylinder3 ? "less than or equal to Cylinder3 " : "greater than Cylinder3") << endl; exit(EXIT_SUCCESS); } Cylinder.cpp #include <iostream> #include "Cylinder.h" Cylinder::Cylinder(void) { this->radius = 1; this->height = 1; } Cylinder::Cylinder(double _radius, double _height) { this->radius = _radius; this->height = _height; } const Cylinder& Cylinder::operator=(const Cylinder &n) { this->radius = n.radius; this->height = n.height; return (*this); } Cylinder Cylinder::operator+(const Cylinder& n) const { Cylinder new_n; new_n.radius = radius + n.radius; new_n.height = height + n.height; return (new_n); }
{ "domain": "codereview.stackexchange", "id": 42957, "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++, overloading", "url": null }
c++, overloading Cylinder Cylinder::operator-(const Cylinder& n) const { Cylinder new_n; new_n.radius = radius - n.radius; new_n.height = height - n.height; return (new_n); } Cylinder Cylinder::operator*(const Cylinder& n) const { Cylinder new_n; new_n.radius = radius * n.radius; new_n.height = height * n.height; return (new_n); } bool Cylinder::operator==(const Cylinder& n) const { Cylinder new_n; return ((new_n.radius == n.radius && new_n.height == n.height) ? true : false); } bool Cylinder::operator!=(const Cylinder& n) const { Cylinder new_n; return ((new_n.radius != n.radius && new_n.height != n.height) ? true : false); } bool Cylinder::operator>=(const Cylinder& n) const { Cylinder new_n; return ((new_n.radius >= n.radius && new_n.height >= n.height) ? true : false); } bool Cylinder::operator>(const Cylinder& n) const { Cylinder new_n; return ((new_n.radius > n.radius && new_n.height > n.height) ? true : false); } bool Cylinder::operator<(const Cylinder& n) const { Cylinder new_n; return ((new_n.radius < n.radius && new_n.height < n.height) ? true : false); } bool Cylinder::operator<=(const Cylinder& n) const { Cylinder new_n; return ((new_n.radius <= n.radius && new_n.height <= n.height) ? true : false); } Cylinder operator++(Cylinder& n, int) { Cylinder temp = n; (n.radius)++; (n.height)++; return (temp); } ostream &operator<<(ostream& out, const Cylinder& n) { out << "Radius: " << n.radius << '\t' << "Height: " << n.height << std::endl; return (out); } Cylinder.h #ifndef CYLINDER_H_INCLUDED #define CYLINDER_H_INCLUDED using namespace std; class Cylinder { public: /* function members */ Cylinder(void); Cylinder(double, double); const Cylinder& operator=(const Cylinder &);
{ "domain": "codereview.stackexchange", "id": 42957, "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++, overloading", "url": null }
c++, overloading Cylinder operator+(const Cylinder&) const; Cylinder operator-(const Cylinder&) const; Cylinder operator*(const Cylinder&) const; bool operator==(const Cylinder&) const; bool operator!=(const Cylinder&) const; bool operator>=(const Cylinder&) const; bool operator>(const Cylinder&) const; bool operator<(const Cylinder&) const; bool operator<=(const Cylinder&) const; friend Cylinder operator++(Cylinder&, int); friend ostream &operator<<(ostream& out, const Cylinder&); private: /* data members */ double radius; double height; }; #endif /* CYLINDER_H_INCLUDED */ Answer: Answer to your question is it really necessary to add the parameter name (int <parameter_name>), instead of just (int) in a definition of an operator function to overload "++" ( post-increment) ? or would it be optional?
{ "domain": "codereview.stackexchange", "id": 42957, "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++, overloading", "url": null }
c++, overloading That is not necessary. If a function parameter is not used in the body of a function, you do not need to give that parameter a name. Cylinder arithmetic doesn't make sense What does it mean to add two cylinders together? Or to multiply them? You are implementing overloads for the arithmetic and relational operators, and just blindly apply those operators to the radius and height, but that doesn't make any sense. Consider your cylinders are all made out of the same homogeneous material. If you add two identical cylinders together, what do you expect the result to be? Another cylinder that has double the volume? But if you add the radii and height individually, then the volume will actually increase eightfold. The same goes for mass. What if you add a cylinder with a very small radius but large height to one with a large radius but small height? If you subtract cylinders, what does it mean if the result has a negative value for both radius and height? Your relational operators also don't make sense, at least they don't form a total order. Consider comparing two cylinders A with radius 1 and height 2, and cylinder B with radius 2 and height 1. Then operator<, operator> and operator== will all return false. Also consider that you can have two cylinders with equal radius but different height. Then both operator== and operator!= return false. Actually, the operators don't even do that. Why are most of them creating a new Cylinder object and using that instead of this? Use '\n' instead of std::endl Prefer using '\n' instead of std::endl; the latter is equivalent to the former but also forces the output to be flushed, which is usually not necessary and can have a negative impact on performance. Unnecessary code Your code has some unnecessary parentheses and ternary operators. Consider: return ((new_n.radius < n.radius && new_n.height < n.height) ? true : false);
{ "domain": "codereview.stackexchange", "id": 42957, "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++, overloading", "url": null }
c++, overloading First, the outer parentheses are not necessary at all. Second, the ternary operator doesn't do anything. Everything before the ? is already a boolean value, so you can just write: return new_n.radius < n.radius && new_n.height < n.height; operator= should return a non-const reference operator= only makes sense on a non-const object, and the return value should also be a non-const reference. Use () for functions that take no parameters (void) is only necessary in C, in C++ you can just write: Cylinder(); Prefer initializer lists to initialize member variables While your constructors are valid, prefer using initializer lists to initialize member variables, like so: Cylinder::Cylinder(): radius(1), height(1) {} Cylinder::Cylinder(double radius_, double height_): radius(radius_), height(height_) {} Or combine them using default parameter values: Cylinder::Cylinder(double radius_ = 1, double height_ = 1): radius(radius_), height(height_) {}
{ "domain": "codereview.stackexchange", "id": 42957, "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++, overloading", "url": null }
python, python-3.x, object-oriented, web-scraping Title: Scrape a URL for articles to save Question: Below is an exercise project I was doing on a certain educational site. It is supposed to parse a given (static address in this example) URL for html data, search articles of a given type there and then save their text data on your drive. It is working fine but since there're no code reviews on this site, I'm sort of worried that I'm doing something wrong without understanding it. Specifically, I'm struggling to understand is which cases or to what aim I should use classes in Python. What I want to ask is for someone to tell if the below code is a valid application of OOP (and if OOP approach should even be used for such task). And if not, why and what I should be looking for to improve. import string import os import requests from dataclasses import dataclass, field from typing import ClassVar from bs4 import BeautifulSoup as beauty @dataclass class WebScraper: CACHE: ClassVar[dict] = dict() BASE_URL: ClassVar[str] = 'https://www.nature.com' PAGE_URL: ClassVar[str] = 'https://www.nature.com/nature/articles?sort=PubDate&year=2020' page_number: int art_type: str raw_text: str = field(init=False) art_urls: dict = field(init=False) page_content: dict = field(init=False) @classmethod def save_content(cls): for page, articles in cls.CACHE.items(): os.mkdir(page) for name, text in articles.items(): path = os.path.join(page, f'{name}.txt') with open(path, 'wt', encoding='utf-8') as file: file.write(text) def __post_init__(self): self.page_content = dict() url = self.PAGE_URL + f"&page{self.page_number}" self.raw_text = requests.get(url, headers={'Accept-Language': 'en-US,en;q=0.5'}).text self.art_urls = dict() self.parse_page()
{ "domain": "codereview.stackexchange", "id": 42958, "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, object-oriented, web-scraping", "url": null }
python, python-3.x, object-oriented, web-scraping def parse_page(self): soup = beauty(self.raw_text, 'html.parser') articles = soup.find_all('article') for art in articles: span = art.find('span', {'class': 'c-meta__type'}) if span.text == self.art_type: link = art.find('a') url = self.BASE_URL + link['href'] self.art_urls[link.text] = url def parse_articles(self): for name, url in self.art_urls.items(): r = requests.get(url, headers={'Accept-Language': 'en-US,en;q=0.5'}) soup = beauty(r.text, 'html.parser') article = soup.find('div', {'class': 'c-article-body'}) file_name = ''.join(ch if ch not in string.punctuation else '' for ch in name) file_name = file_name.replace(' ', '_') self.page_content[file_name] = article.get_text() def cache_content(self): self.CACHE[f'Page_{self.page_number}'] = self.page_content n_of_pages = int(input()) art_type = input() for page_num in range(1, n_of_pages + 1): scraper = WebScraper(page_num, art_type) scraper.parse_articles() scraper.cache_content() WebScraper.save_content() ```
{ "domain": "codereview.stackexchange", "id": 42958, "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, object-oriented, web-scraping", "url": null }
python, python-3.x, object-oriented, web-scraping Answer: beauty is not a conventional alias for BeautifulSoup; you're better off using the original. Your cache mechanism is a little strange, and should probably be deleted. It's not as if you've shown an access pattern that warrants this. The OOP design hasn't particularly captured the right things. The "object" you care about most is an article and there is no class for that in your implementation. Conversely, WebScraper isn't very useful as a class since it doesn't need to carry around any state, and is probably better as a small collection of free functions. These functions can handle depagination as expressed through a generator. Note that save_content doesn't save the content: it only saves the journal abstracts. t is the default mode for open and can be omitted. You jump through a few hoops to derive a filename from the title that will be (probably) compatible with your filesystem. This ends up with the worst of all worlds: a title that doesn't look as good as the original, which still has no guarantee of filesystem compatibility. Instead, there's a perfectly good article ID as the last part of the URL that you can use. If you still did want to title-mangle for a filename, consider instead a regex sub. I don't find it useful to carry the concept of a page, which only has meaning in the web search interface, to your filesystem. You could just save these files flat. The broader question is: why? When you pull an abstract and discard its DOM structure, the resulting text has lost all of its formatting, including some fairly important superscript citations, etc. Why not just save the HTML? You could save an index csv with the additional fields that I've demonstrated you can parse, and then one .html per article. When you're able, use a soup strainer to constrain the parse breadth. The Accept-Language that you pass is less important (and is ignored by the server); the more important Accept should be passed which says that you only understand text/html.
{ "domain": "codereview.stackexchange", "id": 42958, "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, object-oriented, web-scraping", "url": null }
python, python-3.x, object-oriented, web-scraping Don't input() without passing a prompt to give the user a clue as to why your program mysteriously hung. Suggested This does not include file saving. from datetime import date from textwrap import wrap from typing import NamedTuple, Iterator, Optional from urllib.parse import urljoin
{ "domain": "codereview.stackexchange", "id": 42958, "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, object-oriented, web-scraping", "url": null }
python, python-3.x, object-oriented, web-scraping from bs4 import BeautifulSoup from bs4.element import SoupStrainer, Tag from requests import Session BASE_URL = 'https://www.nature.com' SEARCH_STRAINER = SoupStrainer('ul', class_='app-article-list-row') ARTICLE_STRAINER = SoupStrainer('div', id='Abs1-content') class Article(NamedTuple): title: str authors: tuple[str, ...] article_type: str date: date url: str description: Optional[str] @classmethod def from_tag(cls, tag: Tag) -> 'Article': anchor = tag.find('a', class_='c-card__link') authors = tuple( span.text for span in tag.find('span', itemprop='name') ) article_type = tag.find('span', class_='c-meta__type').text article_date = date.fromisoformat( tag.find('time')['datetime'] ) description = tag.find('div', itemprop='description') return cls( title=anchor.text, url=urljoin(BASE_URL, anchor['href']), authors=authors, article_type=article_type, date=article_date, description=description and description.text.strip(), ) @property def id(self) -> str: return self.url.rsplit('/', 1)[1] def get_abstract(session: Session, url: str) -> str: with session.get( url=url, headers={'Accept': 'text/html'}, ) as resp: resp.raise_for_status() html = resp.text doc = BeautifulSoup(markup=html, features='html.parser', parse_only=ARTICLE_STRAINER) return doc.text def articles_from_html(html: str) -> Iterator['Article']: doc = BeautifulSoup(markup=html, features='html.parser', parse_only=SEARCH_STRAINER) for tag in doc.find_all('article'): yield Article.from_tag(tag)
{ "domain": "codereview.stackexchange", "id": 42958, "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, object-oriented, web-scraping", "url": null }
python, python-3.x, object-oriented, web-scraping def scrape_one( session: Session, article_type: str, year: int, page: int, sort: str = 'PubDate', ) -> Iterator[Article]: params = { 'searchType': 'journalSearch', 'sort': sort, 'type': article_type, 'year': year, 'page': page, } with session.get( url=urljoin(BASE_URL, '/nature/articles'), headers={'Accept': 'text/html'}, params=params, ) as resp: resp.raise_for_status() html = resp.text yield from articles_from_html(html) def scrape( session: Session, article_type: str, year: int, pages: int, sort: str = 'PubDate', ) -> Iterator[Article]: for page in range(1, pages+1): yield from scrape_one(session, article_type, year, page, sort) def test() -> None: with Session() as session: for article in scrape( session=session, article_type='article', year=2020, pages=2, ): print(article) print('\n'.join(wrap( get_abstract(session, article.url) ))) print() if __name__ == '__main__': test()
{ "domain": "codereview.stackexchange", "id": 42958, "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, object-oriented, web-scraping", "url": null }
python, python-3.x, object-oriented, web-scraping if __name__ == '__main__': test() Output Article(title='Nociceptive nerves regulate haematopoietic stem cell mobilization', authors=('Xin Gao',), article_type='Article', date=datetime.date(2020, 12, 23), url='https://www.nature.com/articles/s41586-020-03057-y', description='Stimulation of pain-sensing neurons, which can be achieved in mice by the ingestion of capsaicin, promotes the migration of haematopoietic stem cells from the bone marrow into the blood.') Haematopoietic stem cells (HSCs) reside in specialized microenvironments in the bone marrow—often referred to as ‘niches’—that represent complex regulatory milieux influenced by multiple cellular constituents, including nerves1,2. Although sympathetic nerves are known to regulate the HSC niche3,4,5,6, the contribution of nociceptive neurons in the bone marrow remains unclear. Here we show that nociceptive nerves are required for enforced HSC mobilization and that they collaborate with sympathetic nerves to maintain HSCs in the bone marrow. Nociceptor neurons drive granulocyte colony-stimulating factor (G-CSF)-induced HSC mobilization via the secretion of calcitonin gene-related peptide (CGRP). Unlike sympathetic nerves, which regulate HSCs indirectly via the niche3,4,6, CGRP acts directly on HSCs via receptor activity modifying protein 1 (RAMP1) and the calcitonin receptor-like receptor (CALCRL) to promote egress by activating the Gαs/adenylyl cyclase/cAMP pathway. The ingestion of food containing capsaicin—a natural component of chili peppers that can trigger the activation of nociceptive neurons—significantly enhanced HSC mobilization in mice. Targeting the nociceptive nervous system could therefore represent a strategy to improve the yield of HSCs for stem cell-based therapeutic agents. ...
{ "domain": "codereview.stackexchange", "id": 42958, "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, object-oriented, web-scraping", "url": null }
typescript, angular-2+, firebase Title: Managing Angular subscriptions Question: There are different methods to get data from server in Angular application: Get Observable from the service and subscribe to it at component Create Subject at the service and subscribe to the Subject at component Both of this methods work for me but I can't understand which should I use. First method. Get Observable from the service and subscribe to it at component: article.service.ts import { Injectable } from '@angular/core'; import { Article } from '../models/article'; import { AngularFirestore } from '@angular/fire/firestore'; import { map, take } from 'rxjs/operators'; import { Observable, Subject } from 'rxjs'; @Injectable({ providedIn: "root" }) export class ArticleService { public articlesChanged: Subject<Article[]> = new Subject<Article[]>(); articles: Article[]; constructor(private db: AngularFirestore) {} get() { return this.db.collection('articles').valueChanges({ idField: 'id' }); } } home.component.ts import { Component, OnInit } from '@angular/core'; import { ArticleService } from 'src/app/services/article.service'; import { Observable, Subscription } from 'rxjs'; import { Article } from 'src/app/models/article'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { articles: Article[]; constructor(private articlesService: ArticleService) { } ngOnInit() { this.articlesService.get().subscribe(articles => this.articles = articles as Article[]); } } Second method. Create Subject at the service and subscribe to the Subject at component: article.service.ts import { Injectable } from '@angular/core'; import { Article } from '../models/article'; import { AngularFirestore } from '@angular/fire/firestore'; import { map, take } from 'rxjs/operators'; import { Observable, Subject } from 'rxjs';
{ "domain": "codereview.stackexchange", "id": 42959, "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": "typescript, angular-2+, firebase", "url": null }
typescript, angular-2+, firebase @Injectable({ providedIn: "root" }) export class ArticleService { public articlesChanged: Subject<Article[]> = new Subject<Article[]>(); articles: Article[]; constructor(private db: AngularFirestore) {} get(): void { this.db .collection('articles') .valueChanges({ idField: 'id' }).subscribe(articles => { this.articles = articles as Article[]; this.articlesChanged.next(this.articles); }); } } home.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { ArticleService } from 'src/app/services/article.service'; import { Observable, Subscription } from 'rxjs'; import { Article } from 'src/app/models/article'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit, OnDestroy { articlesSubscription: Subscription; articles: Article[]; constructor(private articlesService: ArticleService) { } ngOnInit() { this.articlesSubscription = this.articlesService.articlesChanged.subscribe(articles => this.articles = articles); this.articlesService.get(); } ngOnDestroy(): void { this.articlesSubscription.unsubscribe(); } } Is there a best practice which I should use? Answer: I suggest to use the first approach. You than can provide some pipes that could transform the returned values as you need. And if the articles are showed only in your component is better to store them inside then as a service property, because they will be stored even after the component will be destroyed. In an multipage application it can cause many problem to store old data. Your second approach you also leave an observable (the one listening for changes) running after the component destroy.
{ "domain": "codereview.stackexchange", "id": 42959, "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": "typescript, angular-2+, firebase", "url": null }
python, number-guessing-game Title: Number Guessing Game Version 1 Question: I made a really basic number guessing game based off a list of recommended projects, and i want to see if it follows the normal coding conventions before I aim to improve it(with lives, or hints, ect). This is also my first attempt at loops. I am wondering if this follows the normal coding conventions, if i was unnecessarily repetitive with the code, and if there is any thing I can do to improve the code. #Guessing Game! #The code has the user guess a number from 1-100 #if they get it right, they are congratulated and asked to play again #if they get it wrong, they must keep guessing #Game code import random as r play = True #rnum = The random number #gnum = The guessed number while play: x = r.randrange(1,100,1) rnum = str(x) #this exists for testing print(rnum) gnum = input("Guess the number!") if gnum == rnum: print("Good Job! Play Again?") play_again = input("y/n") if play_again == "y": continue else: break if gnum != rnum: gnum = input("Nope, guess again!") if gnum == rnum: print("Good Job! Play Again?") play_again = input("y/n") if play_again == "y": continue else: break print("Thank you for playing!")
{ "domain": "codereview.stackexchange", "id": 42960, "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, number-guessing-game", "url": null }
python, number-guessing-game print("Thank you for playing!") Answer: Broadly: whereas the game does work, it isn't very fun, since no feedback is given to the user (e.g. that the number guessed is too high or too low, or that you're close or far). The only way to win is to try every single number from 1 to 100. Your play loop variable can be deleted since you can break out of the loop directly when needed. r is not a very good alias for the random module. Either keep it as random, or use import from syntax. randrange is not the right function to call; since you care about an inclusive range call randint instead. As it stands, your code doesn't do what you say it does since the maximum will only be 99, not 100. You have repeated code that should be centralised - your "play again" section. Rather than casting your rnum as a string, you should do the opposite and validate and cast the user input to an integer. Suggested """ Guessing Game! The code has the user guess a number from 1-100 if they get it right, they are congratulated and asked to play again if they get it wrong, they must keep guessing """ from random import randint while True: # rnum = The random number rnum = randint(1, 100) while True: # gnum = The guessed number gnum = input("Guess the number! ") if not gnum.isnumeric(): print("Invalid integer") elif int(gnum) == rnum: break else: print("Nope, guess again!") print("Good Job! Play Again?") play_again = input("y/n") if play_again != "y": break print("Thank you for playing!")
{ "domain": "codereview.stackexchange", "id": 42960, "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, number-guessing-game", "url": null }
php, mysql Title: PHP search multiple filter inputs Question: Okay so I built this search page that searches for posts but my current code seems so bloated and inefficient. My script(search page) if(isset($_GET['title']))$title = $_GET['title'];else{ $title = ''; } if(isset($_GET['ad_brand']))$brand = $_GET['ad_brand'];else{ $brand = ''; } if(isset($_GET['min_range']))$min_range = $_GET['min_range'];else{ $min_range = ''; } if(isset($_GET['max_range']))$max_range = $_GET['max_range'];else{ $max_range = ''; } if(isset($_GET['sub_cat']))$sub_cat = $_GET['sub_cat'];else{ $sub_cat = ''; } if(isset($_GET['for_r_s']))$for_r_s = $_GET['for_r_s']; else{ $for_r_s = ''; } if(isset($_GET['main_cat']))$main_cat = $_GET['main_cat']; else{ $main_cat = ''; } if(isset($_POST['filter_button'])){ if(isset($_POST['ad_brand'])) $brand = $_POST['ad_brand']; else{$brand = '';} if(isset($_POST['main_cat'])) $main_cat = $_POST['main_cat']; else{ $main_cat = ''; } if(isset($_POST['sub_cat'])) $sub_cat = $_POST['sub_cat']; else{ $sub_cat = ''; } if($_POST['min_range'] != '') $min_range = $_POST['min_range']; else{ $min_range = ''; } if(isset($_POST['max_range'])) $max_range = $_POST['max_range']; else{ $max_range = ''; } if(isset($_POST['for_r_s'])) $for_r_s = $_POST['for_r_s']; else{ $for_r_s = ''; } header('location:search?title='. $title .'&main_cat='.$main_cat.'&sub_cat='. $sub_cat .'&ad_brand='. $brand .'&min_range='.$min_range.'&max_range='.$max_range.'&for_r_s='.$for_r_s.''); }
{ "domain": "codereview.stackexchange", "id": 42961, "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": "php, mysql", "url": null }
php, mysql if(isset($_GET['sub_cat'])){ if($_GET['sub_cat'] != ''){ if(isset($_GET['min_range'])){ if(isset($_GET['max_range']) && $_GET['max_range'] != ''){ if(isset($_GET['for_r_s'])){ if($_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` >= ? AND `ad_price` <= ? AND `for_r_s` = ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("sssiii", $title, $sub_cat ,$brand, $min_range, $max_range, $for_r_s); }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` >= ? AND `ad_price` <= ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("sssii", $title, $sub_cat ,$brand, $min_range, $max_range); } }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` >= ? AND `ad_price` <= ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("sssii", $title, $sub_cat ,$brand, $min_range, $max_range); } }else{ if(isset($_GET['for_r_s'])){ if($_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){
{ "domain": "codereview.stackexchange", "id": 42961, "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": "php, mysql", "url": null }
php, mysql if($_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` >= ? AND `for_r_s` = ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("sssii", $title, $sub_cat ,$brand, $min_range, $for_r_s); }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` >= ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("sssi", $title, $sub_cat ,$brand, $min_range); } }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` >= ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("sssi", $title, $sub_cat ,$brand, $min_range); } } }else{ if(isset($_GET['max_range']) && $_GET['max_range'] != ''){ if(isset($_GET['for_r_s'])){ if($_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` <= ? AND `for_r_s` = ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("sssii", $title, $sub_cat ,$brand, $max_range,$for_r_s);
{ "domain": "codereview.stackexchange", "id": 42961, "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": "php, mysql", "url": null }
php, mysql }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` <= ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("sssi", $title, $sub_cat ,$brand, $max_range); } }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` <= ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("sssi", $title, $sub_cat ,$brand, $max_range); } }else{ if(isset($_GET['for_r_s'])){ if($_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `for_r_s` = ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("sssi", $title, $sub_cat ,$brand, $for_r_s); }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%')"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("sss", $title, $sub_cat ,$brand); } }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%')"; $get_posts = $conn_posts->prepare($query);
{ "domain": "codereview.stackexchange", "id": 42961, "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": "php, mysql", "url": null }
php, mysql $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("sss", $title, $sub_cat ,$brand); } } } }else{ if(isset($_GET['min_range'])){ if(isset($_GET['max_range']) && $_GET['max_range'] != ''){ if(isset($_GET['for_r_s'])){ if($_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` >= ? AND `ad_price` <= ? AND `for_r_s` = ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("ssiii", $title, $brand, $min_range, $max_range, $for_r_s); }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` >= ? AND `ad_price` <= ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("ssii", $title, $brand, $min_range, $max_range); } }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` >= ? AND `ad_price` <= ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("ssii", $title, $brand, $min_range, $max_range); } }else{ if(isset($_GET['for_r_s'])){ if( $_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` >= ? AND `for_r_s` = ?";
{ "domain": "codereview.stackexchange", "id": 42961, "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": "php, mysql", "url": null }
php, mysql LIKE CONCAT('%',?,'%') AND `ad_price` >= ? AND `for_r_s` = ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("sssi", $title, $brand, $min_range, $for_r_s); }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` >= ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("ssi", $title, $brand, $min_range); } }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` >= ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("ssi", $title, $brand, $min_range); } } }else{ if(isset($_GET['max_range']) && $_GET['max_range'] != ''){ if(isset($_GET['for_r_s'])){ if($_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` <= ? AND `for_r_S` = ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("ssii", $title, $brand, $max_range, $for_r_s); }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` <= ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("ssi", $title, $brand, $max_range); } }else{
{ "domain": "codereview.stackexchange", "id": 42961, "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": "php, mysql", "url": null }
php, mysql } }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` <= ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("ssi", $title, $brand, $max_range); } }else{ if(isset($_GET['for_r_s'])){ if($_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `for_r_s` = ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("ssi", $title, $brand, $for_r_s); }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%')"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("ss", $title, $brand); } }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%')"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("ss", $title, $brand); } } } } }else{ $sub_cat = ''; if(isset($_GET['for_r_s'])){ if($_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `for_r_s` = ?"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("ssi", $title, $brand, $for_r_s); }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%')";
{ "domain": "codereview.stackexchange", "id": 42961, "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": "php, mysql", "url": null }
php, mysql $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("ss", $title, $brand); } }else{ $query = "SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%')"; $get_posts = $conn_posts->prepare($query); $get_posts->bind_param("ss", $title, $brand); } }
{ "domain": "codereview.stackexchange", "id": 42961, "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": "php, mysql", "url": null }
php, mysql My Html code <form action="" method="post"> <select name="main_cat" id="main_cat"> <option value="null" disabled selected>Select Category</option> <?php $get_category = $conn_posts->prepare("SELECT * FROM `cats` WHERE `main_cat` = 0;"); $get_category->execute(); $get_category_results = $get_category->get_result(); // get result while($row = $get_category_results->fetch_assoc()){ echo '<option value="'.$row['ID'].'">'.$row['cat_name'].'</option>'; } ?> </select> </br> <select name="sub_cat" id="sub-category-dropdown"> <option value="">Select SubCategory</option> </select> </br> <input type="text" name="ad_brand" Placeholder="Brand(Cat,Jcb,Doosan)"> </br> <label for="for_r_S">Price</label> <div class="range_sliders"> <input type="text" name="min_range" Placeholder="Min"> <span> - </span> <input type="text" name="max_range" Placeholder="Max"> </div> </br> <label for="for_r_S">For Rent</label> <input type="radio" name="for_r_s" id="for_r_s" value="1"> <label for="for_r_S">For Sale</label> <input type="radio" name="for_r_s" id="for_r_s" value="2"> </br> <div id="content"></div> <button type="submit" name="filter_button" class="filter_button">Search</button> </form> My Database table layout
{ "domain": "codereview.stackexchange", "id": 42961, "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": "php, mysql", "url": null }
php, mysql My Database table layout ID ad_title ad_sub_cat ad_price used_new for_r_s ad_brand ad_des ad_location 1 title 12 100 1 1 loerm ipsum new york for_r_s:: 1 = for rent, 2 = for sale used_new:: 1 = used, 2 = new Also the sub cat is gotten from ajax but i don't want to include that code here so just fill it in with any category like this <option value="12">Select car</option> The script is working how I want it to but I just want to clean this code(i don't know of any bugs and it should work just fine) and I need some help doing that my friend told me to ask here so I am still ned please tell me if this post is not good and i will put more info. Answer: There is one thing that is not right in your application: tabs and indentation. Example: if(isset($_POST['filter_button'])){ if(isset($_POST['ad_brand'])) $brand = $_POST['ad_brand']; else{$brand = '';} So the code is hard to read and decipher because it is too compact, indentation and spacing are not consistent and the control flows are not outlined clearly enough. Something like this would be slightly more readable: if(isset($_POST['filter_button'])) { if(isset($_POST['ad_brand'])) { $brand = $_POST['ad_brand']; else { $brand = ''; } Right ? But since PHP has the ternary operator the code could be written more concisely in a one-liner fashion like: $brand = (isset($_POST['ad_brand'])) ? $_POST['ad_brand'] : '';
{ "domain": "codereview.stackexchange", "id": 42961, "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": "php, mysql", "url": null }
php, mysql The other problem is that you have too many nested ifs. From line 38, you have 6 levels of nesting. This is too much for a program that is not even of high complexity. It is very hard to figure out if the logic is even correct, because it is difficult to tell where the ifs exactly begin end end. The likelihood of producing bugs becomes high as a result. To simplify this my advice is to check the input values early, provide default values where desired, (or abort with an error if the form is being tampered by the user). In fact you are already doing it. If you consider for example lines 38-39: if(isset($_GET['sub_cat'])){ if($_GET['sub_cat'] != ''){ the form field sub_cat has already been assigned to variable $sub_cat previously. So from now on, you should be using that variable. It has been validated and has a default value too, so there is no need to make further verification. So you can already remove two levels of nesting. The third problem is repetition. It is understandable that you want to have different SQL statements depending on some condition, but there is no need to repeat prepare, bind_param etc. Once would be enough, at the end of the if block. But you should go further and move all the SQL statements to dedicated functions. What you need is a function with a few parameters, some of them optional, with default values for some parameters, and inside that function you can build your SQL statement. Eg: function get_posts($title, $subcat, $min_price, $max_price) { ... } The function shall return a resultset depending on the supplied parameters. All you have to do is call the function with appropriate values. Inside that function you can have ifs and build a dynamic statement according to the function arguments received. Basically all you have is a series of criteria. If for a example a minimum price is supplied to your function you can concatenate this to your SQL statement: $query = "SELECT * FROM `posts`";
{ "domain": "codereview.stackexchange", "id": 42961, "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": "php, mysql", "url": null }
php, mysql if ($min_price) { $query .= " AND price >= $min_price"; } and so on, as long as the resulting SQL remains correct. So what you will be doing is selective concatenation. As far as I can tell the criteria can be evaluated one by one in a sequential manner. All you will need is some ifs, AND, OR. The idea is to concentrate all the logic into that function. Thus you could ditch all those if blocks. Just doing that will reduce the code size significantly and improve readability. The rule of thumb that everything that is repetitive is a candidate for a function. To sum up, all you need is: verify that all expected parameters are received from a POST request validate them where appropriate, you can supply default values (you are already doing that) populate your variables then you can pass those variables to a function that will build your SQL dynamically Result: all the nested ifs are gone. Something that could make the code more explanatory is to use constants. eg: define('FOR_SALE', '1'); define('FOR_RENT', '2'); Then you can use variables like FOR_SALE or FOR_RENT in your code to make the SQL statements more descriptive. What is disturbing is the total lack of comments. It would be good to add some notes in plain English here and there, especially when you are checking for some condition. The idea is to better separate blocks, and that if you are looking for something, you don't have to decipher the whole code. The database structure is not known but judging by the present of LIKE and CONCAT I suspect that you are not taking advantage of indexes, provided they are present. You may run into performance issues as your database grows bigger. The HTML page on the other hand is easy. You may want to use a templating engine like twig perhaps. PS: maybe you need a better editor to enforce good formatting.
{ "domain": "codereview.stackexchange", "id": 42961, "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": "php, mysql", "url": null }
c, winapi Title: A small C WinAPI program moving the cursor in a circle Question: So the program below will move the mouse cursor in a circle all 360 degrees for 2,5 seconds (after 2,5 seconds, the program exits and the user can use his/her cursor normally). #include <Windows.h> #include <math.h> const double RADIANS_PER_DEGREE = acos(-1.0) / 180.0; // acos(-1.0) = Pi const int SLEEP_DURATION = 2500 / 360; int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { const int screenWidth = GetSystemMetrics(SM_CXSCREEN); const int screenHeight = GetSystemMetrics(SM_CYSCREEN); const int screenCenterX = screenWidth / 2; const int screenCenterY = screenHeight / 2; const int radius = 3 * min(screenWidth / 2, screenHeight / 2) / 4; int currentDegree = 90; for (int degree = 0; degree < 360; degree++, currentDegree++) { const int x = screenCenterX + (int)(radius * cos(currentDegree * RADIANS_PER_DEGREE)); const int y = screenCenterY - (int)(radius * sin(currentDegree * RADIANS_PER_DEGREE)); SetCursorPos(x, y); Sleep(SLEEP_DURATION); } return 0; } Critique request I would like to hear anything that comes to mind.
{ "domain": "codereview.stackexchange", "id": 42962, "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, winapi", "url": null }
c, winapi return 0; } Critique request I would like to hear anything that comes to mind. Answer: Integer math for an integer problem Consider a variation on Bresenham's circle algorithm for an integer only solution: faster and precise. Note: Graphics processors use integer math for drawing circles on a screen, not floating point. 1 degree steps? On high precision monitors, (think 2k * 2k or more) the result may look more circular (not a polygon) with finer steps. Above integer solution provides the best digitized circle. Not standard C code Good idea to use the systems best machine π, yet double global_variable = some_function(-1.0) is not valid. I suspect OP is not using a standard C compiler. Alternative. Since π does not change, let the system derive the best machine π by providing code that the compiler will use even if double is many more than 64-bit. // const double RADIANS_PER_DEGREE = acos(-1.0) / 180.0; // acos(-1.0) = Pi const double RADIANS_PER_DEGREE = 3.1415926535897932384626433832795028841971 / 180.0; Or define it #ifdef M_PI // some implementation will define this, use if available. #define MY_PI M_PI #else #define MY_PI 3.1415926535897932384626433832795028841971 #endif const double RADIANS_PER_DEGREE = MY_PI / 180.0; Pedantically, in rare cases, performing math like MY_PI / 180.0 will not result in the best RADIANS_PER_DEGREE and code could directly use const double RADIANS_PER_DEGREE = 0.01745329251994329576923690768489; Manually formatting? Below hints that OP is not using an auto formatter. Code looks nice. Yet I would rather oblige a SW team to use auto formatting that spend time formatting. int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{ "domain": "codereview.stackexchange", "id": 42962, "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, winapi", "url": null }
c, winapi Save time and increase productivity: auto-format. Comment units Naked code like const int SLEEP_DURATION = 2500 / 360; lacks units. How long is 2500? 2500 seconds, 2500 milliseconds? Do not lay the seeds for another big bucks units failure. // const int SLEEP_DURATION = 2500 / 360; const int SLEEP_DURATION = 2500 /* ms */ / 360; Truncated quotient? Note that 2500 / 360.0 is 6.9444... and 2500 / 360 is 6. Code may want to do things more precisely. At a minimum, consider a rounded quotient. // const int SLEEP_DURATION = 2500 / 360; const int SLEEP_DURATION = (2500 + 360/2) / 360;
{ "domain": "codereview.stackexchange", "id": 42962, "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, winapi", "url": null }