text
stringlengths
1
2.12k
source
dict
java, algorithm, strings Title: Related to DSA: Find longest common prefix Question: The objective of below code is find longest common prefix from trie DataStructure which is written in Java. Code: public String longestCommonPrefix(String[] words) { var commonPrefix = getCommonPrefixOf(words, 0, ""); if (contains(commonPrefix)) return commonPrefix; return "";} private String getCommonPrefixOf(String[] words, int index, String prefix) { if (words == null || words.length == 0 || index == words.length) return prefix; if (words.length <= 1) return words[0]; var first = words[index]; var second = (index > 1) ? prefix : words[++index]; if (first == null || second == null) return ""; var length = Math.min(first.length(), second.length()); StringBuilder builder = new StringBuilder(); for (int i = 0; i < length; i++) if (first.charAt(i) == second.charAt(i)) builder.append(first.charAt(i)); return getCommonPrefixOf(words, ++index, builder.toString());} Answer: The code does not use a trie, so it would appear to fail the requirements out of the gate. I have several concerns with the layout of the code: Indentation is inconsistent. In particular, code inside a method should be indented. Curly braces, though technically optional, make code much easier to read. They can also prevent errors when editing existing code. When present, closing curly braces belong on a line by themselves. They should not be on the same line as the block they're closing. In my opinion, var is being overused. The design intent of var is to keep code from having to declare a type on both sides of an assignment. It was not intended as a blanket means of avoiding declaring type. Code is harder to read when the type is not obvious on at least one side of the assignment operator. Source
{ "domain": "codereview.stackexchange", "id": 42963, "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, algorithm, strings", "url": null }
java, algorithm, strings The use of meaningful variable names is very good and greatly enhances the readability of this code. Unit tests make it easier to see exactly how the code is behaving and to make sure failures aren't introduced as code gets modified. Especially for problems of this type, you might consider learning about Test-Driven Development (TDD). I do not see the value in the contains() call. If there is no common prefix, getCommonPrefixOf returns "", which is what longestCommonPrefix() is returning anyway. It would be preferable to validate words as close to when the user provides it as possible. This is slightly more performant, and the helper method doesn't have as much work to do. Validating words.length <= 1 is misleading, because it implies that the code hasn't checked its size is zero. It also won't behave properly if the size actually is zero. The check on second for index > 1 is somewhat inefficient and confusing to read. It would be preferable for longestCommonPrefix to just start the index at 1 and make the first prefix words[0]. Then, the code doesn't need the concept of first or second at all. It can just compare words[index] to prefix. It might be easier to read with a currentWord variable. I'm assuming the contract states the code should return "" if any word is null. That would typically be specified in Javadoc, which is not useful for toy problems except when people are asked to review the code and don't have the contract. :) The StringBuilder's name is uninspiring. Fortunately, the StringBuilder is superfluous. The code can instead use substring(). The code should break out of the for loop early once no match has been detected. Otherwise aaxbb and aaybb will report a common prefix of aabb. Refactoring it looks a bit ugly if we try to keep it inline, because we need to track the loop index outside the loop. A nice way to deal with that is to extract the loop into a helper method, which can then return the index from inside the loop.
{ "domain": "codereview.stackexchange", "id": 42963, "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, algorithm, strings", "url": null }
java, algorithm, strings Avoid situations where the difference between variable++ and ++variable will matter. Use variable + 1 if the value of the variable itself does not need to change. If you made all these changes, your code might look more like: public class Test {
{ "domain": "codereview.stackexchange", "id": 42963, "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, algorithm, strings", "url": null }
java, algorithm, strings public static void main(String[] argv) { Test test = new Test(); System.out.println("empty array? " + "".equals(test.longestCommonPrefix(new String[0]))); System.out.println("one word?? " + "a".equals(test.longestCommonPrefix(new String[]{"a"}))); System.out.println("no common prefix? " + "".equals(test.longestCommonPrefix(new String[]{"a", "b"}))); System.out.println("short common prefix? " + "a".equals(test.longestCommonPrefix(new String[]{"aa", "ab"}))); System.out.println("long common prefix? " + "abcde".equals(test.longestCommonPrefix(new String[]{"abcdef", "abcdeg", "abcdefg"}))); System.out.println("test interrupt? " + "aa".equals(test.longestCommonPrefix(new String[]{"aaxbb", "aaybb", "aazbb"}))); System.out.println("perfect match? " + "aaxbb".equals(test.longestCommonPrefix(new String[]{"aaxbb", "aaxbb", "aaxbb"}))); System.out.println("one null word? " + "".equals(test.longestCommonPrefix(new String[]{"aa", null}))); System.out.println("two words w/ null? " + "".equals(test.longestCommonPrefix(new String[]{"aa", null}))); System.out.println("three words w/ null? " + "".equals(test.longestCommonPrefix(new String[]{"aa", "ab", null}))); } public String longestCommonPrefix(String[] words) { if (words == null || words.length == 0) { return ""; } if (words.length == 1) { return words[0] == null ? "" : words[0]; } return getCommonPrefixOf(words, 1, words[0]); } private String getCommonPrefixOf(String[] words, int index, String prefix) { if (index == words.length) { return prefix; } String currentWord = words[index]; if (currentWord == null) { return ""; } int firstNonmatchingIndex = firstNonmatchingIndexOf(currentWord, prefix); return getCommonPrefixOf(words, index + 1, currentWord.substring(0, firstNonmatchingIndex)); }
{ "domain": "codereview.stackexchange", "id": 42963, "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, algorithm, strings", "url": null }
java, algorithm, strings /** * Returns the first index where the two inputs do not have a matching character. * Ex. * <pre> * firstNonmatchingIndexOf("", "b") -> 0 * firstNonmatchingIndexOf("a", "b") -> 0 * firstNonmatchingIndexOf("aab", "aac") -> 2 * </pre> * @throws NullPointerException if either parameter is null. */ private static int firstNonmatchingIndexOf(String s1, String s2) { int maxLength = Math.min(s1.length(), s2.length()); for (int i = 0; i < maxLength; i++) { if (s1.charAt(i) != s2.charAt(i)) { return i; } } return maxLength; } } I do not believe that a recursive solution is optimal here. I think that using a nested loop would be significantly easier to read: public class Test {
{ "domain": "codereview.stackexchange", "id": 42963, "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, algorithm, strings", "url": null }
java, algorithm, strings public static void main(String[] argv) { Test test = new Test(); System.out.println("empty array? " + "".equals(test.longestCommonPrefix(new String[0]))); System.out.println("one word?? " + "a".equals(test.longestCommonPrefix(new String[]{"a"}))); System.out.println("no common prefix? " + "".equals(test.longestCommonPrefix(new String[]{"a", "b"}))); System.out.println("short common prefix? " + "a".equals(test.longestCommonPrefix(new String[]{"aa", "ab"}))); System.out.println("long common prefix? " + "abcde".equals(test.longestCommonPrefix(new String[]{"abcdef", "abcdeg", "abcdefg"}))); System.out.println("test interrupt? " + "aa".equals(test.longestCommonPrefix(new String[]{"aaxbb", "aaybb", "aazbb"}))); System.out.println("perfect match? " + "aaxbb".equals(test.longestCommonPrefix(new String[]{"aaxbb", "aaxbb", "aaxbb"}))); System.out.println("one null word? " + "".equals(test.longestCommonPrefix(new String[]{"aa", null}))); System.out.println("two words w/ null? " + "".equals(test.longestCommonPrefix(new String[]{"aa", null}))); System.out.println("three words w/ null? " + "".equals(test.longestCommonPrefix(new String[]{"aa", "ab", null}))); } public String longestCommonPrefix(String[] words) { if (words == null || words.length == 0) { return ""; } if (words.length == 1) { return words[0] == null ? "" : words[0]; } String prefix = words[0]; for (int i = 1; i < words.length; i++) { if (words[i] == null) { return ""; } int firstNonmatchingIndex = firstNonmatchingIndexOf(prefix, words[i]); if (firstNonmatchingIndex < prefix.length()) { prefix = prefix.substring(0, firstNonmatchingIndex); } } return prefix; }
{ "domain": "codereview.stackexchange", "id": 42963, "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, algorithm, strings", "url": null }
java, algorithm, strings /** * Returns the first index where the two inputs do not have a matching character. * Ex. * <pre> * firstNonmatchingIndexOf("", "b") -> 0 * firstNonmatchingIndexOf("a", "b") -> 0 * firstNonmatchingIndexOf("aab", "aac") -> 2 * </pre> * @throws NullPointerException if either parameter is null. */ private static int firstNonmatchingIndexOf(String s1, String s2) { int maxLength = Math.min(s1.length(), s2.length()); for (int i = 0; i < maxLength; i++) { if (s1.charAt(i) != s2.charAt(i)) { return i; } } return maxLength; } }
{ "domain": "codereview.stackexchange", "id": 42963, "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, algorithm, strings", "url": null }
beginner, go, url Title: Download artifacts using HTTP Question: The public code is SaveAsFile(). It takes a URL, checksum and authentication info, and downloads the artifact and its hash using HTTP. It saves the content as a file and returns the file's path on success, otherwise an error. As I'm fairly new to Go I would like to get some feedback on the error handling and on any ways to write this code more elegantly? https://go.dev/play/p/8i_xZ-EVTvP import ( "io" "io/ioutil" "net/http" "os" "strings" "time" "github.com/pkg/errors" ) var errCode = errors.New("bad response status code") var errFileNotWritten = errors.New("file not written") var errDigest = errors.New("digest are not identical") const ( statusMsg = `code: %d, response body:\n%s` notWritten = `unable to write file %s from Response body` msgDigestFailure = `target: \"%s\", file: \"%s\")` msgFileNotClosed = `unable to close file %s` ) func respBody(url string, user string, pass string) (io.ReadCloser, error) { client := &http.Client{ Timeout: time.Second * 10, } req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } if user != "" && pass != "" { req.SetBasicAuth(user, pass) } resp, err := client.Do(req) if err != nil { return nil, err } if resp.StatusCode < 200 || resp.StatusCode >= 300 { return nil, errors.Wrapf(errCode, statusMsg, resp.StatusCode, resp.Body) } return resp.Body, nil } func classify(url string, user string, pass string) (string, error) { const suffix = ".sha512" rb, err := respBody(url+suffix, user, pass) if err != nil { return "", err } defer rb.Close() bodyBytes, err := ioutil.ReadAll(rb) if err != nil { return "", err } return string(bodyBytes), nil }
{ "domain": "codereview.stackexchange", "id": 42964, "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": "beginner, go, url", "url": null }
beginner, go, url return string(bodyBytes), nil } func downFile(url string, user string, pass string) (*os.File, error) { responseBody, err := respBody(url, user, pass) if err != nil { return nil, err } defer responseBody.Close() file, err := ioutil.TempFile("", "*") if err != nil { return nil, err } written, err := io.Copy(file, responseBody) if err != nil { return nil, errors.Wrapf(err, notWritten, file.Name()) } else if written <= 0 { return nil, errors.Wrapf(errFileNotWritten, notWritten, file.Name()) } if err := file.Close(); err != nil { return nil, errors.Wrapf(err, msgFileNotClosed, file.Name()) } return file, nil } func SaveAsFile(url string, digest string, user string, pass string) (string, error) { file, err := downFile(url, user, pass) if err != nil { return "", err } if digest != "" { targetDigest, err := classify(url, user, pass) if err != nil { return "", err } if strings.Compare(targetDigest, digest) != 0 { return "", errors.Wrapf(errDigest, msgDigestFailure, targetDigest, digest) } } return file.Name(), nil } Answer: First I want to say that your code is very well written and idiomatic for someone who is new to Go. Here are a few suggestions:
{ "domain": "codereview.stackexchange", "id": 42964, "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": "beginner, go, url", "url": null }
beginner, go, url Prefer standard library tools for error handling rather than using an external library. errors.Wrapf can be replaced by fmt.Errorf. The %q format verb will print a string in quotes. Prefer using %q instead of \"%s\". Call file.Close with defer, so that if writing to the file fails it will still get closed. The documentation for file.Close specifies that it will only return an error if the file is already closed, so you could consider just ignoring any error from file.Close. Also if writing to the temp file fails, downFile should probably delete the file to avoid leaving extra empty files. This is kind of subjective, but I think downFile should return the file name instead of an *os.File because the file is already closed, so any attempt to read or write it would fail. Strings can be compared directly with !=, no need to call strings.Compare. SaveAsFile has a lot of string arguments, and some of them are optional. If a caller calls SaveAsFile(url, digest, "", ""), it's not obvious that the empty strings are the username and password. What you can use for this last point is the option pattern, I would define SaveAsFile as follows: type opts struct { user string pass string digest string } type SaveAsFileOption func(*opts) func Auth(user, pass string) SaveAsFileOption { return func(o *opts) { o.user = user o.pass = pass } } func Digest(digest string) SaveAsFileOption { return func(o *opts) { o.digest = digest } } func SaveAsFile(url string, options SaveAsFileOption...) { var o opts for _, opt := range options { opt(&o) } // Then you can the options through o.user, o.pass, etc. } Callers can call SaveAsFile either with SaveAsFile(url), or with SaveAsFile(url, Digest(digest), Auth(user, pass)). This also gives you the flexibility to define more options in the future.
{ "domain": "codereview.stackexchange", "id": 42964, "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": "beginner, go, url", "url": null }
php, authentication Title: Authenticate and log in users Question: How can I improve my login script and how to check for any possible injection? PS. the script must run on multiple platforms, so I need empty arrays for cases such as the Android ones. user_table: CREATE TABLE `user_table` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `user_type` varchar(255) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=63 DEFAULT CHARSET=latin1 Field Type Null Key Default Extra user_id int(11) NO PRI NULL auto_increment user_type varchar(255) NO NULL student_table: CREATE TABLE `student_table` ( `user_id` int(11) NOT NULL, `user_type` varchar(255) NOT NULL, `user_email` varchar(255) NOT NULL, `user_pass ` varchar(255) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 Field Type Null Key Default Extra user_id int(11) NO PRI NULL user_type varchar(255) NO NULL user_email varchar(255) NO NULL user_pass varchar(255) NO NULL teacher_table: CREATE TABLE `teacher_table` ( `user_id` int(11) NOT NULL, `Class` varchar(255) NOT NULL, `DEPARTMENT` varchar(255) NOT NULL, `user_email` varchar(255) NOT NULL, `user_pass ` varchar(255) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 Field Type Null Key Default Extra user_id int(11) NO PRI NULL Class varchar(255) NO NULL DEPARTMENT varchar(255) NO NULL user_email varchar(255) NO NULL user_pass varchar(255) NO NULL management_table: CREATE TABLE `management_table` ( `user_id` int(11) NOT NULL, `Class` varchar(255) NOT NULL, `DEPARTMENT` varchar(255) NOT NULL, `HEAD` varchar(255) NOT NULL, `user_email` varchar(255) NOT NULL, `user_pass ` varchar(255) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 Field Type Null Key Default Extra user_id int(11) NO PRI NULL Class varchar(255) NO NULL DEPARTMENT varchar(255) NO NULL HEAD varchar(255) NO NULL user_email varchar(255) NO NULL user_pass varchar(255) NO NULL
{ "domain": "codereview.stackexchange", "id": 42965, "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, authentication", "url": null }
php, authentication NULL HEAD varchar(255) NO NULL user_email varchar(255) NO NULL user_pass varchar(255) NO NULL user_status table: CREATE TABLE `user_status` ( `user_id` int(11) NOT NULL, `Login_id` int(11) NOT NULL, `user_token` varchar(255) NOT NULL, `user_status` varchar(255) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 Field Type Null Key Default Extra user_id int(11) NO NULL Login_id int(11) NO PRI NULL auto_increment user_token varchar(255) NO NULL user_status varchar(255) NO NULL login script: <?php if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { // echo $emailErr = "Invalid email format"; exit; }else{ $db_name ="mysql:host=localhost;dbname=DATABASE;charset=utf8"; $db_username="root"; $db_password=""; try{ $PDO = new PDO($db_name, $db_username, $db_password); //echo "connection success"; }catch (PDOException $error){ //echo "connection error"; exit; } $email = $_POST['email']; $pass = $_POST['pass']; $stmt = $PDO->prepare(" SELECT student_table.user_id ,student_table.user_pass FROM student_table WHERE student_table.user_email = :EMAIL UNION SELECT teacher_table.user_id ,teacher_table.user_pass FROM teacher_table WHERE teacher_table.user_email = :EMAIL UNION SELECT management_table.user_id ,management_table.user_pass FROM management_table WHERE management_table.user_email = :EMAIL " ); $stmt->bindParam(':EMAIL', $email); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); if (!empty($row)) { if (password_verify($pass, $row['user_pass'])) { function guidv4($data = null) { $data = $data ?? random_bytes(16); assert(strlen($data) == 16); $data[6] = chr(ord($data[6]) & 0x0f | 0x40); $data[8] = chr(ord($data[8]) & 0x3f | 0x80); return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); }
{ "domain": "codereview.stackexchange", "id": 42965, "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, authentication", "url": null }
php, authentication $user_id = $row['user_id']; $user_online = 'ONLINE'; $user_token = guidv4(); $sql_insert = " INSERT INTO user_status (user_id, user_token,user_status) VALUES (:ID,:TOKEN,:ONLINE ); "; $stmt = $PDO->prepare($sql_insert); $stmt->bindParam(':ID', $user_id); $stmt->bindParam(':ONLINE', $user_online); $stmt->bindParam(':TOKEN', $user_token); $stmt->execute(); $sql_select =" SELECT user_table.user_type FROM user_table WHERE user_table.user_id = :USER_ID"; $stmt = $PDO->prepare($sql_select); $stmt->bindParam(':USER_ID', $user_id); $stmt->execute(); $row2 = $stmt->fetch(PDO::FETCH_ASSOC); foreach ($row2 as $key ) { $user_id = $row['user_id']; if ($key == 'STUDENT') { $stmt2 = $PDO->prepare(" SELECT student_table.user_type, user_status.login_id, user_status.user_token FROM student_table LEFT JOIN user_status ON user_status.user_id = student_table.user_id WHERE student_table.user_id = :USERID ");
{ "domain": "codereview.stackexchange", "id": 42965, "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, authentication", "url": null }
php, authentication $stmt2->bindParam(':USERID', $user_id); if ($stmt2->execute()) { $row3 = $stmt2->fetch(PDO::FETCH_ASSOC); $returnApp = array( 'LOGIN' => 'Log_In_Success', 'user' =>$row2['user_type'], 'type' => $row3['user_type'], 'id' => $row3['login_id'], 'token' => $row3['user_token']); echo json_encode($returnApp); } }if ($key == 'TEACHER') { $stmt3 = $PDO->prepare(" SELECT teacher_table.Class, teacher_table.DEPARTMENT, user_status.login_id, user_status.user_token FROM teacher_table LEFT JOIN user_status ON user_status.user_id = teacher_table.user_id WHERE teacher_table.user_id = :USERID "); $stmt3->bindParam(':USERID', $user_id);
{ "domain": "codereview.stackexchange", "id": 42965, "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, authentication", "url": null }
php, authentication $stmt3->bindParam(':USERID', $user_id); if ($stmt3->execute()) { $row4 = $stmt3->fetch(PDO::FETCH_ASSOC); $returnApp = array( 'LOGIN' => 'Log_In_Success', 'user' =>$row2['user_type'], 'CL' =>$row4['Class'], 'DEP' => $row4['DEPARTMENT'], 'id' => $row4['login_id'], 'token' => $row4['user_token']); echo json_encode($returnApp); } }if ($key == 'MANAGEMENT'){ $stmt4 = $PDO->prepare(" SELECT management_table.CLASS, management_table.DEPARTMENT, management_table.HEAD, user_status.login_id, user_status.user_token FROM management_table LEFT JOIN user_status ON user_status .user_id = management_table.user_id WHERE management_table.user_id = :USERID "); $stmt4->bindParam(':USERID', $user_id);
{ "domain": "codereview.stackexchange", "id": 42965, "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, authentication", "url": null }
php, authentication $stmt4->bindParam(':USERID', $user_id); if ($stmt4->execute()) { $row5 = $stmt4->fetch(PDO::FETCH_ASSOC); $returnApp = array( 'LOGIN' => 'Log_In_Success', 'user' =>$row2['user_type'], 'CL' =>$row5['CLASS'], 'DEP' => $row5['DEPARTMENT'], 'HD' => $row5['HEAD'], 'id' => $row5['login_id'], 'token' => $row5['user_token']); echo json_encode($returnApp); } } } }else { $returnApp = array( 'LOGIN' => 'Log_In_Failed'); echo json_encode($returnApp); } } else { $returnApp = array( 'LOGIN' => 'Email_Doesnt_Exist'); echo json_encode($returnApp); } } Answer: The good thing about your code is that that you use prepared statements with bound variables. Too often we see input variables in query strings. Also nice is the use of the filter_var() function instead of a complex regular expression. But that's where the good things end. You haven't properly indented the code, which makes it hard to read. And hard to read it is. This is a very complex piece of code with lots of nested if ...else ... and exit. To illustrate this point; This is what the structure of your code looks like: if (....) { exit; } else { try { } catch (....) { exit; } if (....) { if (....) { function name(....) { return ....; } foreach (....) { if (....) { if (....) { } } if (....) { if (....) { } } if (....) { if (....) { } } } } else { } } else { } }
{ "domain": "codereview.stackexchange", "id": 42965, "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, authentication", "url": null }
php, authentication Even when properly indented, and without most of the code, it is difficult to understand. The technical term for this type of code is: Spaghetti code. It is difficult to understand and harder to maintain. That is, I have to say, the biggest security risk here. Another problem, also caused by the lack of structure, is that there's quite a bit of repetition of code. See: Don't repeat yourself. I count five echo json_encode($returnApp);. You have four select queries, going through the same routine every time. You could create a function for that. Something like: function retrieveData($db, $query, $parameters = []) { $statement = $db->prepare($query); foreach ($parameters as $placeholder => $value) { $statement->bindValue($placeholder, $value); } $data = null; if ($statement->execute()) { $data = $statement->fetchAll(PDO::FETCH_ASSOC); } return $data; } Or any variant thereof. The basic idea is to encapsulate things you do repeatedly in an easy to read, and therefore easy to understand, function. On top of that you can much better test this function in isolation, than you can with code that is embedded in other code. Note that I even made the function more powerful than you actually need right now: It can cope with multiple parameters and output multiple rows. I challenge you to restructure your code so you only need one echo json_encode($returnApp); and you don't have any if blocks, nested deeper than 1 level, anymore. Use functions for this. You'll find that your code will be much easier to read and maintain.
{ "domain": "codereview.stackexchange", "id": 42965, "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, authentication", "url": null }
javascript, performance, functional-programming, json, ecmascript-6 Title: Download entire localStorage as file Question: I would like to download the entire contents from localStorage to a json file (in a "clear" formatting). I've tried this and it works perfectly. However, I'm not sure it's very performant. If possible I'd like to keep the inline syntax. const download = () => ( Object.assign(document.createElement("a"), { href: `data:application/JSON, ${encodeURIComponent( JSON.stringify( Object.keys(localStorage).reduce( (obj, k) => ({ ...obj, [k]: JSON.parse(localStorage.getItem(k)) }), {} ), null, 2 ) )}`, download: "your_history", }).click() ) Answer: Code Style Though it is brief, the function has consistent indentation and isn’t too complex. However it does look a bit “pyramid shaped” - also known as “callback hell”. Performance However, I'm not sure it's very performant If performance is a concern, then consider a regular for...in loop instead of the functional approach with Object.keys().reduce(), though it may be difficult to keep the inline syntax. Functionality This code seems congruent with most of the answers to Download JSON object as a file from browser on StackOverflow. There is at least one answer there that mentions a library FileSaver.js which abstracts all of the logic of saving the file. Unless adding a library is more overhead than desired, that could allow great simplification and compatibility with more browsers. Usability It appears the code only works with values that are objects or arrays, but would throw an error for some values like strings. Take for example: setting a localStorage item to a string literal: localStorage.setItem('username', 'Gibberish'); Yet when such a value is parsed using JSON.parse() an error occurs: JSON.parse('Gibberish') It might be wise to update the code at JSON.parse(localStorage.getItem(k)) to ensure the item is not a string literal.
{ "domain": "codereview.stackexchange", "id": 42966, "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, performance, functional-programming, json, ecmascript-6", "url": null }
c, formatting, integer, assembly, x86 Title: Minimal `printf` for integer types in x86 assembly Question: I'm writing a minimal C runtime targeting an old 32-bit Windows XP machine as a personal project. The C runtime provided by compilers is quite bloated. I wouldn't mind some library bloats up to several megabytes if this was some paid project, since even a very old PC would load it very fast anyway, but as a personal project, I'm just doing whatever comforts me. (1) This printf can currently only handle %d, %lld, %u, and %llu. The routine is optimized for size, not for speed. IO doesn't happen in a middle of a hot loop - if it does, it is not a hot loop - so it makes more sense to take the minimal amount of size in an executable. div with a constant divisor is preferred over multiply and shift with the multiplicative inverse. mov xl, byte [] instead of movsx exx, byte []; saves a byte packed code, unaligned jump targets Code duplication is avoided whenever possible. Non-variadic functions follow the regparm(3) calling convention. The arguments are passed to eax, edx, and ecx in order, and the return value is stored in eax and edx. A local function divq10 disobeys the rule by also returning with ecx. printf.s section .bss stdout: resb 4 section .text extern _GetStdHandle@4 extern _WriteFile@20 err: ud2 global _initstdout _initstdout: push -11 call _GetStdHandle@4 cmp eax, -1 je err mov [stdout], eax ret divq10: ; edx:eax <- edx:eax / 10, ecx <- remainder push ebx mov ecx, eax mov eax, edx xor edx, edx mov ebx, 10 div ebx mov ebx, eax mov eax, ecx mov ecx, 10 div ecx mov ecx, edx mov edx, ebx pop ebx ret
{ "domain": "codereview.stackexchange", "id": 42967, "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, formatting, integer, assembly, x86", "url": null }
c, formatting, integer, assembly, x86 llu2str: ; edx:eax -> *ecx (string), eax <- count push ebx push edi push esi push ebp mov edi, eax mov esi, edx mov ebp, ecx xor ebx, ebx .0: inc ebx call divq10 mov ecx, eax or ecx, edx jnz .0 mov eax, edi mov edx, esi mov edi, ebx .1: call divq10 add ecx, '0' dec ebx mov [ebp + ebx], cl jnz .1 mov eax, edi pop ebp pop esi pop edi pop ebx ret global _printf _printf: push ebx push edi push esi push ebp lea ebp, [esp + 24] mov esi, [ebp - 4] sub esp, 1024 mov edi, esp .start: mov bl, [esi] test bl, bl jz .end cmp bl, '%' jne .copy inc esi mov bl, [esi] cmp bl, 'u' jne .d0 mov eax, [ebp] add ebp, 4 xor edx, edx .u1: mov ecx, edi call llu2str add edi, eax jmp .next .d0: mov bl, [esi] cmp bl, 'd' jne .ll mov eax, [ebp] add ebp, 4 cdq .d1: mov ecx, edx shr ecx, 31 jz .u1 mov byte [edi], '-' inc edi neg eax adc edx, 0 neg edx jmp .u1 .ll: mov bl, [esi] cmp bl, 'l' jne err inc esi mov bl, [esi] cmp bl, 'l' jne err inc esi mov eax, [ebp] mov edx, [ebp + 4] add ebp, 8 mov bl, [esi] cmp bl, 'u' je .u1 cmp bl, 'd' je .d1 jmp err .copy: mov [edi], bl inc edi .next: inc esi jmp .start .end: mov eax, esp push 0 push edi sub edi, eax push edi push eax push dword [stdout] call _WriteFile@20 test eax, eax jz err add esp, 1024 pop ebp pop esi pop edi pop ebx ret test.c void initstdout(void); void printf();
{ "domain": "codereview.stackexchange", "id": 42967, "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, formatting, integer, assembly, x86", "url": null }
c, formatting, integer, assembly, x86 test.c void initstdout(void); void printf(); void start() { initstdout(); printf("Hello, world!\n"); printf("%d %u %lld %llu\n", 0, 0, 0, 0); int dm = 1u << 31; int dx = (1u << 31) - 1; int ux = -1; long long lldm = 1llu << 63; long long lldx = (1llu << 63) - 1; long long llux = -1; printf("%d %d %d\n%lld %lld %lld\n", dm, dx, ux, lldm, lldx, llux); printf("%u %u %u\n%llu %llu %llu\n", dm, dx, ux, lldm, lldx, llux); } build.sh O="-O3 -msse2 -fno-builtin -fno-asynchronous-unwind-tables" S="-std=c11 -pedantic -masm=intel" F="$O $S" LF="--entry=_start --subsystem=console --enable-stdcall-fixup" SYS="/c/Windows/SysWOW64" gcc -c $F test.c nasm -fwin32 printf.s ld -or.exe $LF *.o *.obj $SYS/kernel32.dll I used gcc and ld, but MSVC's cl and link should also work fine. I had to put --enable-stdcall-fixup to shut up warnings, but I currently don't know why those warnings are happening. AFAIK Windows API functions have _@ decorations on 32-bit, but the linker is complaining that I shouldn't have put those decorations. output Hello, world! 0 0 0 0 -2147483648 2147483647 -1 -9223372036854775808 9223372036854775807 -1 2147483648 2147483647 4294967295 9223372036854775808 9223372036854775807 18446744073709551615 (1) MinGW GCC creates a 100KB executable for a single call to printf, including all the initialization code, and its own fix-up code to patch the default Windows C runtime. MSVC provides a several-hundred-KB DLL runtime, which should always be provided as-is to distribute freely.
{ "domain": "codereview.stackexchange", "id": 42967, "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, formatting, integer, assembly, x86", "url": null }
c, formatting, integer, assembly, x86 Answer: If, for the sake of this exercise, codesize is the only thing that you care about, then I would dare suggest the following: For divq10, not having to reload the constant will save 5 bytes, and using xchg with the EAX register is shorter as it is a 1-byte instruction. Total savings 12 bytes. divq10: ; edx:eax <- edx:eax / 10, ecx <- remainder push ebx push ebx mov ecx, eax xor ecx, ecx mov eax, edx xchg eax, ecx xor edx, edx xchg eax, edx mov ebx, 10 mov ebx, 10 div ebx div ebx mov ebx, eax xchg eax, ecx mov eax, ecx div ebx mov ecx, 10 xchg ecx, edx div ecx pop ebx mov ecx, edx ret mov edx, ebx pop ebx ret
{ "domain": "codereview.stackexchange", "id": 42967, "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, formatting, integer, assembly, x86", "url": null }
c, formatting, integer, assembly, x86 In llu2str you essentially use the EDI and ESI registers for preservation. Why not simply push/pop the values so you can omit preserving these registers themselves? Total savings 10 bytes. llu2str: ; edx:eax -> *ecx (string), eax <- count push ebx push ebx push edi push esi push ebp push ebp mov edi, eax push eax ; (1) mov esi, edx push edx ; (2) mov ebp, ecx mov ebp, ecx xor ebx, ebx xor ebx, ebx .0: .0: inc ebx inc ebx call divq10 call divq10 mov ecx, eax mov ecx, eax or ecx, edx or ecx, edx jnz .0 jnz .0 mov eax, edi pop eax ; (2) mov edx, esi pop edx ; (1) mov edi, ebx push ebx ; (3) .1: .1: call divq10 call divq10 add ecx, '0' add ecx, '0' dec ebx dec ebx mov [ebp + ebx], cl mov [ebp + ebx], cl jnz .1 jnz .1 mov eax, edi pop eax ; (3) pop ebp pop ebp pop esi pop edi pop ebx pop ebx ret ret In _printf, when hopping to .d0, the BL register did not change and when branching to .ll it didn't change either. You can omit mov bl, [esi] that reloads it. The code to see if the number is negative mov ecx, edx shr ecx, 31 jz .u1 can be replaced by the shorter test edx, edx jns .u1. Checking for the double 'll' can happen in one go: .ll: .ll: mov bl, [esi] cmp word [esi], 'll' cmp bl, 'l' jne err jne err inc esi inc esi inc esi mov bl, [esi] cmp bl, 'l' jne err inc esi
{ "domain": "codereview.stackexchange", "id": 42967, "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, formatting, integer, assembly, x86", "url": null }
r Title: A function that modifies the column types of a `data.frame`, given a character vector of "format codes" Question: Problem A business process requires me to read two different text files (raw and processed) into R as data.frames, with each column being read as a character type. Both files contain the same information, though the numeric columns are formatted slightly differently. I need to convert the column types of both data.frames to the appropriate class, using special formatting codes. Both file types (raw/processed) use the same formatting codes for each column. I've created a function that accepts a data.frame, a character vector of formatting codes, and whether the data is raw or processed. This function then returns a data.frame with the proper columns. Formatting Codes EDIT: I don't have control over the formatting codes. For this bit of code the numbers in parentheses are not used. e.g., the "09" in "C(09)" Formatting codes for each column follow 3 distinct patterns (of which there should be no overlap): "C(05)": Represents a character with length 5. Other examples include "C(13)", "C(01)". The two digit number in parentheses will be between 01 and 99. "N(09)": Represents integer with 9 numbers. Other examples include "N(13)", "N(01)". The two digit number in parentheses will be between 01 and 99. "NNVNN": Represents numeric column with 4 numbers and an implied decimal between number 2 and 3 (e.g. 22.45). The "V" represents where the decimal should be.
{ "domain": "codereview.stackexchange", "id": 42968, "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": "r", "url": null }
r Difference between raw and processed files The main difference is how floating numbers are represented. In the raw file, there is only an implied decimal point whereas in the processed file the decimal point is explicit. The formatting code for floating numbers (e.g., "NNVNN") explains where the decimal should be. (The "V" is where the decimal place goes) Goal for Review I am open to any feedback at all. My primary concerns lie with the implementation of the which_regex function and the fmt_func function. It feels like there should be a better way to implement both in order to eventually scale the types of "files" (e.g., raw/processed). While I was hoping to have fmt_func vectorised, I was unable to do so and maintain a general readability. This code was modified from the actual code I wrote, because I use a naming convention more specific to the business case in the actual code. Data for Testing # Source Data raw <- data.frame( a = c("12345", "00123", "10000"), b = c("12345", "00123", "10000"), c = c("12345", "00123", "10000"), d = c("12345", "00123", "10000"), stringsAsFactors = FALSE ) # Processed Data processed <- data.frame( a = c("12345", "00123", "10000"), b = c("12345", "123", "10000"), c = c("12345", "1.23", "100."), d = c("12.345", ".123", "10."), stringsAsFactors = FALSE ) # Format Specification Codes # Each element maps to the columns in data above. fmts <- c("C(05)", "N(05)", "NNNVNN", "NNVNNN") Code Developed to Solve Problem # Goal: Function that formats columns of a data.frame to desired specifications. # Specifications are indicated by formatting codes. fmt_data <- function(data, fmts, raw=TRUE){ f <- purrr::map(fmts, fmt_func, raw=raw) purrr::map2_df(data, f, ~ .y(.x)) }
{ "domain": "codereview.stackexchange", "id": 42968, "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": "r", "url": null }
r # Given a string `x`, what's the index of the supplied regex pattern that matches it. which_regex <- function(x, patterns){ matches <- unlist(lapply(patterns, grepl, x = x)) match_matrix <- matrix(matches, ncol=length(patterns)) indices <- which(match_matrix, arr.ind = TRUE)[,2] as.integer(indices) } # Chooses the column formatting function based on the format code # I believe this function is technically a "function factory"? fmt_func <- function(fmt, raw = TRUE){ # These are regex patterns that match to the three types of formatting codes patterns <- c("^(C)\\([0-9]{2}\\)$", "^(N)\\([0-9]{2}\\)$", "^N+V+N*$") # which_regex is defined above ind <- which_regex(fmt, patterns) # If it's a 'raw' data.frame, we'll need to specify where the decimal place goes, # so choose option 4 opt <- ifelse(ind==3 & raw, 4, ind) f <- switch(opt, as.character, as.integer, as.numeric, function(x){ force(fmt) as.numeric(x) / (10 ^ nchar(unlist(strsplit(fmt, "V"))[2])) } ) f } Example Using Testing Data Above fmt_data(raw, fmts, raw=TRUE) fmt_data(processed, fmts, raw=FALSE) ```
{ "domain": "codereview.stackexchange", "id": 42968, "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": "r", "url": null }
r fmt_data(processed, fmts, raw=FALSE) ``` Answer: Edit I am new to Code review and yes have provided answers on StackOverflow. As explained by @pacmaninbw my answer lacks clarity for a review so let me try to motivate my approach. which_regex function is not needed as the switch to detect can be done on your sanitized expressions. The first switch case can easily be "C" and there is no need to translate that to 1. One could even argue using the letters makes it more readable and we save the need for that function. The input fmts is more detailed than what the function actually does so can easily be translated up front. Like C(05) and C(99) do the same thing, same for N() and NNNVNNN the N's prior to V are always ignored. We can simply translate those to C, N, VN* strings. We then can use the switch based on C, N and use the default case to take the nchar-1 to get the position of the dots. Perhaps switching to data.table could be considered personal preference so that can surely be argued as an improvement of code. But all above this to skip out the which_regex function is I think still a valid improvement you dan do while keeping your purr approach. original post After some thoughts and reading your comments, I think this could be a way to go. function fmt_data <- function(data, fmts, raw = TRUE) { fmts_translated <- gsub("^(C|N)\\(.+|^N+(V+N*$)", "\\1\\2", fmts) # could also be outside the function I think cols <- names(data) out <- data[, lapply(seq_along(names(.SD)), function(i) { switch(fmts_translated[[i]], "C" = as.character(.SD[[i]]), "N" = as.integer(.SD[[i]]), if(raw) as.numeric(.SD[[i]]) / (10 ^ nchar(fmts_translated[i])-1) else (as.numeric(.SD[[i]])) ) }), .SDcols = cols] setnames(out, new = cols) return(out) }
{ "domain": "codereview.stackexchange", "id": 42968, "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": "r", "url": null }
r edit I think that fmts_translated <- gsub("^(C|N)\\(.+|^N+(V+N*$)", "\\1\\2", fmts) should be outside the function actually as it is depending on your fmts and if you happen to run your function many times on for example many tables there is no need to translate fmts over again for every function call if fmts remains the same. usage and output note that I use data.table here library(data.table) # make it a data.table setDT(raw) setDT(processed) fmt_data(raw, fmts, raw = TRUE) # a b c d # 1: 12345 12345 123.45 12.345 # 2: 00123 123 1.23 0.123 # 3: 10000 10000 100.00 10.000 # Classes ‘data.table’ and 'data.frame': 3 obs. of 4 variables: # $ a: chr "12345" "00123" "10000" # $ b: int 12345 123 10000 # $ c: num 123.45 1.23 100 # $ d: num 12.345 0.123 10 # - attr(*, ".internal.selfref")=<externalptr> fmt_data(processed, fmts, raw = FALSE) # a b c d # 1: 12345 12345 12345.00 12.345 # 2: 00123 123 1.23 0.123 # 3: 10000 10000 100.00 10.000 # Classes ‘data.table’ and 'data.frame': 3 obs. of 4 variables: # $ a: chr "12345" "00123" "10000" # $ b: int 12345 123 10000 # $ c: num 12345 1.23 100 # $ d: num 12.345 0.123 10 # - attr(*, ".internal.selfref")=<externalptr> data raw <- data.frame( a = c("12345", "00123", "10000"), b = c("12345", "00123", "10000"), c = c("12345", "00123", "10000"), d = c("12345", "00123", "10000"), stringsAsFactors = FALSE ) # Processed Data processed <- data.frame( a = c("12345", "00123", "10000"), b = c("12345", "123", "10000"), c = c("12345", "1.23", "100."), d = c("12.345", ".123", "10."), stringsAsFactors = FALSE ) # Format Specification Codes # Each element maps to the columns in data above. fmts <- c("C(05)", "N(05)", "NNNVNN", "NNVNNN")
{ "domain": "codereview.stackexchange", "id": 42968, "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": "r", "url": null }
python, pandas Title: find maximum corresponding column for maximum value after group by Question: For my haves: I want to find the key values for the maximum value whilst grouping by g1 and g2 to get these wants: This is my current possibly (?) clumsy code: df = pd.DataFrame({ 'value': [0, 1, 1, 3], 'g1': ["b", "b", "c", "c"], 'g2': ["a", "a", "a", "a"], 'key': ["1", "2", "3", "4"] }) print(df) stats = df.groupby(["g1", "g2"])["value"].max().reset_index() pd.merge(df, stats, left_on=["g1", "g2", "value"], right_on=["g1", "g2", "value"], how="inner") Any improvement suggestions would be very much welcome please. Thanks. Answer: Recognise that your first pass should not be to find the group maxima: it should be to find the indices of the group maxima. From there it is easy to index into the original dataframe to retrieve the desired maximum rows: import pandas as pd df = pd.DataFrame({ 'value': (0, 1, 1, 3), 'g1': ('b', 'b', 'c', 'c'), 'g2': ('a', 'a', 'a', 'a'), 'key': ('1', '2', '3', '4') }) imax = df.groupby(['g1', 'g2']).value.idxmax() result = df.loc[imax] However, your original dataframe construction has an issue. If key is truly a key, you should be using it as your index instead of the implicit numeric-range index: import pandas as pd df = pd.DataFrame({ 'value': (0, 1, 1, 3), 'g1': ('b', 'b', 'c', 'c'), 'g2': ('a', 'a', 'a', 'a'), 'key': ('1', '2', '3', '4') }).set_index('key') imax = df.groupby(['g1', 'g2']).value.idxmax() result = df.loc[imax]
{ "domain": "codereview.stackexchange", "id": 42969, "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, pandas", "url": null }
python, performance, array, excel, random Title: Python - Efficiently pick random data from an array, generate random UUIDs and save it all in an Excel table Question: I wrote the following prototype: import xlsxwriter import numpy as np import pandas as pd import random import uuid workbook = xlsxwriter.Workbook('test.xlsx') worksheet = workbook.add_worksheet() companyissuearray = ['3001', 'Test1', 'TestCat1', 'TesSubtCat1'], ['3002', 'Test2', 'TestCat1', 'TesSubtCat1'], ['3003', 'Test3', 'TestCat1', 'TesSubtCat1'], ['3011', 'Test4', 'TestCat1', 'TestSubCat2'], ['3012', 'Test5', 'TestCat1', 'TestSubCat2'], ['3013', 'Test6', 'TestCat1', 'TestSubCat2'], ['3021', 'Test7', 'TestCat1', 'TestSubCat3'], ['3022', 'Test8', 'TestCat1', 'TestSubCat3'], ['3023', 'Test9', 'TestCat1', 'TestSubCat3'], ['1001', 'Test10', 'TestCat2', 'TesSubtCat1'], ['1002', 'Test11', 'TestCat2', 'TesSubtCat1'], ['1003', 'Test12', 'TestCat2', 'TesSubtCat1'], ['1011', 'Test13', 'TestCat2', 'TestSubCat2'], ['1012', 'Test14', 'TestCat2', 'TestSubCat2'], ['1013', 'Test15', 'TestCat2', 'TestSubCat2'], ['1021', 'Test16', 'TestCat2', 'TestSubCat3'], ['1022', 'Test17', 'TestCat2', 'TestSubCat3'], ['1023', 'Test18', 'TestCat2', 'TestSubCat3'], ['2001', 'Test19', 'TestCat3', 'TesSubtCat1'], ['2002', 'Test20', 'TestCat3', 'TesSubtCat1'], ['2003', 'Test21', 'TestCat3', 'TesSubtCat1'], ['2011', 'Test22', 'TestCat3', 'TestSubCat2'], ['2012', 'Test23', 'TestCat3', 'TestSubCat2'], ['2013', 'Test24', 'TestCat3', 'TestSubCat2'], ['2021', 'Test25', 'TestCat3', 'TestSubCat4'], ['2022', 'Test26', 'TestCat3', 'TestSubCat4'], ['2023', 'Test27', 'TestCat3', 'TestSubCat4']
{ "domain": "codereview.stackexchange", "id": 42970, "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, performance, array, excel, random", "url": null }
python, performance, array, excel, random companyissueid = ['3001', '3002', '3003', '3011','3012', '3013','3021','3022','3023','1001','1002','1003','1011','1012','1013','1021','1022','1023','2001','2002','2003','2011','2012','2013','2021','2022','2023'] companyissuecat = ['Test1', 'Test2', 'Test3', 'Test4', 'Test5', 'Test6', 'Test7','Test8','Test9','Test10','Test11','Test12','Test13','Test14','Test15','Test16','Test17','Test18','Test19','Test20','Test21', 'Test22','Test23', 'Test24', 'Test25', 'Test26', 'Test27'] companyissuetype = ['TestCat1', 'TestCat1','TestCat1','TestCat1','TestCat1','TestCat1','TestCat1','TestCat1', 'TestCat2','TestCat2','TestCat2','TestCat2','TestCat2','TestCat2','TestCat2','TestCat2','TestCat2', 'TestCat3','TestCat3','TestCat3', 'TestCat3','TestCat3','TestCat3','TestCat3','TestCat3','TestCat3'] companyissuesubcat=['TesSubtCat1', 'TesSubtCat1', 'TestSubCat2', 'TestSubCat2', 'TestSubCat2', 'TestSubCat3', 'TestSubCat3', 'TestSubCat3', 'TesSubtCat1', 'TesSubtCat1', 'TesSubtCat1', 'TestSubCat2', 'TestSubCat2', 'TestSubCat2', 'TestSubCat3', 'TestSubCat3', 'TestSubCat3', 'TesSubtCat1', 'TesSubtCat1', 'TesSubtCat1', 'TestSubCat2', 'TestSubCat2', 'TestSubCat2', 'TestSubCat4', 'TestSubCat4', 'TestSubCat4']
{ "domain": "codereview.stackexchange", "id": 42970, "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, performance, array, excel, random", "url": null }
python, performance, array, excel, random templateArray = ['3001', 'LA001', 'Test1 bah'], ['3001', 'LA002', 'Test1 bzh'], ['3001', 'LV001', 'Test1 adsf'], ['3002', 'LA003', 'afdgfdag'], ['3002', 'LA004', 'htrhesdfg'], ['3002', 'LA005', 'fasdfasfd'], ['3003', 'LA006', 'poigf'], ['0003', 'LA007', 'asfdcx'], ['0003', 'LA008', 'xyzc'], ['3011', 'LB001', 'cyxz'], ['3011', 'LB002', 'cyrek'], ['3011', 'LB003', 'yomai'], ['3012', 'LB004', 'maiyo'], ['3012', 'LB005', 'breakfast'], ['3012', 'LB006', 'thedaleksarecoming'], ['3013', 'LB007', 'mustfeedthemothership'], ['3013', 'LB008', 'withgreatresponsitribilities'], ['3013', 'LB009', 'comesgreat'], ['3021', 'LL001', 'stuff'], ['3021', 'LL002', 'this'], ['3021', 'LL003', 'should'], ['3022', 'LL004', 'be'], ['3022', 'LL005', 'random'], ['3022', 'LL006', 'but'], ['3023', 'LL007', 'it'], ['3023', 'LL008', 'aint'], ['3023', 'LL009', 'egsf'], ['1001', 'KA001', 'eggs'], ['1001', 'KA002', 'spoon'], ['1001', 'KA003', 'nuts'], ['1002', 'KA004', 'cereal'], ['1002', 'KA005', 'Frank'], ['1002', 'KA006', 'John'], ['1003', 'KA007', 'Doe'], ['1003', 'KA008', 'Dove'], ['1003', 'KA009', 'Johnny'], # TRUNCATED # there's more of this stuff...
{ "domain": "codereview.stackexchange", "id": 42970, "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, performance, array, excel, random", "url": null }
python, performance, array, excel, random templateArrayID = ['3001', '3001','3001','3002','3002','3002','3003','0003','0003','3011','3011','3011','3012','3012','3012','3013','3013','3013','3021','3021','3021','3022','3022','3022','3023','3023', '3023','1001','1001','1001','1002','1002','1002','1003','1003','1003','1011','1011','1011','1012','1012','1012','1013','1013','1013','1021','1021','1021','1022','1022','1022','1023','1023','1023','2001', '2001','2001','2002','2002','2002','2003','2003','2003','2011','2011','2011','2012','2012','2012','2013','2013','2013','2021','2021','2021','2022','2022','2022','2023','2023','2023'] templateArrayCode = ['LA001', 'LA002','LV001','LA003','LA004','LA005','LA006','LA007','LA008','LB001','LB002','LB003','LB004','LB005','LB006','LB007','LB008','LB009','LL001','LL002','LL003','LL004','LL005', 'LL006','LL007','LL008','LL009','KA001','KA002','KA003','KA004','KA005','KA006','KA007','KA008','KA009','KB001','KB002','KB003','KB004','KB005','KB006','KB007','KB008','KB009','KL001','KL002','KL003','KL004', 'KL005','KL006','KL007','KL008','KL009','SA001','SA002','SA003','SA004','SA005','SA006','SA007','SA008','SA009','SB001','SB002','SB003','SB004','SB005','SB006','SB007','SB008','SB009','SL001','SL002','SL003', 'SL004','SL005','SL006','SL007','SL008','SL009'] templateArrayTemplateName = ['truncatedforbrevity','seethearraysaboveforanexample'] #should I just np.array at this point?.. # what is this amateur stuff? #LIMIT=2000000 # now we cooking with gas! LIMIT=10000000 i=0 row=0 while i < LIMIT: """ col= random.randint(0,25) data= random.choice(GeVoArray) worksheet.write_column(row,col,data) """ # print(random.choices(GeVoArrayZiffern)) # print(random.choices(GeVoArrayKategorie)) # print(random.choices(GeVoArrayArt)) # print(random.choices(GeVoArraySubkategorie)) i += 1
{ "domain": "codereview.stackexchange", "id": 42970, "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, performance, array, excel, random", "url": null }
python, performance, array, excel, random uuid_list = [str(uuid.uuid4()) for _ in range(LIMIT)] for row in range(0,LIMIT): #test=uuid.uuid4() worksheet.write_column(row, 0, random.choices(companyissueid)) worksheet.write_column(row, 1, random.choices(companyissuecat)) worksheet.write_column(row, 2, random.choices(companyissuetype)) worksheet.write_column(row, 3, random.choices(companyissuesubcat)) worksheet.write_column(row, 4, uuid_list) worksheet.write_column(row, 5, random.choices(templateArrayID)) worksheet.write_column(row, 6, random.choices(templateArrayCode)) worksheet.write_column(row, 7, random.choices(TemplateArrayTemplateName)) row += 1 test= uuid.uuid4() print(test) print(type(test)) workbook.close() It does basically the following: It randomly picks values from the predefined arrays to generate a random data table containing those specific predefined values. Also one column is just random UUIDs which appears to be working but not especially fast. Credits to SSayan from https://stackoverflow.com/questions/71155509/python-save-a-column-in-excel-with-a-lot-of-rows-with-random-uuids It does not have to truly random, pseudorandom is ok and hence I'm using UUIDv4 for the UUIDs and random.choices for picking the values. The problem It took way over 11 minutes (I stopped the execution) to generate 100k values and I need values in millions of rows. How do I optimize this? Would using numpy's array make my code way more efficient? I need to make my code at least 100x faster considering the run time above... Answer: I think there is a misunderstanding in what this does: uuid_list = [str(uuid.uuid4()) for _ in range(LIMIT)] This is what is called a list comprehension in Python. It is a compact way of doing a for loop. It is equivalent to this: uuid = [] for i in range(LIMIT): uuid_list.append(str(uuid.uuid4()))
{ "domain": "codereview.stackexchange", "id": 42970, "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, performance, array, excel, random", "url": null }
python, performance, array, excel, random So what your code does with the while i < LIMIT is computing a list of a million UUIDs, a million times. Same for the writing part: you are writing the columns a million times. Remember the previous post, the write_column() is already a loop somehow. The code should just be: LIMIT=1_000_000 for row in range(0,LIMIT): #test=uuid.uuid4() worksheet.write(row, 0, random.choice(companyissueid)) worksheet.write(row, 1, random.choice(companyissuecat)) worksheet.write(row, 2, random.choice(companyissuetype)) worksheet.write(row, 3, random.choice(companyissuesubcat)) worksheet.write(row, 4, str(uuid.uuid4())) worksheet.write(row, 5, random.choice(templateArrayID)) worksheet.write(row, 6, random.choice(templateArrayCode)) worksheet.write(row, 7, random.choice(TemplateArrayTemplateName)) workbook.close() NOTE: for a million lines it took 81s on my system. Be careful - the limit in your example code is ten million lines. You can use the underscores as I do to see how many zeros you have: 1_000_000 is the same as 1000000 or 10**6. PS: you should not increment (row+=1) in a for loop. Pandas version This pandas version takes less than 15s (on the same system) for a million lines :). import pandas as pd from tqdm import tqdm import time start_time = time.time() columns = {f"column{i}":[] for i in range(8)} for _ in tqdm(range(LIMIT)): columns["column0"].append(random.choice(companyissueid)) columns["column1"].append(random.choice(companyissuecat)) columns["column2"].append(random.choice(companyissuetype)) columns["column3"].append(random.choice(companyissuesubcat)) columns["column4"].append(str(uuid.uuid4())) columns["column5"].append(random.choice(templateArrayID)) columns["column6"].append(random.choice(templateArrayCode)) columns["column7"].append(random.choice(templateArrayTemplateName))
{ "domain": "codereview.stackexchange", "id": 42970, "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, performance, array, excel, random", "url": null }
python, performance, array, excel, random data_generation_end = time.time() print(f"Data Generation: {data_generation_end - start_time:.2f}s") data_df = pd.DataFrame(columns) data_df.to_csv("test_million.csv") print(f"Write to CSV: {time.time() - data_generation_end :.2f}s") print(f"Overall time: {time.time() - start_time :.2f}s") 100%|██████████| 1000000/1000000 [00:08<00:00, 122234.30it/s] Data Generation: 8.20s Write to CSV: 4.56s Overall time: 12.76s
{ "domain": "codereview.stackexchange", "id": 42970, "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, performance, array, excel, random", "url": null }
java, queue Title: Animal shelter simulation using Queues Question: This is of one the interesting problems I've solved: An animal shelter holds only dogs and cats, and operates on a strictly "first in, first out" basis. People must adopt either the "oldest" (based on arrival time) of all animals at the shelter, or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of that type). They cannot select which specific animal they would like. Create the data structures to maintain this system and implement operations such as enqueue, dequeueAny, dequeueDog and dequeueCat. My algorithm: Maintain two Queues, CatQ and a DogQ. If the user wants a Cat, dequeue from the CatQ, and if he wants a Dog, dequeue from DogQ. The problem gets trickier for dequeueAny, since there are two Queues and should be served on FIFO basis. While enqueuing, I'm inserting the arrivalTime too, so whichever animal has the lowestarrivalTime will be dequeued first. Implementation: static class Node<T>{ Node<T> next; T type; String animalName; int arrivalTime; Node(String name){ this.animalName = name; } @Override public String toString(){ return this.animalName; } } static class Dog{ } static class Cat{ } static class Queue<T>{ Node<T> front, rear; public void enq(Node<T> toEnq){ if(rear==null){ rear = toEnq; front = rear; }else{ rear.next = toEnq; rear = rear.next; } } public Node deq(){ if(front==null){ System.out.println("Underflow!"); return new Node("Error"); }else{ Node<T> frn = front; front = front.next; return frn; } }
{ "domain": "codereview.stackexchange", "id": 42971, "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, queue", "url": null }
java, queue public void printQ(){ Node<T> temp = front; if(this.isEmpty()){ System.out.println("No animals here"); return; } while(temp.next!=null){ System.out.print(temp.animalName + "->"); temp = temp.next; } System.out.println(temp.animalName); } public boolean isEmpty(){ return front == null; } } static class AnimalHouse{ Queue<Cat> catQ = new Queue<Cat>() ; Queue<Dog> dogQ = new Queue<Dog>(); Node prev, qFront, qRear; int arrivalTime = 0; public void enq(Node toEnq, String animal){ toEnq.arrivalTime = this.arrivalTime; arrivalTime++; if(animal.equals("Cat")){ catQ.enq(toEnq); }else{ dogQ.enq(toEnq); } } public Node<Dog> deqDog(){ return dogQ.deq(); } public Node<Cat> deqCat(){ return catQ.deq(); } public Node deqAny(){ if(catQ.isEmpty()){ return deqDog(); } if(dogQ.isEmpty()){ return deqCat(); } if(catQ.front.arrivalTime < dogQ.front.arrivalTime){ return deqCat(); }else{ return deqDog(); } } public void printAnimalHouse(){ System.out.println("Cats in the Animal House : "); catQ.printQ(); System.out.println("Dogs in the Animal House : "); dogQ.printQ(); } }
{ "domain": "codereview.stackexchange", "id": 42971, "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, queue", "url": null }
java, queue public static void main(String[] args) { AnimalHouse myHouse = new AnimalHouse(); myHouse.enq(new Node<Cat>("bela"), "Cat"); myHouse.enq(new Node<Dog>("rufus"), "Dog"); myHouse.enq(new Node<Cat>("browny"), "Cat"); myHouse.enq(new Node<Dog>("meenu"), "Dog"); myHouse.enq(new Node<Cat>("chownmy"), "Cat"); myHouse.enq(new Node<Cat>("pinky"), "Cat"); myHouse.enq(new Node<Cat>("blacky"), "Cat"); myHouse.enq(new Node<Dog>("leo"), "Dog"); myHouse.enq(new Node<Dog>("rockstar"), "Dog"); myHouse.enq(new Node<Cat>("Google"), "Cat"); myHouse.enq(new Node<Dog>("Yahoo"), "Dog"); myHouse.enq(new Node<Cat>("square"), "Cat"); myHouse.enq(new Node<Cat>("rectangel"), "Cat"); myHouse.enq(new Node<Cat>("fire"), "Cat"); myHouse.enq(new Node<Dog>("iota"), "Dog"); myHouse.printAnimalHouse(); System.out.println(myHouse.deqAny()); } A Problem which I'd like to mention: There's no particular reason why I made independent Cat and Dog classes; I just wanted to differentiate between those. I had a hard time resolving the issue for differentiating between Node<Cat> and Node<Dog> as it is not possible to find out the data type of generic parameter at runtime. I also don't want to complicate the instantiation process (better see the link), so in the end I had to insert node like this: myHouse.enq(new Node<Cat>("CatName"), "Cat") which is somewhat dumb, so are there any suggestions on how I could've made it more sensible?
{ "domain": "codereview.stackexchange", "id": 42971, "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, queue", "url": null }
java, queue which is somewhat dumb, so are there any suggestions on how I could've made it more sensible? Answer: Structure So your structure is definitely a bit off. First of all, you made your Node generic, which is good, as it could theoretically work with any content - which is what you want from a queue. But then, you have fields which just don't belong there, such as animalName (and type, which is just not needed). So first of all, lets move animalName outside of the node and into the animal classes, where it belongs. As cats and dogs are both animals, lets also create an Animal class which both extend: static class Dog extends Animal { public Dog(String name) { super(name); } } static class Cat extends Animal { public Cat(String name) { super(name); } } static class Animal { String animalName; public Animal(String name) { this.animalName = name; } @Override public String toString() { return this.animalName; } } Now our Node class makes more sense (we'll remove arrivalTime later as well): static class Node<T>{ Node<T> next; int arrivalTime; T content; Node(T content){ this.content = content; } @Override public String toString(){ return this.content.toString(); } } This restructuring did break some other parts of your code, but not that many. enq now doesn't work like this, so change it to: public void enq(Node toEnq){ toEnq.arrivalTime = this.arrivalTime; arrivalTime++; if (toEnq.content instanceof Cat) { catQ.enq(toEnq); } else { dogQ.enq(toEnq); } } Adding new animals is now simpler, and your queue is actually reusable, you can add anything: myHouse.enq(new Node<Cat>(new Cat("Bella"))); Misc
{ "domain": "codereview.stackexchange", "id": 42971, "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, queue", "url": null }
java, queue Misc fields should be private as to not expose implementation details you could easily get rid of the arrival time by just having one queue, and if deqAny is called, return the first entry, if deqDog or deqCat is called peek until you find the correct animal, then return that. (This would worsen your performance in some corner-cases, see comments.) A better idea would be to move arrivalTime into Animal, because it's a datapoint for animals, not for nodes. Ideally, you would also use some sort of time instead of a counter, because it makes more logical sense. don't shorten words in variable and method names, it makes code harder to read. Eg; printQ, what's a Q? deq? etc your whitespace usage is a bit off (spaces and vertical whitespace) an error node is not a good idea, nor is printing in a queue. just throw an exception, that way the code using your queue can decide how to handle that case. your AnimalHouse doesn't need to know about the implementation details of the queue. So remove the node fields (which aren't used anyways), and instead of passing and returning nodes, pass and return the content instead and create the nodes inside of the queues.
{ "domain": "codereview.stackexchange", "id": 42971, "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, queue", "url": null }
c#, programming-challenge, time-limit-exceeded Title: Kattis challenge, processing string with special characters and conditions Question: I'm new to programming challenges and I'm attempting the following Kattis challenge Sim. This problem is an extension of another Kattis problem - backspace. In that problem, every time we see a character ‘<’, it actually means that the ‘Backspace’ key is pressed and we undo the last character that was just typed. The extension is as follows: Now, pressing a ‘<’ (the ‘Backspace’ key) when the (typing) cursor is at the front of the line does nothing. Now if we see a character ‘[’, it actually means that the ‘Home’ key is pressed and we move the (typing) cursor to the front of the line. Similarly, if we see a character ‘]’, it actually means that the ‘End’ key is pressed and we move the (typing) cursor the back of the line. For all other valid character in the input, it actually means that the corresponding key is pressed, we insert that character at the (typing) cursor position, and advance one position to the right the cursor accordingly. Input The input starts with a line containing just one integer T(1≤T≤10), denoting the number of test cases.Each test case is a line containing the string that was written in the Text Editor Sim (Steven IMproved). The length of the string is at most 1.000.000, and it will only contain lowercase letters from the English alphabet [‘a’…‘z’], digits [‘0’…‘9’], spaces, as well as some of the three special characters: ‘<’, ‘[’, or ‘]’. Output For each test case, output one line containing the final string that is displayed on screen. The test cases are divided in 3 groups where group 1: with at most 1000 bytes string and no '[' group 2: with at most 1000 bytes string with '[' group 3: with at most 1000000 bytes string.
{ "domain": "codereview.stackexchange", "id": 42972, "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#, programming-challenge, time-limit-exceeded", "url": null }
c#, programming-challenge, time-limit-exceeded Given that premise, I made a program in c# to solve it. When the solution is submitted, I pass group 1 and group 2 with no problems, but the very first test case of group 3 returns a Time Limit Exceeded. This is the solution I did: using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace Sim { public class NoMoreTokensException : Exception { } public class Tokenizer { string[] tokens = new string[0]; private int pos; StreamReader reader; public Tokenizer(Stream inStream) { var bs = new BufferedStream(inStream); reader = new StreamReader(bs); } public Tokenizer() : this(Console.OpenStandardInput()) { // Nothing more to do } private string PeekNext() { if (pos < 0) // pos < 0 indicates that there are no more tokens return null; if (pos < tokens.Length) { if (tokens[pos].Length == 0) { ++pos; return PeekNext(); } return tokens[pos]; } string line = reader.ReadLine(); if (line == null) { // There is no more data to read pos = -1; return null; } // Split the line that was read on white space characters tokens = line.Split("dont split omg"); pos = 0; return PeekNext(); } public bool HasNext() { return (PeekNext() != null); } public string Next() { string next = PeekNext(); if (next == null) throw new NoMoreTokensException(); ++pos; return next; } } public class Scanner : Tokenizer {
{ "domain": "codereview.stackexchange", "id": 42972, "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#, programming-challenge, time-limit-exceeded", "url": null }
c#, programming-challenge, time-limit-exceeded public class Scanner : Tokenizer { public int NextInt() { return int.Parse(Next()); } public long NextLong() { return long.Parse(Next()); } public float NextFloat() { return float.Parse(Next()); } public double NextDouble() { return double.Parse(Next()); } } public class BufferedStdoutWriter : StreamWriter { public BufferedStdoutWriter() : base(new BufferedStream(Console.OpenStandardOutput())) { } } class Program { static void Main(string[] args) { List<string> Result = new List<string>(); string craftSentence = ""; string leftSidedSentence = ""; Scanner scan = new Scanner(); int tc = scan.NextInt(); bool foward = true; string input; while (tc != 0) { craftSentence = ""; input = scan.Next(); foreach (char c in input.ToCharArray()) { switch (c) { case '[': foward = false; if (leftSidedSentence != "") { craftSentence = leftSidedSentence + craftSentence; leftSidedSentence = ""; }
{ "domain": "codereview.stackexchange", "id": 42972, "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#, programming-challenge, time-limit-exceeded", "url": null }
c#, programming-challenge, time-limit-exceeded break; case ']': foward = true; if (leftSidedSentence != "") { craftSentence = leftSidedSentence + craftSentence; leftSidedSentence = ""; } break; case '<': if (craftSentence.Length == 0 && foward) { break; } if (foward) { craftSentence = craftSentence.Substring(0, craftSentence.Length - 1); } else if (leftSidedSentence.Length != 0) { leftSidedSentence = leftSidedSentence.Substring(0, leftSidedSentence.Length - 1); } break; default: if (foward) { craftSentence += c; } else { leftSidedSentence += c; } break; } } craftSentence = leftSidedSentence + craftSentence; Result.Add(craftSentence); tc--; } foreach (string r in Result) { Console.WriteLine(r); } } } } Basically what I do:
{ "domain": "codereview.stackexchange", "id": 42972, "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#, programming-challenge, time-limit-exceeded", "url": null }
c#, programming-challenge, time-limit-exceeded Basically what I do: If the char is ']' and there is a text written before with '[' char, concatenate to the finished text to the left. If the char is '<' we check if we are on the right side, or left side and remove the last char from the specific string. After all testcases and chars are processed, print the result. From what I've tried, I generated a random string (containing said special characters) of a million characters and even just pasting that string on the console takes more than 1 second, (but my pc is slow idk if that's the reason, I've used Kattio.cs for the I/O as stated on their c# help site). Regardless of that I bet that my algorithm is no way optimized (I tried with list and it was even slower) so, What should I do to improve this algorithm?
{ "domain": "codereview.stackexchange", "id": 42972, "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#, programming-challenge, time-limit-exceeded", "url": null }
c#, programming-challenge, time-limit-exceeded Answer: I solved this in Node JS -- just barely (0.99s with a TLE of 1s). I appear to be the only person to solve it with Node JS at this time, but SpiderMonkey JS has a 0.32s solution, so there is probably room for optimization. I didn't bother to code it in C#, but I'm pretty sure the algorithm will pass (please let me know if it doesn't). 95% of solving these problems is picking the right data structure, so for difficulty 3 and above, the naive implementation usually won't cut it. Your current solution is quadratic due to +, += (check out Shlemiel the Painter's algorithm if you're not clear why) and Substring (requires copying up to the entire string), but Kattis wants linear. Right off the bat, any solution based on repeatedly manipulating a plain string is pretty much a non-starter. Testing it yourself is very good, but you have to think about worst cases designed to break your solution. If the code is 3 million 'a's followed by 3 million '<'s, or a bunch of prepends on a large string, these are worst-case quadratic situations that random testing won't necessarily produce but are pretty likely to show up in a submission. Based on thinking about these edge cases, I was pretty sure from the start that my data structure would involve lists of chars, or a doubly-linked list that makes it fast to splice characters in and out, which might have been easier than what I did settle on. We're shooting for O(1) for just about all operations to give an overall linear runtime from looping over the input string. I settled on a nested array/list structure like [[[]], []] and an index to point to one of the 2 lists (I'll explain the extra nested list in the zero-th element later). The motivation can be explained with an execution walkthrough below. The plan is to walk the input string character by character. We initially start out in the back list (index 1) with a variable pointing to it: 0 1 [[[]], []] ^ currPart (an index number)
{ "domain": "codereview.stackexchange", "id": 42972, "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#, programming-challenge, time-limit-exceeded", "url": null }
c#, programming-challenge, time-limit-exceeded If we get a backspace character '<' on this empty structure, we do nothing. If we get a plain old alphanumeric character, we append to this list: 0 1 [[[]], ['a']] ^ And another append: 0 1 [[[]], ['a', 'b']] ^ If we receive a delete action '<', we pop the current list if it has elements: 0 1 [[[]], ['a']] ^ If the list was empty, we'd try moving to index 0 and popping from any lists that might have elements there. Now, let's say we get a '[' character. Move the current index to the first list, and things get a bit tricky: 0 1 [[[]], ['a']] ^ What's up with that nested list at position 0? The motivation for it is that if we have more than two '[' actions in the input, we need to prepend each chunk to the front of the result, so "ab[de[fg" should give "fgdeab". Let's process that case, starting from scratch: 0 1 [[[]], []] ^ After "ab[": 0 1 [[[]], ['a', 'b']] ^ After "de[" (notice the new sublist on the back of currPart = 0 triggered by '['): 0 1 [[['d', 'e'], []], ['a', 'b']] ^ After "fg": 0 1 [[['d', 'e'], ['f', 'g']], ['a', 'b']] ^ Once the input string has been visited, the result is built by first reversing parts[0] (a one-time O(n) operation, better than unshifting lists repeatedly on parts[0]): 0 1 [[['f', 'g'], ['d', 'e']], ['a', 'b']] Then flattening and joining: "fgdeab". To summarize the algorithm at a high-level:
{ "domain": "codereview.stackexchange", "id": 42972, "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#, programming-challenge, time-limit-exceeded", "url": null }
c#, programming-challenge, time-limit-exceeded Then flattening and joining: "fgdeab". To summarize the algorithm at a high-level: Keep two sublists and an index representing which inner list (a chunk that will eventually become part of the result) we're currently operating on. If we receive a backspace, pop off the current list unless it's empty, in which case move back to the previous chunk to see if something can be popped there. If we receive a "home" command, go to the first chunk and append an empty inner list to it. If we receive a "end" command, go to the second chunk. If we receive a character and we're on the first of the two chunks due to a previous '[' command, append the character to the last innermost list of that chunk; otherwise we're on the second chunk and we can append the character to its list. When the input string has been totally exhausted, reverse the order of the lists in the first (0th) chunk and flatten and join both lists to produce the result.
{ "domain": "codereview.stackexchange", "id": 42972, "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#, programming-challenge, time-limit-exceeded", "url": null }
javascript Title: Inserting Characters In Certain Positions Of A String Question: I'm currently inserting chars into a string with the given position.Unfortunately at this stage I was unable to create a regular expression that would allow me to achieve the following. Nevertheless, while the code is working, I'm not particularly happy with it, any advice?Thanks. Input Text - A12123456789012 Output Text - A-12/1234/5678-901 const insertAt = (str, sub, pos) => `${str.slice(0, pos)}${sub}${str.slice(pos)}`; function interceptor(value){ if (!value) return ''; let a = null; let b = null; let c = null; let d = null; if (value.length > 0){ a = insertAt(value, '-', 1);} if (value.length > 3){ b = insertAt(a, '/', 4);} if (value.length > 8){ c = insertAt(b, '/', 9);} if (value.length > 13){ d = insertAt(c, '-', 14);} if (d !== null) return d; if (c !== null) return c; if (b !== null) return b; if (a !== null) return a; } Answer: Your variable names of a, b, c, and d aren't particularly descriptive. We can refactor your code to promote scalability (if you want to add more "insertions" in the future), and at the same time, do away with these variables entirely. Instead, let's store your insertions in an array of pairs: const insertions = [ ['-', 1], ['/', 4], ['/', 9], ['-', 14], ]; Now, in your interceptor function, you can iterate over this collection of insertions, and apply each one to the value after you've checked the length against the position: function interceptor(value){ if (!value) return ''; let transformed = value; for (const [char, pos] of insertions) { if (transformed.length <= pos) break; transformed = insertAt(transformed, char, pos); } return transformed; }
{ "domain": "codereview.stackexchange", "id": 42973, "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", "url": null }
javascript return transformed; } I've created the transformed variable in favour of modifying the function's parameter because this is generally frowned upon. This code makes the assumption that the insertions array is sorted by the position (ascending). This assumption lets us exit the loop early (if (transformed.length <= pos) break;) and skip unnecessary checks. If you can't guarantee the sort order of insertions, you can either sort it before the loop, or reshuffle the loop's logic to not break: function interceptor(value){ if (!value) return ''; let transformed = value; for (const [char, pos] of insertions) { if (transformed.length > pos) transformed = insertAt(transformed, char, pos); } return transformed; }
{ "domain": "codereview.stackexchange", "id": 42973, "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", "url": null }
php, regex Title: Regex to capture possible US date entries Question: The Problem I'm relying on plaintext entry to capture dates. End users are urged to enter as MM-DD-YY, but it'll be great to account for as many possibilities. US Date Format is assumed I.e. MM-DD-YYYY, M-D-YYYY,M-D-YY, MM/DD/YYYY, MM/DD/YY, etc.. Current Code //'1 or 2 digits...and then a single hyphen or forward slash..(REPEAT LAST PATTERN) followed by 2 or 4 digits //MOD named group stands for 'Month or Day' /(?<MOD>\d{1,2}[-\/])(?&MOD)(?:\d{4}|\d{2})/ You can run this with some unit tests I created too on https://regex101.com/r/LzoqRa/4 Questions Anything wrong with regex? Any way to simplify regex? Any other edge cases I should be thinking about? Is it worth it to capture MOD and recurse? Or should I just copy the pattern? What's the difference between regex match and recurse (relating to doing this on a previous pattern)? Answer: Your ~(?<MOD>\d{1,2}[-/])(?&MOD)(?:\d{4}|\d{2})~ pattern takes 204 steps on your sample string. The equivalent ~(?:\d{1,2}[-/]){2}(?:\d{4}|\d{2})~ pattern takes 188steps on your sample string. The step count is a loose metric available to help you understand the efficiency of your pattern. The step count indicates that the recursion is doing more work than necessary. But consider the string 5/6-1999, neither of the above patterns are preventing mixed delimiters. Using a capture group on the first delimiter and then matching that specific delimiting character as the second delimiter seems critical if you are not going to pre-sanitize the input string. ~\d{1,2}([-/])\d{1,2}\1(?:\d{4}|\d{2})~ This further reduces the step count to 161, so it not only improves accuracy, it improves efficiency, but at a trivial cost to pattern brevity. What @KIKOSoftware mentions as a comment under the question is also important. Your list of valid formats is not world-ready.
{ "domain": "codereview.stackexchange", "id": 42974, "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, regex", "url": null }
php, regex So, what is your goal here? If you are trying to validate a date looking "kinda" like a date, regex is fine. If you are actually trying to validate a date as a real date, then regex is certainly the wrong tool for the job. To validate the string, use a loose pattern to isolate the components of your string, then feed them to the datetime class for parsing. If the string is parsed as a valid date that matches the sanitized input, then it is a good date. (Demo) function isValidDate(string $date, string $format = 'm/d/Y', string $yearPadding = '19'): bool { $date = preg_replace_callback( '~^(\d+)(\D)(\d+)\2(\d{2}|\d{4})$~', fn($m) => sprintf('%02d/%02d/%d', $m[1], $m[3], str_pad($m[4], 4, $yearPadding, STR_PAD_LEFT)), $date ); // sanitize $d = DateTime::createFromFormat($format, $date); // attempt to parse return $d && $d->format($format) === $date; // check if formatted string is same as sanitized string } To validate the string and return it if it is deemed to be valid, you can modify the above like this: (Demo) function getFormattedDate(string $date, string $format = 'm/d/Y', string $yearPadding = '19'): string { $sanitizedDate = preg_replace_callback( '~^(\d+)(\D)(\d+)\2(\d{2}|\d{4})$~', fn($m) => sprintf('%02d/%02d/%d', $m[1], $m[3], str_pad($m[4], 4, $yearPadding, STR_PAD_LEFT)), $date ); $d = DateTime::createFromFormat($format, $sanitizedDate); if (!$d) { throw new Exception("Could not parse date: $date"); } $formattedDate = $d->format($format); if ($formattedDate !== $sanitizedDate) { throw new Exception("Date not in a desired American format: $date"); } return $date; } foreach ($tests as $test) { try { echo getFormattedDate($test); } catch (Exception $e) { echo $e->getMessage(); } echo "\n"; }
{ "domain": "codereview.stackexchange", "id": 42974, "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, regex", "url": null }
python, python-3.x, google-bigquery Title: Calculates start time and end time of jobs in a dataproc cluster Question: I have the below function get_status_time which calculates the start time and the end time of the spark job which has already completed its run (status could be either fail or pass). It's working but the function is too complex; I want to fine tune it to reduce cognitive complexity. def run_sys_command(cmd): try: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True) s_output, s_err = proc.communicate() s_return = proc.returncode return s_return, s_output, s_err except Exception as e: logger.exception(e,stack_info=True) def get_status_time(app_name): """returns the start and end time of the spark job running on dataproc cluster Args: app_name (str): application name region (str): region name Returns: list: [status_value, start_time, end_time] """ try: end_time = get_today_dt() logger.info(f"the end_time is {end_time}") app_id = app_name cmd = "gcloud dataproc jobs describe {} --region={}".format(app_id, region) (ret, out, err) = run_sys_command(cmd) logger.info(f"return code :{ret} , out :{out} , err :{err}") split_out = out.split("\n") logger.info(f"the value of split_out is {split_out}") logical_bool,status_value, start_time= False,"UNACCESSED","" try: matches = split_out.index(" state: ERROR") print(f"matches are {matches}") except Exception as e: matches = 0
{ "domain": "codereview.stackexchange", "id": 42975, "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, google-bigquery", "url": null }
python, python-3.x, google-bigquery if matches == 0: # Grab status for line in split_out: if logical_bool == False: if "status:" in line: logical_bool = True elif logical_bool == True: status_value = line break else: status_value = "FAILED" # Grab start_time logical_bool = False for line in split_out: if logical_bool == False: if "state: RUNNING" in line: logical_bool = True elif logical_bool == True: start_time = line.replace("stateStartTime:", "").strip(" `'\n") logger.info(f"START TIME AFTER STRIP: {start_time}") start_time = datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%S.%fZ").strftime("%Y-%m-%d %H:%M:%S") break status_value = status_value.replace("state:", "").strip() if status_value == "DONE": status_value = "SUCCEEDED" return [status_value, start_time, end_time] except Exception as e: logger.error(e, stack_info=True, exc_info=True) if __name__ == "__main__": get_status_time('data-pipeline','us-east4')
{ "domain": "codereview.stackexchange", "id": 42975, "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, google-bigquery", "url": null }
python, python-3.x, google-bigquery if __name__ == "__main__": get_status_time('data-pipeline','us-east4') Answer: Factor repeated line-handling logic out to a utility function. Most of the complexity in your current implementation stems from the need to (1) examine a list of lines, (2) find a line that meets some condition, and (3) grab the next line. You need to do that in two places, and both times you try to achieve it within the confines of a regular for-loop using a boolean flag variable to manage state. Any time you find yourself doing something moderately complex more than once, consider writing a function. Even if the function mimicked your current approach, simply factoring out that behavior would be a noteworthy improvement. But I think there's a somewhat more intuitive way to implement the behavior using a while-true loop and Python's next() function: def get_line_after(lines, predicate): it = iter(lines) while True: line = next(it, None) if line is None: return None elif predicate(line): return next(it, None)
{ "domain": "codereview.stackexchange", "id": 42975, "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, google-bigquery", "url": null }
python, python-3.x, google-bigquery Factor grubby parsing details out to utility functions. The other complexity in the current implementation involves the parsing of information from the output of a subprocess call. You can simplify the primary function by shifting those annoying details elsewhere. This strategy doesn't really reduce the amount of code (it increases it slightly), but it increases clarity in two ways, detailed in the ensuing points. The primary function becomes small and clear. It acquires a routine, step-by-step quality. Its job is to delegate tasks to others and to log the results. A few other notes: (1) the region variable was undefined in your code, so I've added it to the function signature here; (2) for brevity here, I've omitted logging calls; (3) restrict try-except handling to the things that can fail beyond your control (parsing code typically does not meet that test); (4) your code is unclear about how to respond to a failure of the subprocess call; and (5) because we don't have your data, we can't run the code, so there might be typos or errors in my code suggestions. def get_status_time(app_name, region): end_time = get_today_dt() cmd = 'gcloud dataproc jobs describe {} --region={}'.format(app_name, region) try: ret, out, err = run_sys_command(cmd) except Exception as e: # Return, raise, or have run_sys_command() log its own exception # and then return data, letting callers decide what to do rather # than requiring them to handle exceptions as well. return lines = out.split('\n') status_value = get_status_value(lines) start_time = get_start_time(lines) return [status_value, start_time, end_time]
{ "domain": "codereview.stackexchange", "id": 42975, "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, google-bigquery", "url": null }
python, python-3.x, google-bigquery return [status_value, start_time, end_time] The utility functions become sharply focused. Although the utility functions are still a bit tedious, at least they are focused on very narrow parts of the problem. They are also easy to unit-test and debug in isolation from the other machinery of the program. Finally, because of their narrow focus, they tend to require the spawning of fewer intermediate variable names: instead, their job is just to return an answer. Under most circumstances, I would not do any logging in these functions. An additional improvement you could make is to convert some of the magic values (eg, the status values and datetime formats) into named constants. def get_status_value(lines): if ' state: ERROR' in lines: return 'FAILED' else: predicate = lambda line: 'status:' in line line = get_line_after(lines, predicate) if line is None: return 'UNACCESSED' else: sval = line.replace('state:', '').strip() return 'SUCCEEDED' if sval == 'DONE' else sval def get_start_time(lines): predicate = lambda line: 'state: RUNNING' in line line = get_line_after(lines, predicate) if line is None: return '' else: line = line.replace('stateStartTime:', "").strip(" `'\n") dt = datetime.strptime(start_time, '%Y-%m-%dT%H:%M:%S.%fZ') return dt.strftime('%Y-%m-%d %H:%M:%S')
{ "domain": "codereview.stackexchange", "id": 42975, "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, google-bigquery", "url": null }
javascript, react.js Title: Elegant defensive checks for nested values Question: I have the following function where data may not exist during the many nested steps to obtain data. To prevent errors, doing the checks as follows. Is there a more elegant way to do this? Please note that Optional chaining is not an option due to the project structure and difficulties in upgrades at this stage. Something like this would have been cleaner but as said Optional chaining is not an option. let Component = configMap[environment][locale] ?.find(config => config['names']?.includes(id))?.config; The logic is to search through the config map and select the Component if it exists within the dev key. Else use the Component within the default key. Example of this configMap is mentioned below. Actual map is much larger and has more keys than just dev. Also looking for feedback if I could write these ifs in a more cleaner way. Appreciate any feedbacks. Thanks. To note, this is a React project. import { configMap } from '../maps'; const get = (locale, environment, id) => { if (!id) return <Fragment />; // id example: '1', '12', '34' let Component = configMap[environment][locale] && configMap[environment][locale] && configMap[environment][locale].find(config => config['names'] && config['names'].includes(id)) && configMap[environment][locale].find(config => config['names'].includes(id)).config; if (!Component) { Component = configMap['default'][locale] && configMap['default'][locale] && configMap['default'][locale].find(config => config['names'] && config['names'].includes(id)) && configMap['default'][locale].find(config => config['names'].includes(id)).config; } if (Component) { return <Component /> } return <Fragment />; }
{ "domain": "codereview.stackexchange", "id": 42976, "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, react.js", "url": null }
javascript, react.js if (Component) { return <Component /> } return <Fragment />; } Just for reference, the configMap will look like this. export const configMap = { 'dev': { 'australia': [ { names: ['12'], config: AndroneDesignComponent, // AndroneDesignComponent is a React component }, { names: ['34'], config: ShreadDesignComponent, // ShreadDesignComponent is a React component }, ], }, 'default': { 'australia': [ { names: ['1'], config: ThymeDesignComponent, // ThymeDesignComponent is a React component }, { names: ['12'], config: DefaultDesignComponent, // DefaultDesignComponent is a React component }, { names: ['34'], config: DefaultDesignComponent, // DefaultDesignComponent is a React component }, ], }, } Answer: One option could be to extract the checking and getting of the component to its own function, such as: import { configMap } from '../maps'; const getComponentFromConfigMap = (env, locale, id) => { const actualEnv = Object.keys(configMap).includes(env) ? env : "default"; const actualLocale = Object.keys(configMap[actualEnv]).includes(locale) ? locale : null; if(!actualLocale) { return null; } const component = configMap[env][locale].find(config => config['names'] && config['names'].includes(id)) || { config: null }; // Get the correct component config, or assign a null value to it return component.config; } const get = (locale, environment, id) => { const Component = getComponentFromConfigMap(environment, locale, id); // This will contain the correct component or null, if no matching component was found if (Component) { return <Component /> } else { return <Fragment />; } }
{ "domain": "codereview.stackexchange", "id": 42976, "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, react.js", "url": null }
javascript, react.js One thing to also note is that checking for the id in the if (!id) return ... statement might give unexpected results, if the id can be something that is falsy (e.g. if someone is trying to get with an id of 0). Further, in the suggestion above, on line const component = configMap[env][locale].find(config => config['names'] && config['names'].includes(id)) the config['names'] && might not be needed, if the object is guaranteed to always have names (even if it's empty) as was the case in the example configMap provided.
{ "domain": "codereview.stackexchange", "id": 42976, "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, react.js", "url": null }
python, beginner, python-3.x Title: A Simple Word Guessing Game Question: I have just finished learning basic-intermediate Python subjects and wanted to test myself. This word-guessing game is one of the first programs I have written. import random def pick_random_word(): word_list = ["python", "c", "java", "swift", "html", "css", "go", "ruby"] random_word = random.choice(word_list) return random_word def make_word_classified(word): classified_list = ["_" for i in word] return classified_list def guess(): word = pick_random_word() classified_word = make_word_classified(word) print(*classified_word) total_attempts = 0 while True: try: answer = input("Guess a letter (Write only one letter)>: ").lower() if len(answer) > 1: raise Exception except Exception: print("Only one letter at a time!") continue total_attempts += 1 if total_attempts >= 7: print("Sorry but you lost!") try_again = input("Wanna play again? (write y or n) >: ") if try_again == 'y': guess() elif try_again == 'n': print("Goodbye!") quit() for i in range(len(word)): if answer == word[i]: classified_word[i] = answer if "".join(classified_word) == word: print("You won!") quit() print(*classified_word, f"\nTotal attempts left: {7 - total_attempts}") if __name__ == "__main__": guess() So, what do you think? How can I make it better? What are my mistakes? Answer: General Remarks
{ "domain": "codereview.stackexchange", "id": 42977, "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, beginner, python-3.x", "url": null }
python, beginner, python-3.x So, what do you think? How can I make it better? What are my mistakes? Answer: General Remarks For the most part, this code is quite good if it's truly one of the first programs you've written. I've seen experienced coders with a University degree do much worse things. Congrats. Avoid: while True:, catch Exception, raise Exception in the future. These should only be used in rare cases, and yours wasn't one. KISS. That try..except block where you raise and catch an exception is just too complex for what can simply be achieved with an if statement. Consider the control flow. There's a couple of bugs that I found because some of the conditions were incomplete. I've annotated and fixed some of them in the line-by-line review, and will put them rest as "exercises" at the end. Avoid the use of quit() (or even sys.exit()) and opt for an early return instead. Personal Remarks and Hints Consider adopting type hinting. A small program like this is ideal to explore Python type hinting, and tools such as mypy can make your life a lot easier once you get the hang of it. I would've liked to see some docstrings in your module and functions. Variable names and functions names were okay for the most part, although there's room for improvement. Always make them indicative of the variable/function's purpose, and avoid confusion. Consider the visibility of your functions, and mark functions that should not be visible outside of your module as "private" by prefixing them with an underscore. Although unnecessary for this code, it's good practice for the future. Line-by-Line Review Without further ado, here's a line-by-line review with some inline comments and personal suggestions for improvement I've made while reading your code. import random # EXERCISES: # - What if I win, but I want to play another round? # - What happens if I guess the same character twice? What *should* happen? # Maybe it's already okay.
{ "domain": "codereview.stackexchange", "id": 42977, "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, beginner, python-3.x", "url": null }
python, beginner, python-3.x # COMMENT: Putting this list in the `pick_random_word` function will constantly # reconstruct the list, which is redundant. Instead, moving it to the global # scope will only construct it once. # NOTE: Putting variables into the global scope is also considered bad # practice, but in this simple case there's not a lot wrong with it. There's # other options that I won't go into detail on. # COMMENT: You removed "javascript" because @Gloweye correctly pointed out a # bug in your program. We'll instead fix this bug here. _WORD_LIST = [ "python", "c", "java", "swift", "html", "css", "go", "ruby", "javascript"] # COMMENT: Magic constants are a bad practice to have in your source code. I've # extracted the maximum attempts to a global variable, so if you want to # provide more attempts at a later date, you just have to change this, and not # search for the number in the code. _MAX_FAILED_ATTEMPTS = 7 # COMMENT: I've prefixed all function definitions with an underscore. This is # mostly just a convention to denote names that should be kept internal. In # case of modules, this signifies a user of the module that this is not a # function they should be concerned with. In your case, this is probably # redundant, but it's good practice for the future. def _pick_random_word(): # COMMENT: Don't assign and immediately return, instead, return without # assignment. This makes your code clearer. return random.choice(_WORD_LIST) def _make_word_classified(word): # COMMENT: Again, immediately return instead of assigning to a variable # first. Secondly, lists can be "multiplied". This replicates the contents, # just like your list comprehension did previously. # Note: Mind the brackets so it's a list, not a string. Strings can be # multiplied too, but are immutable so won't work for the remainder of the # code. return ["_"] * len(word) # return classified_list
{ "domain": "codereview.stackexchange", "id": 42977, "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, beginner, python-3.x", "url": null }
python, beginner, python-3.x # COMMENT: A better name would be in order here. Something along the lines of # `play_guessing_game` would be better, but still not ideal. `guess` feels like # the wrong name to me. def guess(): # COMMENT: Confusing variable names are one of my pet peeves, so I changed # `word` to `target_word`. This way, when writing the code, you won't get # confused. target_word = _pick_random_word() classified_word = _make_word_classified(target_word) print(*classified_word) # COMMENT: Let's count the how many attempts are left, since that's what # we use more often: In printing as well as (now) the condition of the loop attempts_left = _MAX_FAILED_ATTEMPTS
{ "domain": "codereview.stackexchange", "id": 42977, "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, beginner, python-3.x", "url": null }
python, beginner, python-3.x # COMMENT: I don't like `while True:`, unless it's really necessary. # I've changed it to iterate with a condition on the number of attempts # instead. This will also simplify our loop body. # COMMENT: We could simplify this to `while attempts_left` and use the fact # that 0 is equivalent to `False`, but this is more explicit. while attempts_left > 0: # COMMENT: The `try..except` block is over-engineered, it could've # been done with a simple `if` statement. answer = input("Guess a letter (Write only one letter)>: ").lower() # COMMENT: What happens if I don't enter anything? Should it really be # counted as an attempt? Thus I check if there's exactly one character. if len(answer) != 1: print("Exactly one letter is expected!") # COMMENT: I like the use of `continue` instead of an `else` block. # Both are viable, but for a large `else` body it gets hard on the # eyes. Well done. continue # COMMENT: Before I forget: You raised and caught `Exception`. In the # future, create your own custom exceptions instead, or use a specific # exception that's already provided by Python. `Exception` is the # superclass of almost all exceptions in Python, and by catching # exceptions, you would've suppressed different errors as well, such # as `IndexError`, `KeyError`, `AttributeError`, `TypeError`, ... # COMMENT: We'll only increment the attempt counter on mistakes, so # that words of arbitrary length are possible. # total_attempts += 1
{ "domain": "codereview.stackexchange", "id": 42977, "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, beginner, python-3.x", "url": null }
python, beginner, python-3.x # COMMENT: We don't have to check this anymore, it's already checked # in the loop condition. Instead. we'll move the handling of running # out of attempts to after the loop. # if total_attempts >= _MAX_ATTEMPTS: # print("Sorry but you lost!") # try_again = input("Wanna play again? (write y or n) >: ") # if try_again == 'y': # guess() # elif try_again == 'n': # print("Goodbye!") # quit() attempt_correct = False # COMMENT: Use enumerate(word) rather than range(len(word)) to get both # the value and the index. for char_idx, target_char in enumerate(target_word): # I've reindented this code to be 4 spaces rather than 8. New # blocks should always have 4 spaces. if answer == target_char: classified_word[char_idx] = answer attempt_correct = True # We still need to decrement the attempt counter if the attempt was # incorrect. This is why we maintain a boolean and set it to True only # if the attempt is correct. if not attempt_correct: attempts_left -= 1
{ "domain": "codereview.stackexchange", "id": 42977, "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, beginner, python-3.x", "url": null }
python, beginner, python-3.x # COMMENT: Let's move this out of that loop, so we only compare the # words once, rather than every time we access a character. # COMMENT: Instead of turning the classified word into a string, let's # instead check whether it still contains an underscore to check if # we're done. This is more elegant. if "_" not in classified_word: print("You won!") # COMMENT: Instead of calling `quit()`, we'll return. I'm # `quit()` is not really an elegant way to exit a program, # and is not necessary here. Returning early will simply # break out of the function (and thus also the loop) and # thus stop the game. # COMMENT: Exercise for you: What if I wanted to continue # to play another round? return # COMMENT: You could move this to the top of the loop, and do away # with the initial print before the loop, and then you'd have the # "Total attempts left" from the start. print(*classified_word, f"\nTotal attempts left: {attempts_left}")
{ "domain": "codereview.stackexchange", "id": 42977, "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, beginner, python-3.x", "url": null }
python, beginner, python-3.x # If we reach the end of this loop, we've lost, since if we've won, # we'd already have returned from the function. print("Sorry but you lost!") try_again = input("Wanna play again? (write y or n) >: ") # COMMENT: Python makes no distinction between strings and characters, so # single quotes and double quotes are equivalent. "y" and "n" here were # single quotes while the rest of your strings are double quotes. # Be consistent. Choose one and stick with it. if try_again == "y": # Okay, but what if I play millions of times? It's likely never going # to be an issue, but if I play millions of times, this will cause a # stack overflow because of the recursion. Prefer iteration (with a # `for` or `while` loop) instead. Python does not have tail-call # optimization: https://stackoverflow.com/q/13591970/10973209 guess() # We still need the `else` to print the goodbye, otherwise it would print # goodbye multiple times if we recursively call ourselves. I've changed it # to `else` so that it prints goodbye even if I didn't say 'n'. # This would previously cause a bug when it was still in the loop. If I # entered 'a', it would just continue the game and I'd have an infinite # number of attempts. else: print("Goodbye!") # Now that this is moved outside of the loop, we don't need to return # or quit anymore, the function will just end. if __name__ == "__main__": guess() Exercises There's still room for improvement, and I'll give you a few pointers on where to start:
{ "domain": "codereview.stackexchange", "id": 42977, "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, beginner, python-3.x", "url": null }
python, beginner, python-3.x Exercises There's still room for improvement, and I'll give you a few pointers on where to start: Consider the case where I'm forgetful, and I've typed the same character twice. How should this be handled? How is this currently handled? Is that okay? I've won the game. Now what? I'd like to play again, please and thank you. I already mentioned in the code the possibility of stack overflow because Python doesn't perform so-called tail-call optimisation. I doubt you'll ever run into issues with this program because of this, but it's still a good exercise to 1) look into what tail-call optimisation is and why your program could crash without it, and 2) fix the program so that it wouldn't have that problem.
{ "domain": "codereview.stackexchange", "id": 42977, "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, beginner, python-3.x", "url": null }
c++, matrix, c++17, iterator, overloading Title: Matrix implementation Question: I am trying to implement an optimal and fast running matrix in C++. I need some review of the code and ideas on how to improve the code quality if it shall be. class Matrix { // Some static assertions and useful types static_assert(std::is_arithmetic_v<T>, "Matrix template parameter type must be arithmetic"); using DataType = std::vector<T>; // Default constructors public: Matrix() : mCols(0), mRows(0), mData(0) { }; Matrix(const Matrix &other) = default; Matrix(Matrix &&other) noexcept = default; Matrix &operator=(const Matrix &other) = default; Matrix &operator=(Matrix &&other) noexcept = default; // Parameterized constructors public: Matrix(std::size_t cols, std::size_t rows) : mCols(cols), mRows(rows) { mData.resize(cols * rows); } Matrix(std::size_t cols, std::size_t rows, const DataType &data) { if (rows * cols != data.size()) { throw std::invalid_argument("Invalid matrix mData"); } mCols = cols; mRows = rows; mData = data; } Matrix(std::size_t cols, std::size_t rows, DataType &&data) { if (rows * cols != data.size()) { throw std::invalid_argument("Invalid matrix mData"); } mCols = cols; mRows = rows; mData = std::move(data); }
{ "domain": "codereview.stackexchange", "id": 42978, "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++, matrix, c++17, iterator, overloading", "url": null }
c++, matrix, c++17, iterator, overloading // Setters public: void set(std::size_t rows, std::size_t cols, const DataType &data) { if (rows * cols != data.size()) { throw std::invalid_argument("Invalid vector data"); } mRows = rows; mCols = cols; mData.resize(rows * cols); std::copy(data.begin(), data.end(), mData.begin()); } void set(std::size_t rows, std::size_t cols, DataType &&data) { if (rows * cols != data.size()) { throw std::invalid_argument("Invalid vector data"); } mRows = rows; mCols = cols; mData.resize(rows * cols); std::move(data.begin(), data.end(), mData.begin()); } void set(std::size_t rows, std::size_t cols) { mData.resize(rows * cols); } void set(const DataType &data) { if (mRows * mCols != data.size()) { throw std::invalid_argument("Invalid vector data"); } std::copy(data.begin(), data.end(), mData.begin()); } void set(DataType &&data) { if (mRows * mCols != data.size()) { throw std::invalid_argument("Invalid vector data"); } std::move(data.begin(), data.end(), mData.begin()); } // Getters public: auto cols() const { return mCols; } auto rows() const { return mRows; } const DataType &data() const { return mData; }
{ "domain": "codereview.stackexchange", "id": 42978, "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++, matrix, c++17, iterator, overloading", "url": null }
c++, matrix, c++17, iterator, overloading const DataType &data() const { return mData; } // Operator overloads public: Matrix operator+(const Matrix &rhs) const { if (mCols != rhs.mCols || mRows != rhs.mRows) { throw std::invalid_argument("Invalid vector mData, you may add matrices with same dimensions only"); } Matrix result(mCols, mRows); std::transform(mData.begin(), mData.end(), rhs.mData.begin(), result.mData.begin(), std::plus<>()); return result; } Matrix operator+(Matrix &&rhs) const { if (mCols != rhs.mCols || mRows != rhs.mRows) { throw std::invalid_argument("Invalid vector mData, you may add matrices with same dimensions only"); } Matrix result(mCols, mRows); std::transform(mData.begin(), mData.end(), std::make_move_iterator(rhs.mData.begin()), result.mData.begin(), std::plus<>()); return result; } Matrix operator-(const Matrix &rhs) const { if (mCols != rhs.mCols || mRows != rhs.mRows) { throw std::invalid_argument("Invalid vector mData, you may sub matrices with same dimensions only"); } Matrix result(mCols, mRows); std::transform(mData.begin(), mData.end(), rhs.mData.begin(), result.mData.begin(), std::minus<>()); return result; } Matrix operator-(Matrix &&rhs) const { if (mCols != rhs.mCols || mRows != rhs.mRows) { throw std::invalid_argument("Invalid vector mData, you may sub matrices with same dimensions only"); } Matrix result(mCols, mRows); std::transform(mData.begin(), mData.end(), std::make_move_iterator(rhs.mData.begin()), result.begin(), std::minus<>()); return result; }
{ "domain": "codereview.stackexchange", "id": 42978, "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++, matrix, c++17, iterator, overloading", "url": null }
c++, matrix, c++17, iterator, overloading Matrix &operator+=(const Matrix &rhs) { if (mCols != rhs.mCols || mRows != rhs.mRows) { throw std::invalid_argument("Invalid vector mData, you may add matrices with same dimensions only"); } std::transform(mData.begin(), mData.end(), rhs.mData.begin(), mData.begin(), std::plus<>()); return *this; } Matrix &operator+=(Matrix &&rhs) { if (mCols != rhs.mCols || mRows != rhs.mRows) { throw std::invalid_argument("Invalid vector mData, you may add matrices with same dimensions only"); } std::transform(mData.begin(), mData.end(), std::make_move_iterator(rhs.mData.begin()), mData.begin(), std::plus<>()); return *this; } Matrix &operator-=(const Matrix &rhs) { if (mCols != rhs.mCols || mRows != rhs.mRows) { throw std::invalid_argument("Invalid vector mData, you may add matrices with same dimensions only"); } std::transform(mData.begin(), mData.end(), rhs.mData.begin(), mData.begin(), std::minus<>()); return *this; } Matrix &operator-=(Matrix &&rhs) { if (mCols != rhs.mCols || mRows != rhs.mRows) { throw std::invalid_argument("Invalid vector mData, you may add matrices with same dimensions only"); } std::transform(mData.begin(), mData.end(), std::make_move_iterator(rhs.mData.begin()), mData.begin(), std::minus<>()); return *this; } bool operator==(const Matrix &rhs) const { return mCols == rhs.mCols && mRows == rhs.mRows && std::equal(mData.begin(), mData.end(), rhs.mData.begin(), rhs.mData.end()); } bool operator!=(const Matrix &rhs) const { return !(*this == rhs); }
{ "domain": "codereview.stackexchange", "id": 42978, "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++, matrix, c++17, iterator, overloading", "url": null }
c++, matrix, c++17, iterator, overloading friend std::ostream &operator<<(std::ostream &os, const Matrix &matrix) { for (int i = 0; i < matrix.mCols; ++i) { for (int j = 0; j < matrix.mRows; ++j) { os << matrix.mData[i * matrix.mCols + j] << " "; } os << "\n"; } return os; } protected: std::size_t mCols; std::size_t mRows; std::vector<T> mData; }; I'll add determinant and matrix multiplication operators too, but that will come after reviewing this part. Answer: for Matrix() : mCols(0), mRows(0), mData(0) { }; semicolon should be removed as useless. for Matrix(std::size_t cols, std::size_t rows) : mCols(cols), mRows(rows) { mData.resize(cols * rows); } You can use member list initialization too for vector: Matrix(std::size_t cols, std::size_t rows) : mCols(cols), mRows(rows), mData(cols * rows) {} for void set(std::size_t rows, std::size_t cols) { mData.resize(rows * cols); } it is wrong, as changing row/columns change internal layout, so for example element of 2nd row, 2nd column won't be there anymore. resize seems to be a better name if you keep that function. for arithmetic operators Matrix operator+(const Matrix &rhs) const, you forget when lhs is a rvalue, so either add overload with this qualifier Matrix operator+(const Matrix &rhs) && or make all overload as (friend) free functions. You might implement operator + with operator +=. std::vector already has an operator == so bool operator==(const Matrix &rhs) const { return mCols == rhs.mCols && mRows == rhs.mRows && std::equal(mData.begin(), mData.end(), rhs.mData.begin(), rhs.mData.end()); } can be simplified to bool operator==(const Matrix &rhs) const { return mCols == rhs.mCols && mRows == rhs.mRows && mData == rhs.mData; }
{ "domain": "codereview.stackexchange", "id": 42978, "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++, matrix, c++17, iterator, overloading", "url": null }
java, comparative-review, formatting, integer Title: Format an integer with space as thousand separator Question: I need to format a number with space as thousand separator in my Java code for Android. How can these functions be improved? What are the pros and cons to the first recursive method? What are the pros and cons to the second substring method? Is there maybe an even better and easier way to solve the problem? Java code for the recursive variant: /** * Format a (int) Number with Space as Thousand Separator * Recursive variant * @param number the Number to Format * @return String the Formatted Number * @since 1.0 */ public static String intToThousandSpacedStringOS(int number) { boolean positive = true; String t = ""; if (number < 0) { positive = false; number = -number; } if (number > 999) { t = intToThousandSpacedStringOS(number / 1000) + " "; do { number = number % 1000; } while (number > 999); t += String.format("%03d", number); } else { t = "" + number; } return positive ? t : "-" + t; } Java code for the substring variant: /** * Format a (int) Number with Space as Thousand Separator * SubString variant * @param number the Number to Format * @return String the Formatted Number * @since 1.0 */ public static String intToThousandSpacedStringOS(int number) { boolean positive = true; String t; String r = ""; int i = 1; if (number < 0) { positive = false; number = -number; } t = "" + number; while (t.length() > 3 * i) { r = t.substring(t.length() - 3 * i > 3 ? t.length() - 3 * (i + 1) : 0, t.length() - 3 * i) + " " + r; i++; } r += t.substring(t.length() - 3 > 0 ? t.length() - 3 : 0, t.length()); return positive ? r : "-" + r; }
{ "domain": "codereview.stackexchange", "id": 42979, "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, comparative-review, formatting, integer", "url": null }
java, comparative-review, formatting, integer return positive ? r : "-" + r; } Answer: I will not discuss if it's re-inventing some wheel, but comment on the two code versions given. Recursive version The loop do { number = number % 1000; } while (number > 999); is nonsense. number % 1000 can never be > 999, so number = number % 1000; without the loop does exactly the same. In the "loop", re-assigning a new value to the method call parameter number is considered bad style. You should introduce a new variable, e.g. int remainder = number % 1000;. You can avoid the error-prone handling of the positive flag by utilising recursion as well: if (number < 0) { return "-" + intToThousandSpacedStringOS(-number); } You declare your variables very early, and later change their values from an (often useless) initial value to something useful, e.g. String t = ""; Better declare your variables in the exact same line where you know their value. Or at least, don't assign an initial value, then the compiler gives you an error message if in some execution path you forgot to assign a useful value. To sum it up, my recursive version would read public static String intToThousandSpacedStringOS(int number) { if (number < 0) { return "-" + intToThousandSpacedStringOS(-number); } else if (number > 999) { return intToThousandSpacedStringOS(number / 1000) + String.format(" %03d", number % 1000); // note the space in the format string. } else { return String.format("%d", number); } } Iterative version Reading and understanding this version is a challenge, and that's a red flag. Don't expect any fellow programmer (and your future self next month) to understand what a line like r = t.substring(t.length() - 3 * i > 3 ? t.length() - 3 * (i + 1) : 0, t.length() - 3 * i) + " " + r;
{ "domain": "codereview.stackexchange", "id": 42979, "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, comparative-review, formatting, integer", "url": null }
java, comparative-review, formatting, integer does. I guess you cut a chunk out of the original decimal string and prepend that, together with a space, to the result string. Then, at least introduce two variables like int chunkStart = t.length() - 3 * i > 3 ? t.length() - 3 * (i + 1) : 0; int chunkEnd = t.length() - 3 * i; r = t.substring(chunkStart, chunkEnd) + " " + r; With the ternary-operator conditional, you probably want to avoid a negative chunkStart. I'd write int chunkStart = Math.max(t.length() - 3 * (i + 1), 0); int chunkEnd = t.length() - 3 * i; r = t.substring(chunkStart, chunkEnd) + " " + r; or int chunkStart = t.length() - 3 * (i + 1); if (chunkStart < 0) chunkStart = 0; int chunkEnd = t.length() - 3 * i; r = t.substring(chunkStart, chunkEnd) + " " + r; You seem to love while loops. Typically, for loops are much more readable, as they combine all loop aspects in a single line - your while loop spreads its aspects over half of the method length: The initial value is found in line 12: int i = 1;. The condition is in line 20: while (t.length() > 3 * i) {. The updating is in line 22: i++;. The variable i that you use in the loop is only loosely related to the values you need inside the loop. You want to iterate a position inside the string backwards from the end, in 3-character steps. A straightforward loop would be e.g. for (int chunkEnd = t.length() - 3; chunkEnd > 0; chunkEnd -= 3) { ... }
{ "domain": "codereview.stackexchange", "id": 42979, "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, comparative-review, formatting, integer", "url": null }
python, beginner, python-3.x, object-oriented, rock-paper-scissors Title: Rock, Paper, Scissors game in Python with OOP Question: I am still practising object oriented programming and I decided to do the rock-paper-scissors game as a project. I listen to constructive criticism to improve the program. #!/usr/bin/env python3 # Rock, Paper, Scissors from os import system from random import randint from sys import exit class rock_paper_scissors: def __init__(self): self.choices = "rock", "paper", "scissors" self.player_wins = 0 self.computer_wins = 0 def _spacer_size(self, length=65): return '-' * length def _player_move(self): while True: try: option = int(input('Choose an option between Rock (1), Paper (2), Scissors (3): ')) if 1 <= option <= 3: break else: print('You can only enter a number between 1 and 3.') except ValueError: print('The value entered is invalid. You can only enter numeric values.') return option def _computer_move(self): return randint(1,3) def _check_winner(self): if self.player_wins == self.computer_wins: return 'Tie.' elif self.player_wins > self.computer_wins: return 'You won the set.' else: return 'Computer wins the set.' def _play(self): times = int(input("How many times do you wish to play?: ")) for i in range(times): player = self._player_move() computer = self._computer_move() print(f"You chose {self.choices[player-1]}.") print(f"The computer chose {self.choices[computer-1]}.")
{ "domain": "codereview.stackexchange", "id": 42980, "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, beginner, python-3.x, object-oriented, rock-paper-scissors", "url": null }
python, beginner, python-3.x, object-oriented, rock-paper-scissors if player == computer: print('Tie.\n') print(self._spacer_size(), '\n') elif (player-computer) % 3 == 1: print('You won.\n') print(self._spacer_size(), '\n') self.player_wins += 1 else: print('You lost.\n') print(self._spacer_size(), '\n') self.computer_wins += 1 print(self._check_winner()) input("Press a key to return to the main menu...") system("CLS") self.main() def main(self, length=95): while True: try: print('-' * length, '\n') print(''' █▀█ █▀█ █▀▀ █▄▀ ░   █▀█ ▄▀█ █▀█ █▀▀ █▀█ ░   █▀ █▀▀ █ █▀ █▀ █▀█ █▀█ █▀ █▀▄ █▄█ █▄▄ █░█ █   █▀▀ █▀█ █▀▀ ██▄ █▀▄ █   ▄█ █▄▄ █ ▄█ ▄█ █▄█ █▀▄ ▄█ '''.center(10)) print('-' * length, '\n') print('1. Play'.center(length)) print('2. Instructions'.center(length)) print('3. Exit'.center(length)) choice = int(input('\nEnter an option: ')) except ValueError: print('The value entered is invalid. You can only enter numeric values.')
{ "domain": "codereview.stackexchange", "id": 42980, "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, beginner, python-3.x, object-oriented, rock-paper-scissors", "url": null }
python, beginner, python-3.x, object-oriented, rock-paper-scissors if choice == 1: system("CLS") self._play() break elif choice == 2: system("CLS") print(" Instructions for Rock, Paper, Scissors: ") print("- Rock wins over scissors (because rock smashes scissors).") print("- Scissors wins over paper (because scissors cut paper).") print("- Paper wins over rock (because paper covers rock).") print("- If both players show the same sign, it's a tie.\n") input("Press a key to return to the main menu...") system("CLS") elif choice == 3: exit() else: print("You have entered a number that isn't in the list.") system("CLS") if __name__ == '__main__': game = rock_paper_scissors() game.main() Answer: One suggestion would be to use an enum instead of a tuple. #!/usr/bin/env python3 # Rock, Paper, Scissors from enum import Enum from os import system from random import randint from sys import exit class Hand(Enum): ROCK = 1 PAPER = 2 SCISSORS = 3 def __str__(self): return self.name.title() class rock_paper_scissors: def __init__(self): # self.choices = "rock", "paper", "scissors" self.player_wins = 0 self.computer_wins = 0 ... for i in range(times): player = self._player_move() computer = self._computer_move() print(f'{player} {computer} ') # print(f"You chose {self.choices[player-1]}.") print(f'You chose {Hand(player)}') # print(f"The computer chose {self.choices[computer-1]}.") print(f'The computer chose {Hand(computer)}')
{ "domain": "codereview.stackexchange", "id": 42980, "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, beginner, python-3.x, object-oriented, rock-paper-scissors", "url": null }
python, beginner, python-3.x, object-oriented, rock-paper-scissors In your use case, it doesn't do much, besides dump the use of math related to the tuple position, but its cleaner and makes more sense this way. Other than that enums are easy to use and offer a lot of functionality. for instance x = Hand.ROCK print(x) print(x.name) print(x.value) print(x is Hand.ROCK) print(x is Hand.PAPER) you have the ability to assign a value, string, easy comparisons. enums are easy to iterate through as well. for hand, value in Hand.__members__.items(): print(f'{hand} => {value}') There's a lot more and would recommend looking into them, if you were't already familiar. suggestion #2: another thing you could consider, and honestly this is a personal preference, is to use a single print statement for multiple lines. In my opinion, it looks cleaner and is easier to read. print(f""" Instructions for Rock, Paper, Scissors: - Rock wins over scissors (because rock smashes scissors). - Scissors wins over paper (because scissors cut paper). - Paper wins over rock (because paper covers rock). - If both players show the same sign, it's a tie.\n Press a key to return to the main menu... """.center(length)) suggestion #3: your system clear is nice, it keeps the terminal, game screen decluttered. However, system('cls') only works on windows. I am using Linux. So if you want to make your game cross-platform you need to be on the lookout for those issues. create a new function that will check the system platform and then execute the appropriate command. def clearScreen(self): if platform == "linux" or platform == "linux2": system('clear') # linu elif platform == "darwin": pass # OS X elif platform == "win32": system('cls') # Windows...
{ "domain": "codereview.stackexchange", "id": 42980, "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, beginner, python-3.x, object-oriented, rock-paper-scissors", "url": null }
python, beginner, python-3.x, object-oriented, rock-paper-scissors and just call this function each time you want to clear the screen. Actually, what was I thinking. Just check once as to what your system is in your constructor. This way you set a constant that can be used for your system call, without needing to check every time. class rock_paper_scissors: def __init__(self): if platform == "linux" or platform == "linux2": self.clear = 'clear' # linu elif platform == "darwin": pass # OS X elif platform == "win32": self.clear = 'cls' # Windows... self.player_wins = 0 self.computer_wins = 0
{ "domain": "codereview.stackexchange", "id": 42980, "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, beginner, python-3.x, object-oriented, rock-paper-scissors", "url": null }
vba Title: VBEMenuButton Class Question: The VBEMenuButton class simplifies creating menu items in the VBE Editor. When Excel opens, the Auto_Open() routine in my Personal Macros book is triggered and my commands are added to the VBE Editor Menus. The example code adds two menu items to the Menu toolbar Tools popup menu: "Backup ActiveWorkbook" and "Update ActiveWorkbook TableDefs". VBEInit: Standard Module Public Sub Auto_Open() Const MenuName As String = "Menu Bar" Const SubMenuName As String = "Tools" Static VBEButtons As Collection VBEMenuButton.DeleteAllVBEMenuButtons Set VBEButtons = New Collection VBEButtons.Add VBEMenuButton.Create(MenuName:=MenuName, SubMenuName:=SubMenuName, BeginGroup:=True, _ Caption:="Backup ActiveWorkbook", wb:=ThisWorkbook, OnAction:="ActiveWorkbookBackUp") VBEButtons.Add VBEMenuButton.Create(MenuName, SubMenuName, False, "Update ActiveWorkbook TableDefs", ThisWorkbook, "UpdateActiveWorkbookTableDefs") End Sub Public Sub Auto_Close() VBEMenuButton.DeleteAllVBEMenuButtons End Sub VBEMenuButton: Class VERSION 1.0 CLASS BEGIN MultiUse = -1 'True END Attribute VB_Name = "VBEMenuButton" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Option Explicit Private Const TagName = "My VBEMenuButton" Public Button As CommandBarControl Public WithEvents EventHandler As VBIDE.CommandBarEvents Attribute EventHandler.VB_VarHelpID = -1
{ "domain": "codereview.stackexchange", "id": 42981, "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": "vba", "url": null }
vba Public Property Get Create(MenuName As String, SubMenuName As String, BeginGroup As Boolean, Caption As String, wb As Workbook, OnAction As String) As VBEMenuButton With New VBEMenuButton Set .Button = Application.VBE.CommandBars(MenuName).Controls(SubMenuName).Controls.Add With .Button .Caption = Caption .BeginGroup = BeginGroup .OnAction = "'" & wb.Name & "'!" & OnAction .Tag = TagName End With Set .EventHandler = Application.VBE.Events.CommandBarEvents(.Button) Set Create = .Self End With End Property Public Property Get Self() As VBEMenuButton Set Self = Me End Property Private Sub EventHandler_Click(ByVal CommandBarControl As Object, Handled As Boolean, CancelDefault As Boolean) On Error Resume Next Application.Run CommandBarControl.OnAction Handled = True CancelDefault = True On Error GoTo 0 End Sub Sub DeleteAllVBEMenuButtons() Dim Ctrl As Office.CommandBarControl Set Ctrl = Application.VBE.CommandBars.FindControl(Tag:=TagName) Do Until Ctrl Is Nothing Ctrl.Delete Set Ctrl = Application.VBE.CommandBars.FindControl(Tag:=TagName) Loop End Sub My code was based off of Pearson Software Consulting: Creating Menu Items In The VBA Editor. Answer: Public Sub Auto_Close() VBEMenuButton.DeleteAllVBEMenuButtons End Sub This is a bit weird IMO; why should a button have the power to delete other buttons? It basically invalidates other instances of the button class without them knowing. What would happen if I try to access VBEButtons(1).Button after the control it refers to has been deleted? You protect yourself from this scenario with Static: Public Sub Auto_Open() Static VBEButtons As Collection VBEMenuButton.DeleteAllVBEMenuButtons Set VBEButtons = New Collection VBEButtons.Add VBEMenuButton.Create(...
{ "domain": "codereview.stackexchange", "id": 42981, "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": "vba", "url": null }
vba ... basically scoping the VBEMenuButton to a single procedure to prevent unexpected usage. However this scoping is only a convention for consumers of your class. Conventions are not enforced - and what if you refactor that VBEMenuButtons collection into module scope (perhaps there is some cleanup to do of other resources that necessitates access to the button objects), then any code could access it when it is in an invalid orphaned state following a call to DeleteAllVBEMenuButtons. Long story short, a method of a member of a collection should not be able to modify the state of the entire collection (as you have currently). That should be done by a function taking the collection as a parameter, or in OOP, a custom collection class which can clean up after itself - perhaps in the Terminate event - and which contains a set of Buttons to handle the click events.* DeleteAllVBEMenuButtons would then become a normal member function of a VBEMenuButtonCollection class which loops through the internal collection of button event handlers, deleting the corresponding control (and removing the need for a tag I guess) *Speaking of handling events, apparently you should use the Click event of the CommandBarButton class not the CommandBarEvents class because: [...] Office 2010 64-bit doesn't support CommandBarEvents (it crashes if used). Parameters Public Property Get Create(MenuName As String, SubMenuName As String, BeginGroup As Boolean, Caption As String, wb As Workbook, OnAction As String) Private Sub EventHandler_Click(ByVal CommandBarControl As Object, Handled As Boolean, CancelDefault As Boolean) should probably become (more explicit): Public Property Get Create(ByVal MenuName As String, SubMenuName As String, ByVal BeginGroup As Boolean, ByVal Caption As String, ByVal wb As Workbook, ByVal OnAction As String) Private Sub EventHandler_Click(ByVal CommandBarControl As Object, ByRef outHandled As Boolean, ByRef outCancelDefault As Boolean)
{ "domain": "codereview.stackexchange", "id": 42981, "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": "vba", "url": null }
mysql, shell Title: Shell script to backup db from mysql whether the mysql server is running in docker Question: I have written this shell script to backup MySQL database to disk. It works fine but I am not well proficient in shell scripting. So what do you think can it be improved? #!/bin/bash #For taking backup APPEND_CLI=$3 DIR=/media/storage/backup/db_backup/ DATESTAMP=$(date +%d-%m-%y-%H-%M) DB_USER=backup DB_PORT=$2 DB_PASS='readonly' HOST=$1 if [[ `id -u` != 0 ]]; then echo "Must be root to run script" exit fi if test -z "$HOST" then echo "HOST not passed." exit 1 fi if test -z "$DB_PORT" then echo "PORT not passed." exit 1 fi # remove backups older than $DAYS_KEEP DAYS_KEEP=7 find ${DIR}* -mtime +$DAYS_KEEP -exec rm -f {} \; 2> /dev/null # create backups securely umask 006 # list MySQL databases and dump each DB_LIST=`$APPEND_CLI mysql -h $HOST -u $DB_USER -p"$DB_PASS" -e'show databases;'` echo "Listing databases" echo ${DB_LIST##Database} DB_LIST=${DB_LIST##Database} for DB in $DB_LIST; do if [[ "${DB}" == "performance_schema" ]] then echo "Skipping database ${DB}." continue fi FILENAME=${DIR}${DB}-${DATESTAMP}.msql.${DB_PORT}.gz echo "Initiating backup of $DB for ${HOST} on port ${DB_PORT}" $APPEND_CLI mysqldump -h $HOST -P $DB_PORT -u $DB_USER -p"$DB_PASS" $DB --single-transaction | gzip > $FILENAME echo "Done backing up ${FILENAME}" done Answer: Please use lower-case for Bash variables - upper-case is normally used for environment variables that communicate with child processes. if [[ `id -u` != 0 ]]; then echo "Must be root to run script" exit fi Error messages should go to the standard error stream (>&2). And I think we should be exiting with a failure status in this case (since we didn't perform the requested backup). We can make life easier for ourselves with a short function to print an error message and exit with failure. That looks like die() { echo >&2 "$@" exit 1 }
{ "domain": "codereview.stackexchange", "id": 42982, "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": "mysql, shell", "url": null }
mysql, shell Then our three tests become simpler: [ "$(id -u)" = 0 ] || die "Must be root to run script" [ -n "$HOST" ] || die "HOST not passed." [ -n "$DB_PORT" ] || die "PORT not passed." Instead of the continue to skip over the performance_schema database, we could exclude it from our results: mysql -e 'show databases where `Database` not like "performance_schema"' And we can avoid the need to remove the Database column header by passing --skip-column-names. Since we're using Bash, which has arrays, we should use an array for the list of databases, particularly in case they might contain spaces in their names. We can use read -a to assign input lines to an array: IFS=$'\n' read -d '' -r -a db_list \ < <(mysql --batch --skip-column-names -e 'show databases') Then we can loop over the names: for db in "${db_list[@]}" do filename=${dir}${db}-${datestamp}.msql.${db_port}.gz echo "Initiating backup of $db for ${host} on port ${db_port}" $append_cli mysqldump \ -h "$host" -P "$db_port" -u "$db_user" -p"$db_pass" "$db" --single-transaction \ | gzip >$filename echo "Done backing up ${filename}" done
{ "domain": "codereview.stackexchange", "id": 42982, "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": "mysql, shell", "url": null }
php, authentication Title: Authenticate and login script Question: How can I improve/secure my login script and how to check for any possible injection? PS. the script must run on multiple platforms, so I need empty arrays for cases such as the Android ones. user_table: CREATE TABLE `user_table` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `user_type` varchar(255) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=63 DEFAULT CHARSET=latin1 Field Type Null Key Default Extra user_id int(11) NO PRI NULL auto_increment user_type varchar(255) NO NULL student_table: CREATE TABLE `student_table` ( `user_id` int(11) NOT NULL, `user_type` varchar(255) NOT NULL, `user_email` varchar(255) NOT NULL, `user_pass ` varchar(255) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 Field Type Null Key Default Extra user_id int(11) NO PRI NULL user_type varchar(255) NO NULL user_email varchar(255) NO NULL user_pass varchar(255) NO NULL teacher_table: CREATE TABLE `teacher_table` ( `user_id` int(11) NOT NULL, `Class` varchar(255) NOT NULL, `DEPARTMENT` varchar(255) NOT NULL, `user_email` varchar(255) NOT NULL, `user_pass ` varchar(255) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 Field Type Null Key Default Extra user_id int(11) NO PRI NULL Class varchar(255) NO NULL DEPARTMENT varchar(255) NO NULL user_email varchar(255) NO NULL user_pass varchar(255) NO NULL management_table: CREATE TABLE `management_table` ( `user_id` int(11) NOT NULL, `Class` varchar(255) NOT NULL, `DEPARTMENT` varchar(255) NOT NULL, `HEAD` varchar(255) NOT NULL, `user_email` varchar(255) NOT NULL, `user_pass ` varchar(255) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 Field Type Null Key Default Extra user_id int(11) NO PRI NULL Class varchar(255) NO NULL DEPARTMENT varchar(255) NO NULL HEAD varchar(255) NO NULL user_email varchar(255) NO NULL user_pass varchar(255) NO NULL
{ "domain": "codereview.stackexchange", "id": 42983, "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, authentication", "url": null }
php, authentication NULL HEAD varchar(255) NO NULL user_email varchar(255) NO NULL user_pass varchar(255) NO NULL user_status table: CREATE TABLE `user_status` ( `user_id` int(11) NOT NULL, `Login_id` int(11) NOT NULL, `user_token` varchar(255) NOT NULL, `user_status` varchar(255) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 Field Type Null Key Default Extra user_id int(11) NO NULL Login_id int(11) NO PRI NULL auto_increment user_token varchar(255) NO NULL user_status varchar(255) NO NULL login script: <?php //filter email var before connecting to database function validateEmail($email) { if(filter_var($email, FILTER_VALIDATE_EMAIL)) { //echo "email is valid"; } else { //echo "Email not valid"; exit; } } //connect to database function db_connect($db_name, $db_username, $db_password) { $conn = new PDO($db_name, $db_username, $db_password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $conn; } // check login credentials function userLogin($email, $password,$PDO) { $stmt = $PDO->prepare(" SELECT student_table.user_id ,student_table.user_pass FROM student_table WHERE student_table.user_email = :EMAIL UNION SELECT teacher_table.user_id ,teacher_table.user_pass FROM teacher_table WHERE teacher_table.user_email = :EMAIL UNION SELECT management_table.user_id,management_table.user_pass FROM management_table WHERE management_table.user_email = :EMAIL"); $stmt->bindParam(':EMAIL', $email); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); $hash = $row['user_pass']; $returnApp = array( 'LOGIN' => 'Wrong_password_email');
{ "domain": "codereview.stackexchange", "id": 42983, "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, authentication", "url": null }
php, authentication if (!empty($row) && password_verify($password, $hash)) { $user_id = $row['user_id']; return $user_id; }else{ return $returnApp; } } //guidv4 function guidv4($data = null) { $data = $data ?? random_bytes(16); assert(strlen($data) == 16); $data[6] = chr(ord($data[6]) & 0x0f | 0x40); $data[8] = chr(ord($data[8]) & 0x3f | 0x80); return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); } //create token function createtoken($user_id,$user_online,$user_token,$PDO){ $sql_insert = INSERT INTO user_status (user_id, user_token,user_status) VALUES (:ID,:TOKEN,:ONLINE ); $stmt = $PDO->prepare($sql_insert); $stmt->bindParam(':ID', $user_id); $stmt->bindParam(':ONLINE', $user_online); $stmt->bindParam(':TOKEN', $user_token); if ($stmt->execute()){ }else{ } } //getting user type function usertype($user_id,$PDO){ $sql_select ="SELECT user_table.user_type AS user FROM user_table WHERE user_table.user_id = :USER_ID"; $stmt = $PDO->prepare($sql_select); $stmt->bindParam(':USER_ID', $user_id); if ($stmt->execute()) { $row = $stmt->fetch(PDO::FETCH_ASSOC); return $row; }else{ } } //getting specific data for user limitation function getdata($user_id,$PDO){
{ "domain": "codereview.stackexchange", "id": 42983, "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, authentication", "url": null }
php, authentication $stmt = $PDO->prepare(" SELECT student_table.user_type AS type, user_status.login_id AS id, user_status.user_token AS Token, null, null FROM student_table LEFT JOIN user_status ON user_status.user_id = student_table.user_id WHERE student_table.user_id = :USERID UNION SELECT teacher_table.Class AS CL, teacher_table.DEPARTMENT AS DEP, user_status.login_id AS ID, user_status.user_token AS TOKEN, null FROM teacher_table LEFT JOIN user_status ON user_status.user_id = teacher_table.user_id WHERE teacher_table.user_id = :USERID UNION SELECT management_table.CLASS AS CL, management_table.DEPARTMENT AS DEP, management_table.HEAD AS HEAD, user_status.login_id AS ID, user_status.user_token AS TOKEN FROM management_table LEFT JOIN user_status ON user_status .user_id = management_table.user_id WHERE management_table.user_id = :USERID "); $stmt->bindParam(':USERID', $user_id); if ($stmt->execute()) { $row = $stmt->fetch(PDO::FETCH_ASSOC); $data = array( 'LOGIN' => 'Log_In_Success'); $final = array_merge($data, $row); return $final; }else{ } } $email = $_POST['email']; //validate email validateEmail($email);
{ "domain": "codereview.stackexchange", "id": 42983, "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, authentication", "url": null }
php, authentication $email = $_POST['email']; //validate email validateEmail($email); // connect to data base try { $PDO=db_connect("mysql:host=localhost;dbname=DATABASE", "root", ""); //echo "connection success"; } catch (PDOException $e) { //echo "Database error! " . $e->getMessage(); } $password =$_POST['pass']; //getting either user_id or email/pass dont match database $result = userLogin($email,$password,$PDO); $user_online = 'ONLINE'; $user_token = guidv4(); //if checks if email/pass is correct or error if (ctype_digit($result)) { //create token $token = createtoken($result,$user_online,$user_token,$PDO); //get type $user_type = usertype($result,$PDO); // get data $data = getdata($result,$PDO); // merge data with type $final = array_merge($data,$user_type); echo json_encode($final); }else{ echo json_encode($result); exit; } ?> Answer: You do have a user_table containing your users, but it is almost empty. You then put the user_id, user_email and user_pass fields in the student_table, teacher_table and management_table, requiring you to gather them together like this: SELECT student_table.user_id ,student_table.user_pass FROM student_table WHERE student_table.user_email = :EMAIL UNION SELECT teacher_table.user_id ,teacher_table.user_pass FROM teacher_table WHERE teacher_table.user_email = :EMAIL UNION SELECT management_table.user_id,management_table.user_pass FROM management_table WHERE management_table.user_email = :EMAIL This makes no sense. Why not put these fields in the user_table? The user table should contain all fields that are directly related to the user. That includes all the fields from the user_status table. This would make for a much simpler database design, and shorter database queries. Keeping things simple will increase the security of the code because it will be easier to spot security holes. This suggestion falls under the term: database normalization
{ "domain": "codereview.stackexchange", "id": 42983, "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, authentication", "url": null }
mysql Title: How to select lots of friends posts from database Question: $stmt = $conn->prepare( "SELECT post_by, id, post_preview, post_by_fullname, post_meta, total_likes, total_comments, total_shares, post_date, date_time FROM posts_table WHERE post_by IN( SELECT following FROM followers_table WHERE follower='me') AND post_date<? ORDER BY id DESC LIMIT 10"); My concern is only about this particular line: IN( SELECT following FROM followers_table WHERE follower='me') This code works fine but i'm worried If i'm following about 1000 people, will this code still function properly and fast. Is there limit to result in "IN()" Answer: I looked in the documentation as it says: The number of values in the IN() list is only limited by the max_allowed_packet value. So that limits the number of friends you can use here. The default value is 67108864, so I wouldn't worry. In my experience using IN() is always quite fast. They also say how it works: The values the list are sorted and the search ... is done using a binary search, which makes the IN() operation very quick. It basically works like a subquery: SELECT COUNT(*) > 0 FROM values WHERE value = searched In your query however, the use doesn't seem appropriate. It looks like you could simply use a table join, like this: SELECT P.* FROM posts_table AS P INNER JOIN followers_table AS F ON P.post_by = F.following WHERE F.follower = 'me' AND P.post_date < ? ORDER BY P.id DESC LIMIT 10 I've got no way to test this, so I cannot be sure it is correct, but something like this seems more sensible to me. You're basically trying to get a result by combining the data from 2 tables and a join is the normal way of doing that.
{ "domain": "codereview.stackexchange", "id": 42984, "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": "mysql", "url": null }
c++, template, signal-processing Title: Generic exponential damping to smooth noisy signals Question: Exponential damping is a type of "moving average", but it's not an arithmetic mean. The latter has the disadvantage that it requires storage of the last N samples in a std::deque or similar. Exponential damping has constant, and very small, storage costs of just 3 or 4 primitive types, no matter how "slow moving" or "aggressively smoothing" the damping is. The algorithm is also trivially simple, so this type of "moving" averaging is suitable for use in microcontrollers or very high speed systems. In fact, some microcontrollers such as Microchip's PIC series implement this algorithm in hardware, to smooth noisy analog input signals. (Their hardware version doesn't provide the "startup bridge" and the time_constant is in integer powers of 2, saving the "expensive" integer division. See below). This code review proposes a very simple generic class to make exponential damping available with flexible types to tailor it to the platform and data types. I have called this class damper. Its only constructor takes a single parameter which I have called time_constant for reasons, which are explained below. Here is damper smoothing the FramesPerSecond readout of a real time physics simulation (Note: these are not "visual frames" sent to the video card, but merely "frames" in the simulation"). That is probably "over smoothing", so lets drop the time_constant to 30. In order to gain some intuition of what this algorithm does, we can feed it with a "step function". We can see that the response is very similar to an exponential decay function, and is in fact very closely related, mathematically. We use this property below in our unit tests. This similarity is also the origin of the name of the constructor parameter: time_constant. The higher this value, the more aggressive the smoothing.
{ "domain": "codereview.stackexchange", "id": 42985, "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, signal-processing", "url": null }
c++, template, signal-processing The algorithm is so simple, that it's all done in 6 or 7 lines of code, and it really only has a single useful member function, for which we have used operator(). We have included an internal count_ to bridge the startup phase. This avoids damper only slowly ramping up to a steady state set of input samples. To make it slightly more challenging I have tried to make the class completely flexible on types, and this did indeed require some interesting testing regards "signedness", "narrowing", and warnings of "loss of precision". So I have turned the compiler warnings way up and included a set of unit tests below. We are using: clang++-13 -std=c++20 -O3 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Wextra-semi -Werror There is also fairly heavy commenting of what I found to be the tricky areas in dealing with the tested range of types. I chose to support and test the full range of c++ primitive integral and fp types, but nothing more; ie not user defined types, to keep it simple, fast and small memory footprint. I attempted to algebraically remove the need for an internal sum_ member, because this is in danger of overflowing, if the Sum type is inappropriately chosen by the user - she must choose Sum to be large enough to hold average_sample * time_constant. I was unable to find a way for the class implementation to protect the user from this danger. There is a commented out test illustrating the problem. It would be possible to omit the damped_value_ member but I decided for clarity and speed that it was better in. reset() and current() are trivial, and probably will only see rare usage. The final TEST shows a minimal damper, which occupies just 4 bytes of storage, for use in a uC, perhaps. damper.hpp #pragma once #include <concepts> #include <type_traits>
{ "domain": "codereview.stackexchange", "id": 42985, "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, signal-processing", "url": null }
c++, template, signal-processing #include <concepts> #include <type_traits> // Dampens a "noisy" value using "approx exponential damping". // Submit samples using `operator()`, which returns the damped value. // MUST choose a SUM type which can hold: sample avg * time_constant template <typename Value, typename Sum = Value, // type switch is required to prevent warnings AND incorrect arithmetic with -ves typename Count = std::conditional_t<std::is_signed_v<Value>, short, unsigned short>> requires std::floating_point<Value> || std::integral<Value> class damper { public: explicit damper(Count time_constant) : time_constant_(time_constant) {} Value operator()(Value sample) { if (count_ != time_constant_) { // branch avoids distortions for the first time_constant samples sum_ += sample; ++count_; } else { // Main running branch: once system is "primed" with time_constant number of samples // provides "approximately exponential damping" with the given time constant // correct, and well defined, even with unsigned types // but there remains is potential for overflow, if user choses a Sum type which cannot // hold sample avg * time_constant sum_ += sample - damped_value_; } // first static_cast suppresses -Wimplicit-int-conversion about very small types being // implicitly promoted to integer then demoted back again to be assigned to a small Value // type. // second static_cast is about a -Wimplicit-int-float-conversion of count_ from // eg (unsigned) int to float which is never likely to be relevant damped_value_ = static_cast<Value>(sum_ / static_cast<Sum>(count_)); return damped_value_; } Value current() { return damped_value_; } void reset() { sum_ = Sum{}; count_ = Count{}; damped_value_ = Value{}; }
{ "domain": "codereview.stackexchange", "id": 42985, "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, signal-processing", "url": null }
c++, template, signal-processing private: Sum sum_{}; Value damped_value_{}; Count count_{}; const Count time_constant_; }; damper_tests.cpp #include "damper.hpp" #include "gtest/gtest.h" #include <cmath> #include <concepts> #include <limits> #include <type_traits> // for testing purposes only template <typename Value, typename Sum = Value, // type switch is required to prevent warnings AND incorrect arithmetic with -ves typename Count = std::conditional_t<std::is_signed_v<Value>, int, unsigned>> requires std::floating_point<Value> || std::integral<Value> void test_damper(Value pre_step = 100, Value post_step = 0, Count tc = 10) { // modelling a step response from Value{pre_step} down to Value{post_step} after tc samples // expecting flat Value{100} and then "approximately exponential decay" towards Value{0} // `tc` is aprox equiv to the "time constant" in exponential damping // test empty damper auto d = damper<Value, Sum, Count>(tc); static_assert(std::is_same_v<decltype(d.current()), Value>); EXPECT_EQ(d.current(), Value{}); // tc samples with pre_step value for (auto i = Count{1}; i <= tc; ++i) { auto dv = d(pre_step); static_assert(std::is_same_v<decltype(dv), Value>); EXPECT_EQ(dv, pre_step); // check at every step that the `damped_value_` is "flat" } // `damper` is now fully "primed" with pre_step values // tc further samples of `post_step` values for (auto i = Count{1}; i <= tc; ++i) { auto dv = d(post_step); static_assert(std::is_same_v<decltype(dv), Value>); // check at every sample that we are matching the exponential decay curve // which predicts "approximately exponential damping" auto expected = post_step + (pre_step - post_step) * std::pow((tc - 1.0L) / tc, i);
{ "domain": "codereview.stackexchange", "id": 42985, "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, signal-processing", "url": null }
c++, template, signal-processing if constexpr (std::is_integral_v<Value>) { auto predicted = static_cast<Value>(std::round(expected)); // allow an integer result to be "off-by-one" after rounding // std::abs can't be used here, because programm would be ill-formed for some types EXPECT_TRUE(dv - predicted == Value{0} || dv - predicted == Value{1} || predicted - dv == Value{1}); } else { auto predicted = static_cast<Value>(expected); // for FP we expect the prediction to be within appropiately scaled epsilon EXPECT_LT(std::fabs(dv - predicted), std::fabs(pre_step - post_step) * std::numeric_limits<Value>::epsilon()); } } } // signed integer types TEST(damper, short) { test_damper<short>(); } TEST(damper, int) { test_damper<int>(); } TEST(damper, long) { test_damper<long>(); } TEST(damper, long_long) { test_damper<long long>(); } // signed integer types with a step from negative to positive TEST(damper, short_negstep) { test_damper<short>(-100, 100); } TEST(damper, int_negstep) { test_damper<int>(-100, 100); } TEST(damper, long_negstep) { test_damper<long>(-100, 100); } TEST(damper, long_long_negstep) { test_damper<long long>(-100, 100); } // unsigned integer types TEST(damper, unsigned_short) { test_damper<unsigned short>(); } TEST(damper, unsigned) { test_damper<unsigned>(); } TEST(damper, unsigned_long) { test_damper<unsigned long>(); } TEST(damper, unsigned_long_long) { test_damper<unsigned long long>(); } // FP types TEST(damper, float) { test_damper<float>(); } TEST(damper, double) { test_damper<double>(); } TEST(damper, long_double) { test_damper<long double>(); } // FP types with a step from negative to positive TEST(damper, float_negstep) { test_damper<float>(-100.0, 100.0); } TEST(damper, double_negstep) { test_damper<double>(-100.0, 100.0); } TEST(damper, long_double_negstep) { test_damper<long double>(-100.0, 100.0); }
{ "domain": "codereview.stackexchange", "id": 42985, "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, signal-processing", "url": null }
c++, template, signal-processing // tiny integer types (one use case is microcontroller analog input damping) TEST(damper, uint8_t__uint16_t) { test_damper<std::uint8_t, std::uint16_t>(); } TEST(damper, uint8_t__uint16_t__uint8_t) { test_damper<std::uint8_t, std::uint16_t, std::uint8_t>(); } // this test fails, because the sum overflows // I have tried to algebraically eliminate the sum, but it seems that, for integer arithmetic, // we always need at least a temporary result which can hold sample avg * time_constant // TEST(damper, uint8_t__uint8_t__uint8_t) { test_damper<std::uint8_t, std::uint8_t, // std::uint8_t>(); } // however, it is still a valid set of template params when sample avg * tc is small TEST(damper, uint8_t__uint8_t__uint8_t_small_values) { test_damper<std::uint8_t, std::uint8_t, std::uint8_t>(0, 40, 5); } Answer: Focusing in on the type of Count, following comments on my other answer. I see why you made it conditionally signed. I think that could be simplified. I was able to keep it unsigned, but still work with signed Sum type (also defining a concept so we can use abbreviated template constraints): template<typename T> concept arithmetic = std::is_arithmetic_v<T>; // Dampens a "noisy" value using "approx exponential damping". // Submit samples using `operator()`, which returns the damped value. // MUST choose a SUM type which can hold: sample avg * time_constant template <arithmetic Value, arithmetic Sum = Value, std::unsigned_integral Count = unsigned short> class damper
{ "domain": "codereview.stackexchange", "id": 42985, "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, signal-processing", "url": null }