text stringlengths 1 2.12k | source dict |
|---|---|
algorithm, c, hash-map
assert(hash_first_3_letters_ci("BA") == 676);
assert(hash_first_3_letters_ci("baa") == 676);
assert(hash_first_3_letters_ci("baabcd") == 676);
assert(hash_first_3_letters_ci("BAA") == 676);
assert(hash_first_3_letters_ci("BAABCD") == 676);
assert(hash_first_3_letters_ci("ba'a") == 676);
assert(hash_first_3_letters_ci("ba'abcd") == 676);
assert(hash_first_3_letters_ci("BA'A") == 676);
assert(hash_first_3_letters_ci("BA'ABCD") == 676);
assert(hash_first_3_letters_ci("aaz") == 25);
assert(hash_first_3_letters_ci("aazzzz") == 25);
assert(hash_first_3_letters_ci("AAZ") == 25);
assert(hash_first_3_letters_ci("AAZZZZ") == 25);
assert(hash_first_3_letters_ci("azz") == 675);
assert(hash_first_3_letters_ci("azzzzz") == 675);
assert(hash_first_3_letters_ci("AZZ") == 675);
assert(hash_first_3_letters_ci("AZZZZZ") == 675); | {
"domain": "codereview.stackexchange",
"id": 44242,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, c, hash-map",
"url": null
} |
algorithm, c, hash-map
assert(hash_first_3_letters_ci("zaa") == 676 * 25);
assert(hash_first_3_letters_ci("zaazyx") == 676 * 25);
assert(hash_first_3_letters_ci("ZAA") == 676 * 25);
assert(hash_first_3_letters_ci("ZAAZYX") == 676 * 25);
assert(hash_first_3_letters_ci("zzz") == (676 + 26 + 1) * 25);
assert(hash_first_3_letters_ci("zzzzyx") == (676 + 26 + 1) * 25);
assert(hash_first_3_letters_ci("ZZZ") == (676 + 26 + 1) * 25);
assert(hash_first_3_letters_ci("ZZZZYX") == (676 + 26 + 1) * 25);
return 0;
}
``` | {
"domain": "codereview.stackexchange",
"id": 44242,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, c, hash-map",
"url": null
} |
c++, regex, file-system, c++20
Title: Implementing Linux style file name wild cards on Windows 10 PowerShell
Question: Implementing Linux style file name wild cards on Windows 10 PowerShell
While implementing an objected oriented wc on Windows 10 in visual studio C++ I implemented a recursive file search with a weak attempt at pattern matching (regular expressions in file names). While unit testing it I discovered that it did not do a good job of file name matching. An example is that since the source code files of the wc program are a moving target, but I want to use those source files as test input for the wc program I created copies of the files with the file names ending in .cpp.txt and .h.txt. My wc program could not find these files separately, only as .txt files.
The code presented in this question fixes that bug in the program. This is only a stand alone test program. I haven't merged the code into the wc program yet.
This is my first attempt to use C++ regular expressions (std::regex).
One function in this code was contributed by another regular user here on Code Review, Toby Speight. I copied that code and used it as the basis for another function, the one where I actually implement a regex.
Questions:
Are any of the Linux wild card characters missing?
This should be pattern matching against file names only, does the regex in the code miss any legal characters in file names?
Can the use of std::regex be improved here?
Is there anything that isn't portable in this code?
Requirements
This code requires gcc12 to compile, the ranges and views implementation are not available in gcc11.
This code will compile in Visual Studio 2022 when C++20 is selected.
/*
* Testing Linux Shell file regular expressions on Windows 10.
* Need to be able to parse file specifications such as *.cpp.txt as well as
* *.cpp or *.txt.
*/
#include <filesystem>
#include <iostream>
#include <ranges>
#include <regex>
#include <string>
#include <vector> | {
"domain": "codereview.stackexchange",
"id": 44243,
"lm_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++, regex, file-system, c++20",
"url": null
} |
c++, regex, file-system, c++20
static const std::string BASE_SEARCH_DIR = "C:\\Users\\PaulC\\Documents\\ProjectsNfwsi\\StaticCodeEvalTools\\wconsteroids";
static const std::string questionMarkReplacement("[a-zA-Z0-9:$@#-_./]");
static const std::string starReplacement(questionMarkReplacement + "*");
namespace fsys = std::filesystem;
static std::string convertWildCards(std::string testInput)
{
std::string regexString;
try
{
std::regex qmark("\\?");
regexString = std::regex_replace(testInput, qmark, questionMarkReplacement);
std::regex asterisk("\\*");
regexString = std::regex_replace(regexString, asterisk, starReplacement);
}
catch (std::regex_error e)
{
std::cerr << "Regex Error: " << e.what() << "\n";
exit(EXIT_FAILURE);
}
return regexString;
}
struct SubDirNode
{
fsys::path fileSpec;
bool discovered = false;
bool searchedFiles = false;
SubDirNode(fsys::path path)
: fileSpec{ std::move(path) }
{
}
bool operator==(const SubDirNode& other) const
{
return fileSpec == other.fileSpec;
}
bool operator!=(const SubDirNode& other) const = default;
};
static bool SearchSubDirs = true;
static std::vector<SubDirNode> subDirectories;
/*
* Search the current directory for sub directories.
*/
static auto findSubDirs(const SubDirNode& currentDir)
{
// The code and comments in this function was contributed by @tobyspeight
auto is_missing = [](const SubDirNode& branch) {
return std::ranges::find(subDirectories, branch) == subDirectories.end();
};
auto subdirs = fsys::directory_iterator{ currentDir.fileSpec }
| std::views::filter([](auto& f) { return f.is_directory(); })
| std::views::transform([](auto& f)->SubDirNode { return f.path(); })
| std::views::filter(is_missing); | {
"domain": "codereview.stackexchange",
"id": 44243,
"lm_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++, regex, file-system, c++20",
"url": null
} |
c++, regex, file-system, c++20
// TODO (C++23?) return std::vector(subdirs);
auto newSubDirs = std::vector<SubDirNode>{};
std::ranges::copy(subdirs, std::back_inserter(newSubDirs));
return newSubDirs;
}
static bool discoverSubDirs()
{
bool discoveredPhaseCompleted = true;
std::vector<SubDirNode> newSubDirs;
for (std::size_t i = 0; i < subDirectories.size(); i++)
{
if (!subDirectories[i].discovered)
{
std::vector<SubDirNode> tempNewDirs = findSubDirs(subDirectories[i]);
if (tempNewDirs.size())
{
discoveredPhaseCompleted = false;
newSubDirs.insert(newSubDirs.end(), tempNewDirs.begin(),
tempNewDirs.end());
}
subDirectories[i].discovered = true;
}
}
// We are done searching the current level, append the new sub directories
// to the old.
subDirectories.insert(subDirectories.end(), newSubDirs.begin(), newSubDirs.end());
return discoveredPhaseCompleted;
}
static std::vector<std::string> fileList;
static auto searchDirectoryForFilesByPattern(SubDirNode currentDir,
std::string partialFileSpec)
{
auto is_missing = [](const std::string& branch) {
return std::ranges::find(fileList, branch) == fileList.end();
};
std::vector<std::string> newFiles = {};
std::string patternString = convertWildCards(partialFileSpec);
try
{
std::string dir = currentDir.fileSpec.string();
std::regex pattern(patternString);
auto is_type = [pattern](auto f) {
return std::regex_search(f.path().string(), pattern);
};
auto files = fsys::directory_iterator{ currentDir.fileSpec }
| std::views::filter([](auto& f) { return f.is_regular_file() ||
f.is_character_file(); })
| std::views::filter(is_type)
| std::views::transform([](auto& f) { return f.path().string(); })
| std::views::filter(is_missing); | {
"domain": "codereview.stackexchange",
"id": 44243,
"lm_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++, regex, file-system, c++20",
"url": null
} |
c++, regex, file-system, c++20
std::ranges::copy(files, std::back_inserter(newFiles));
}
catch (std::regex_error& re)
{
std::cerr << "Regex Error: " << re.what() << "\n";
std::cerr << patternString << "\n";
exit(EXIT_FAILURE);
}
return newFiles;
}
static void searchAllDirectoriesForFiles(std::string partialFileSpec)
{
for (auto currentDir : subDirectories)
{
if (currentDir.discovered && !currentDir.searchedFiles)
{
std::vector<std::string> newFiles =
searchDirectoryForFilesByPattern(currentDir, partialFileSpec);
std::copy(newFiles.begin(), newFiles.end(), std::back_inserter(fileList));
currentDir.searchedFiles = true;
}
}
}
static void discoverAllSubDirs()
{
bool discoveryPhaseCompleted = false;
while (!discoveryPhaseCompleted)
{
discoveryPhaseCompleted = discoverSubDirs();
}
}
static std::vector<std::string> findAllFilesMatching(std::string partialFileSpec)
{
fileList.clear();
std::filesystem::path cwd = BASE_SEARCH_DIR;
if (subDirectories.empty())
{
SubDirNode root(cwd);
root.discovered = (SearchSubDirs) ? false : true;
subDirectories.push_back(root);
}
discoverAllSubDirs();
searchAllDirectoriesForFiles(partialFileSpec);
return fileList;
}
static void testFindAllFilesMAtching(std::string partialFileSpec)
{
std::cout << "Searching for files that match " << partialFileSpec << " found:\n";
std::vector<std::string> matchingFiles = findAllFilesMatching(partialFileSpec);
for (auto fileName : matchingFiles)
{
std::cout << "\t" << fileName << "\n";
}
std::cout << "\n";
} | {
"domain": "codereview.stackexchange",
"id": 44243,
"lm_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++, regex, file-system, c++20",
"url": null
} |
c++, regex, file-system, c++20
int main(int argc, char* argv[])
{
testFindAllFilesMAtching("CmdLineFileExtractor.cpp");
testFindAllFilesMAtching("CmdLineFileExtractor.*");
testFindAllFilesMAtching("Cmd*.cpp");
testFindAllFilesMAtching("Cmd*.*");
testFindAllFilesMAtching("Cmd*.cpp.txt");
testFindAllFilesMAtching("Cmd*.*");
testFindAllFilesMAtching("*.h");
testFindAllFilesMAtching("*.cpp");
testFindAllFilesMAtching("*.h.txt");
testFindAllFilesMAtching("*.cpp.txt");
}
You will find some of this code in the current version of wconsteroids.
Answer: ? in a wildcard pattern matches any character, so we want . in place of [a-zA-Z0-9:$@#-_./]. Actually, it will match a newline, so probably (.|\n) would be better.
std::regex_error should not be thrown unless we made a programming error; I'd replace the contents of that catch with an assert(false) and abort().
The comment (written by me) // TODO (C++23?) return std::vector(subdirs); is inaccurate. The correct and idiomatic C++23 will use | std::ranges::to<std::vector>(). | {
"domain": "codereview.stackexchange",
"id": 44243,
"lm_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++, regex, file-system, c++20",
"url": null
} |
c++, converting
Title: An up-cast for C++
Question: Usually in C++, the language rules automatically widen types as necessary. For example, I can pass a pointer-to-derived in place of a pointer-to-base, and the same with references.
There are occasions where one needs to specify a type to which a value should be coerced. A common case of this is in the alternatives of the ?: operator, when C++'s rules don't always determine the common type successfully. Also, it's sometimes useful to make a pointer or reference to the const version of its type, to select the desired overload of a function.
We could use a static_cast or dynamic_cast in these circumstances, but that requires more attention from reviewers to ensure that it's definitely an up-cast rather than a down-cast. So I wrote this small function to make this easier:
#include <concepts>
template<typename T>
constexpr T up_cast(std::convertible_to<T&&> auto&& value)
{
return value;
}
Here's a demonstration of the simplest case I could imagine that requires it:
struct Base {int n;};
struct A : Base {};
struct B : Base {};
const Base& object(bool select)
{
static auto const a = A{1};
static auto const b = B{2};
return select
? up_cast<const Base&>(a)
: up_cast<const Base&>(b);
}
Answer: Up-casting is not widening
Usually in C++, the language rules automatically widen types as necessary. For example, I can pass a pointer-to-derived in place of a pointer-to-base, and the same with references. | {
"domain": "codereview.stackexchange",
"id": 44244,
"lm_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++, converting",
"url": null
} |
c++, converting
That's not widening. Widening happens on values of primitive data types, like widening a short to a long. Converting a pointer-to-derived to a pointer-to-base is an up-cast, and the reverse a down-cast, so later on your terminology is correct.
std::convertible_to is not enough
You can't just use std::convertible_to to check that you are doing an up-cast. As the name implies, it only checks if a conversion between the given types are allowed, and conversion can happen in many ways. Consider this slight modification of your example code:
struct Base {
int n;
Base() = default;
Base(int): n(n) {}
};
struct A : Base {};
struct B : Base {};
const Base& object(bool select)
{
static auto const a = A{1};
static auto const b = 2;
return select
? up_cast<const Base&>(a)
: up_cast<const Base&>(b);
}
The second call to up_cast() would just construct a new temporary Base object and return a reference to that. I think you should add a std::derived_from clause to make sure that you are actually converting from a derived class to its base.
You should also make sure that the input and output are either references or pointers to prevent accidental slicing. Consider:
const Base& object(bool select)
{
static auto const c = select
? up_cast<Base>(A{1})
: up_cast<Base>(B{2});
return c;
}
That will compile and do the wrong thing, and the whole point of this function is to ensure we prevent that from compiling.
Make it easier to use
Having to remember the right cv-qualification and adding a reference is a bit annoying. I'd just want to write up_cast<Base>(foo) and have it return a const Base& or Base& or maybe even a volatile Base*, depending on what foo is. | {
"domain": "codereview.stackexchange",
"id": 44244,
"lm_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++, converting",
"url": null
} |
python, performance, algorithm, pandas
Title: Convert a mapping of arbitrary pairs into a one-to-many map
Question: The accepted solution is much cleaner and outperforms the algorithm below for small maps, it doesn't do as well with larger ones: my code takes twice as long as the accepted code for maps of 10 pairs (30 vs. 15 ms), but mine is something like 30 times faster for the larger input described below (8 s vs. 4 m). However, @Reinderien's code never consumes more than around 120MB of memory. Mine is the same for 10-pair maps but it can take well over 1GB for large input (this is all in a Jupyter notebook on my intel i7 windows machine).
I've written an answer to this post with an improved algorithm that splits the difference - it handles the large test case in 55 seconds and consumes less than 600M of memory
The problem
I'm working in python. I have sets of pairs of integers that should be interpreted as bidirectional maps: values in one column should be mapped to values in the other column, but all paired values are considered equivalent. This means that the many-to-many map
src tgt
1 2
2 3
4 3
4 1
5 4
is equivalent to the one-to-many map
src tgt
5 1
5 2
5 3
5 4
I want to take an arbitrary set of input pairs and generate a one-to-many map.
I'm happy with solutions using pandas or pure python, but solutions should only include the standard library and pandas.
Description of my solution
I've written a function that will convert an arbitrary two-column pandas dataframe of integers into a one-to-many map from the first column to the second column.
Below, "first instance" of a value means the earliest occurrence of a row with that value when scanning from the beginning of the dataframe in its current order (the lowest row index that will return the value when using df.iloc rather than df.loc).
There are about six steps in my solution: | {
"domain": "codereview.stackexchange",
"id": 44245,
"lm_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, algorithm, pandas",
"url": null
} |
python, performance, algorithm, pandas
Drop rows of the form [b, a] when the row [a, b] is also present
For values duplicated anywhere in the input regardless of column position,
2.1 locate rows with the first second-column instance of any of the duplicate values
2.2 locate rows with the first second-column instance of duplicate values whose first instance in the entire dataframe is in the second column
Map instances of the second-column values above to the first-column partners of their first instances in the second column
3.1 for the set of rows 2.1, map all instances of the second-column values found anywhere in the first column to the first-column partners of the second-column values in set 2.1
3.2 for the set of rows 2.2, map all duplicate instances of the second-column values in the second column to the first-column partner of the second-column values in set 2.2 and then swap the first and second columns in the rows with duplicate second-column values
Rearrange the input so that values duplicated anywhere in the input should appear first in the second column
If there are any rows whose second-column values also appear in the first column, swap the values in one of those rows (this is a kludge to avoid infinite loops)
If the map is not one-to-many, start over again
I expect there's an algorithm with fewer steps, but even if there isn't I think someone has to be able to do this more efficiently than I have. I have code to test performance at the end - I'm more interested in solutions that use less memory than solutions that run faster, but I'm interested in solutions that boost performance either way.
My code
Sorry for some obscenely long names; this has been a conceptual nightmare for me so I got verbose.
import pandas as pd
def make_bidirectional_map_one_to_many(df):
input_columns = list(df.columns)
df.columns = [0, 1] | {
"domain": "codereview.stackexchange",
"id": 44245,
"lm_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, algorithm, pandas",
"url": null
} |
python, performance, algorithm, pandas
input_columns = list(df.columns)
df.columns = [0, 1]
# Drop identities in a way that doesn't copy the whole dataframe.
identities = df.loc[df[0] == df[1]]
df = df.drop(identities.index).drop_duplicates()
# Using the above method because the following line raises a copy
# vs. view warning:
# df = df.loc[df[0] != df[1], :]
# Check if the input dataframe is already a one-to-many map
if not df[1].duplicated().any() and not df[1].isin(df[0]).any():
return df
# Stack the values so we can find duplicate values regardless of the
# column
values = df.stack()
duplicate_values = values.loc[values.duplicated(keep=False)]
'''
Drop rows of the form [b, a] when the row [a, b] is also present
'''
# Get values that are duplicated and present in both columns
value_selection = duplicate_values.loc[
duplicate_values.isin(df[0]) & duplicate_values.isin(df[1])
]
drop_candidates = df.loc[df[1].isin(value_selection)]
# Hash the dataframe to search for whole rows
hashed_df = pd.util.hash_pandas_object(df, index=False)
# Reverse the selected rows and hash them to search for the
# reversed rows in the input dataframe
reversed_candidates = drop_candidates[[1, 0]]
hashed_candidates = pd.util.hash_pandas_object(
reversed_candidates,
index=False
)
# Drop the reversed rows if they're present in the dataframe
drop_candidates = hashed_df.isin(hashed_candidates)
if drop_candidates.any(): | {
"domain": "codereview.stackexchange",
"id": 44245,
"lm_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, algorithm, pandas",
"url": null
} |
python, performance, algorithm, pandas
# If the search above caught [a, b] then it also caught [b, a]
# so we select one of those rows by stacking, sorting by index
# and then by value, pivoting back to the original shape, and
# then dropping duplicate rows.
drop_candidates = df.loc[hashed_df[drop_candidates].index]
drop_candidates = drop_candidates.stack().reset_index()
drop_candidates = drop_candidates.sort_values(by=['level_0', 0])
drop_candidates.loc[:, 'level_1'] = [0, 1]*int(len(drop_candidates)/2)
drop_candidates = drop_candidates.pivot(
index='level_0',
columns='level_1',
values=0
)
drop_rows = drop_candidates.drop_duplicates().index
df = df.drop(drop_rows)
# If the dataframe is now a one-to-many map, we're done
if not df[1].duplicated().any():
if not df[1].isin(df[0]).any():
return df
# Stack the modified dataframe and get duplicate values
values = df.stack()
duplicate_values = values.loc[values.duplicated(keep=False)]
'''
Locate two different types of duplicate values in the second column
'''
# Get first instance in the second column of values duplicated
# anywhere in the dataframe
first_instance_of_any_dplct_in_c1 = (
duplicate_values.loc[(slice(None), 1)].drop_duplicates()
)
# Get values from the second column which are duplicated anywhere
# in the dataframe but which occurred first in the second column
frst_instnc_of_dplct_found_in_c1_frst = duplicate_values.drop_duplicates()
if 1 in frst_instnc_of_dplct_found_in_c1_frst.index.get_level_values(1):
frst_instnc_of_dplct_found_in_c1_frst = (
frst_instnc_of_dplct_found_in_c1_frst.loc[(slice(None), 1)]
)
else:
frst_instnc_of_dplct_found_in_c1_frst = pd.Series([], dtype=int) | {
"domain": "codereview.stackexchange",
"id": 44245,
"lm_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, algorithm, pandas",
"url": null
} |
python, performance, algorithm, pandas
else:
frst_instnc_of_dplct_found_in_c1_frst = pd.Series([], dtype=int)
# If values duplicated anywhere in the dataframe exist in the
# second column, map the duplicates to the first-column
# partner of the first instance of the value in the second column
if df[1].duplicated().any():
'''
Make maps between the different kinds of first second-column
instances and their first-column partners
'''
# Map from the first instance in the second column of values
# duplicated anywhere in the dataframe to their first-column
# partners
df_selection = df.loc[first_instance_of_any_dplct_in_c1.index]
map_to_c0_from_frst_instnc_of_any_dplct_in_c1 = pd.Series(
df_selection[0].array,
index=df_selection[1].array
)
# Map from duplicate values that occurred first in the second
# column to the first-column partners of their first instance
map_to_c0_from_frst_instnc_of_dplct_found_in_c1_frst = df.loc[
frst_instnc_of_dplct_found_in_c1_frst.index,
:
]
map_to_c0_from_frst_instnc_of_dplct_found_in_c1_frst = pd.Series(
map_to_c0_from_frst_instnc_of_dplct_found_in_c1_frst[0].array,
index=map_to_c0_from_frst_instnc_of_dplct_found_in_c1_frst[1].array
)
'''
Apply the maps
'''
# Get rows with values in the first column that appeared
# first in the second column
c0_value_was_found_in_c1_first = df.loc[
df[0].isin(first_instance_of_any_dplct_in_c1),
:
]
# Map those values to the first-column partners of their first
# instances in the second column
mapped_c0 = c0_value_was_found_in_c1_first[0].map(
map_to_c0_from_frst_instnc_of_any_dplct_in_c1
)
df.loc[c0_value_was_found_in_c1_first.index, 0] = mapped_c0.array | {
"domain": "codereview.stackexchange",
"id": 44245,
"lm_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, algorithm, pandas",
"url": null
} |
python, performance, algorithm, pandas
# Get all duplicate values in the second column which appeared first
# in the second column
c1_value_was_found_in_c1_first = df.loc[
df[1].isin(frst_instnc_of_dplct_found_in_c1_frst),
:
]
# Drop the first instances to isolate only the duplicates
c1_value_was_found_in_c1_first = c1_value_was_found_in_c1_first.drop(
frst_instnc_of_dplct_found_in_c1_frst.index
)
# If there are duplicate values in the second column which
# appeared first in the second column, map those values to the
# first-column partners of their first instances and then swap
# values in those rows so the first instance's first-column
# partner is in the first column
if not c1_value_was_found_in_c1_first.empty:
mapped_1 = c1_value_was_found_in_c1_first[1].map(
map_to_c0_from_frst_instnc_of_dplct_found_in_c1_frst
)
df.loc[c1_value_was_found_in_c1_first.index, :] = list(zip(
mapped_1.array,
df.loc[c1_value_was_found_in_c1_first.index, 0]
))
df = df.drop_duplicates()
# Rearrange the dataframe so that values which appear in both
# columns appear first in the second column
c1_in_c0 = df[1].isin(df[0])
df = pd.concat([df.loc[c1_in_c0], df.loc[~c1_in_c0]])
c0_in_c1 = df[0].isin(df[1])
df = pd.concat([df.loc[~c0_in_c1], df.loc[c0_in_c1]])
# In some cases the above algorithm will loop indefinitely if there
# are values that occur in both columns but there are no repeated
# values in the second column. Avoid this finding rows with values
# in the first column that are present in the second column and, if
# any exist, swapping values in the first row found.
c0_in_c1 = df[0].isin(df[1]) | {
"domain": "codereview.stackexchange",
"id": 44245,
"lm_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, algorithm, pandas",
"url": null
} |
python, performance, algorithm, pandas
if c0_in_c1.any():
to_swap = df.loc[c0_in_c1].index[0]
df.loc[to_swap, :] = df.loc[to_swap, [1, 0]].to_numpy()
df.columns = input_columns
# Remap the modified dataframe
return make_bidirectional_map_one_to_many(df)
Code to test solutions
The above code gives this result
a = pd.DataFrame({0:[1,2,4,4,5], 1:[2,3,3,1,4]})
make_bidirectional_map_one_to_many(a)
0 1
2 5 2
1 5 3
0 5 4
3 5 1
But note that since the map is bidirectional, it doesn't matter which integer is in column 0 and the ordering in the output doesn't matter.
I can run the following code from a VS Code jupyter notebook (Windows) in about 32 seconds on an intel i7, and the python process in the task manager never consumes more than about 100M of memory. With number_of_runs = 10, pop_size = 1e4, and sample_size = 1e6, it takes about 81 seconds and memory consumption can spike to 1.3G but probably averages about 800M.
import time
import pandas as pd
number_of_runs = 1e3
def run_it():
pop_size = 1e1
sample_size = 1e1
t = str(time.time()).split('.')
s1 = int(t[0])
s2 = int(t[1])
pop = pd.Series(pd.RangeIndex(stop=pop_size))
sampled = pd.DataFrame({
'a': pop.sample(int(sample_size), replace=True, random_state=s1).array,
'b': pop.sample(int(sample_size), replace=True, random_state=s2).array
})
try:
make_bidirectional_map_one_to_many(sampled)
except:
print(sampled)
raise RuntimeError
for i in range(1, int(number_of_runs) + 1):
time.sleep(.005)
run_it()
Answer: Somewhat guessing what you're really trying to do:
Forget Pandas for the moment. Consider the left column to be the first vertices of a graph edge, and the second column to contain the second vertex for each of those edges. Your graph has properties:
Undirected
Finite
Not necessarily acyclic, connected or complete
You want to apply a graph transformation to produce a new graph where: | {
"domain": "codereview.stackexchange",
"id": 44245,
"lm_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, algorithm, pandas",
"url": null
} |
python, performance, algorithm, pandas
You want to apply a graph transformation to produce a new graph where:
You identify components of your original graph
Within each component, you
Choose (arbitrarily?) a vertex to become universal
Remove all other edges.
This should give you enough Google fodder. I cannot promise that the following suggested algorithm is the most efficient, but it approaches something sane. It drops out of Pandas for simplicity's sake but certain parts may be further vectorisable.
import pandas as pd
def make_bidirectional_map_one_to_many(df: pd.DataFrame) -> pd.DataFrame:
# Dictionary of every known key to a set
# representing the component we think it's in.
components: dict[int, set[int]] = {}
for idx, (src_k, tgt_k) in df.iterrows():
# Start off with either existing component sets, or make singleton sets.
src_set = components.setdefault(src_k, {src_k})
tgt_set = components.setdefault(tgt_k, {tgt_k})
# Overwrite all of the source set entries with a reference to the target set
components.update({
k: tgt_set for k in tuple(src_set)
})
# Union the source set into the target set
# (all references to this set will update)
tgt_set |= src_set
# All vertices that we've added to the universals list so far
covered = set()
# List of source-target tuples
universals = []
for k, component in components.items():
if k not in covered:
covered |= component
for c in component:
if k != c:
universals.append((k, c))
return pd.DataFrame.from_records(universals, columns=('src', 'tgt')) | {
"domain": "codereview.stackexchange",
"id": 44245,
"lm_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, algorithm, pandas",
"url": null
} |
c++, dependency-injection, callback
Title: An NVIDIA Jetson Nano GPIO Wheel Encoder Message Publisher using ROS2
Question: Although this code uses ros2 my concern is about C++ code quality, because I still struggle when it comes to making good design decisions with regards to single responsibility, dependency injection, and callbacks, etc. I tend to second-guess decisions due to lack of experience.
I am also always worried about which objects to use in callbacks in terms of race conditions (which in this case is not really applicable but it's something I worry about getting wrong).
The below code example is very simple. There's a wheel encoder connected to the GPIO pin on an NVIDIA Jetson Nano board, and a ROS2 Node that publishes the encoder.
I already tested this code on the Jetson Nano and it is fully functional.
The wheel_encoder_sensor.h file
#pragma once
#include <iostream>
#include <memory>
#include <functional>
#include <JetsonGPIO.h>
namespace xiaoduckie {
namespace sensors {
/*!
* @brief This class manages the WheelEncoder sensor connected to the GPIO
* pins in the NVIDIA Jetson Nano Board
* @ingroup Sensors
*/
class WheelEncoderSensor {
/*!
* @brief ENUM that represents the direction of motion for the robot.
* This value is updated when the controller makes a decision about
* direction.
* The value is used to update the global tick count on the encoder.
* @ingroup Sensors
*/
enum Direction {
FORWARD = 1,
BACKWARD = -1
}; | {
"domain": "codereview.stackexchange",
"id": 44246,
"lm_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++, dependency-injection, callback",
"url": null
} |
c++, dependency-injection, callback
/*!
* @brief This class is used by the Jetson GPIO c++ library as a callback
* for the event detect on a GPIO pin.
* We cannot use a regular lambda bcause this Jetson GPIO library requires
* the callbacks must be equaility-comparable.
* More details: https://github.com/pjueon/JetsonGPIO/issues/55#issuecomment-1059888835
* @ingroup Sensors
*/
class EncoderCallback
{
public:
/*!
* @brief Default constructor.
* @param name Reference to the name assigned to this callback.
* @param ticks Pointer referring to total ticks in the WheelEncoderSensor.
* @param callback The external callback passed to WheelEncoderSensor.
* @param direction Pointer to the DIRECTION enum in WheelEncoderSensor.
*/
EncoderCallback(
const std::string& name,
std::shared_ptr<int> ticks,
std::function<void(int)> callback,
std::shared_ptr<WheelEncoderSensor::Direction> direction)
: name(name),
callback_(std::move(callback)),
ticks_(ticks),
direction_(direction)
{};
/*!
* @brief Default copy constructor
*/
EncoderCallback(const EncoderCallback&) = default; // Copy-constructible
/*!
* @brief Callable executed by the GPIO library upon event detection.
* Used to update the global tick count and execute the callback provided
* to the Encoder through its constructor.
* @param channel Reference to the GPIO pin passed in by the library.
*/
void operator()(const std::string& channel) // Callable with one string type argument
{
std::cout << "A callback named " << name;
std::cout << " called from channel " << channel << std::endl;
*ticks_ += *direction_;
callback_(*ticks_);
} | {
"domain": "codereview.stackexchange",
"id": 44246,
"lm_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++, dependency-injection, callback",
"url": null
} |
c++, dependency-injection, callback
/*!
* @brief equality operator used by GPIO library to remove callbacks.
* @param other Reference to the object being compared.
*/
bool operator==(const EncoderCallback& other) const // Equality-comparable
{
return name == other.name;
}
/*!
* @brief in-equality operator used by GPIO library to remove callbacks.
* @param other Reference to the object being compared.
*/
bool operator!=(const EncoderCallback& other) const
{
return !(*this == other);
}
private:
std::string name;
std::function<void(int)> callback_;
std::shared_ptr<int> ticks_ = std::make_shared<int>(0);
std::shared_ptr<WheelEncoderSensor::Direction> direction_ = std::make_shared<WheelEncoderSensor::Direction>();
};
public:
/*!
* @brief Default constructor.
*/
WheelEncoderSensor() = default;
/*!
* @brief The Init function sets the GPIO used by this encoder,
* accepts an additional callback to use when the encoder is
* updated.
* It initializes the internal callback mechanism and passes it
* the additional/external one.
* @param gpio The GPIO pin to which the encoder is connected.
* @param callback The external callback.
*/
bool Init(int gpio, std::function<void(int)> callback) {
gpio_pin_ = gpio;
*direction_ = Direction::FORWARD;
EncoderCallback callback_(
"EncoderCallback",
ticks_,
std::move(callback),
direction_
);
GPIO::setmode(GPIO::BCM);
GPIO::setup(gpio_pin_, GPIO::IN);
GPIO::add_event_detect(gpio_pin_, GPIO::RISING, callback_);
initialized_ = true;
return true;
};
private:
int gpio_pin_;
bool initialized_ = false;
std::shared_ptr<int> ticks_ = std::make_shared<int>(0);
std::shared_ptr<WheelEncoderSensor::Direction> direction_ = std::make_shared<WheelEncoderSensor::Direction>();
}; | {
"domain": "codereview.stackexchange",
"id": 44246,
"lm_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++, dependency-injection, callback",
"url": null
} |
c++, dependency-injection, callback
} // namespace sensors
} // namespace xiaoduckie
The wheel_encoder_publisher.h file
#pragma once
#include <chrono>
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include <iostream>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/int32.hpp"
#include "wheel_encoder/wheel_encoder_sensor.h"
namespace xiaoduckie {
namespace sensors {
/*!
* @brief This is the ROS2 Node that publishes the encoder messages.
* It is constructed with an std::vector of WheelEncodersNode::WheelEncoderConfig
* objects and creates an instance of a WheelEncoderSensor for each, then assigns
* to each its own callback using a lambda function. The lambda function publishes
* the encoder value.
* @ingroup Sensors
*/
class WheelEncodersNode : public rclcpp::Node {
typedef rclcpp::Publisher<std_msgs::msg::Int32>::SharedPtr PublisherPtr;
public:
/*!
* @brief This Struct holds the config for each WheelEncoderSensor
* @ingroup Sensors
*/
struct WheelEncoderConfig {
int gpio_pin_;
int resolution_;
int publish_frequency_;
int queue_limit;
std::string orientation_;
std::string topic_name_;
};
/*!
* @brief Default constructor.
* @param encoder_configs const Reference to the std::vector of WheelEncoderConfig.
*/
WheelEncodersNode(const std::vector<WheelEncoderConfig>& encoder_configs)
: Node("WheelEncodersNode"), encoder_configs_(encoder_configs)
{
int index = 0;
for (auto const &config : encoder_configs_) {
encoder_total_ticks_.push_back(0);
PublisherPtr p = this->create_publisher<std_msgs::msg::Int32>(
config.topic_name_,
config.publish_frequency_);
std::shared_ptr<WheelEncoderSensor> encoder = std::make_shared<WheelEncoderSensor>();
encoder.get()->Init(
config.gpio_pin_,
[p, index, this] (int encoder_ticks) { | {
"domain": "codereview.stackexchange",
"id": 44246,
"lm_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++, dependency-injection, callback",
"url": null
} |
c++, dependency-injection, callback
auto message = std_msgs::msg::Int32();
message.data = encoder_ticks;
this->encoder_total_ticks_[index] = encoder_ticks;
p->publish(message);
}
);
encoders_.push_back(encoder);
++index;
}
};
private:
std::vector<int> encoder_total_ticks_;
std::vector<WheelEncoderConfig> encoder_configs_;
std::vector<std::shared_ptr<WheelEncoderSensor>> encoders_;
std::vector<PublisherPtr> publishers_;
};
} // namespace sensors
} // namespace xiaoduckie
Answer: It isn't clear why there are 2 namespaces, one nested inside the other. The namespace sensors is understandable, what is xiaoduckie?
Indentation: A namespace inside a namespace needs to be indented.
Defining a class within a class such as EncoderCallback is problematic. Among other things it means that the class can't be easily reused; any inheritance becomes overly complicated. Why is it being defined within a class rather than as its own class file?
The class EncoderCallback violates the rule of 3 which states
If a class requires a user-defined destructor, a user-defined copy constructor, or a user-defined copy assignment operator, it almost certainly requires all three.
Why define a copy constructor using default without defining a destructor or an assignment operator?
Rather than have a default constructor and an Init() function for the class WheelEncoderSensor there can be 2 constructors, one with the function body of Init().
Why is direction_ a pointer?
gpio_pin_ should always be initialized, if the parameter isn't passed in, initialize it to a suitable value such as zero.
Where are the C++ (.cpp) files that should be with these header files? Why is all the code in the header files rather than putting most of the executable code in .cpp files? Putting all of the code into the header files means that all the files need to be recompiled every time there is a code change. | {
"domain": "codereview.stackexchange",
"id": 44246,
"lm_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++, dependency-injection, callback",
"url": null
} |
python, machine-learning, matplotlib
Title: Plotting correlation matrix with Seaborn and pandas
Question: I try to plot the correlation matrix of a Pandas DataFrame. As the diagonal elements are always ones, and the matrix is symmetrical, so I can get rid of most than a half of the squares without loosing any useful information. I also moved the zero to the white color by default. Is there any other way to improve the function?
import seaborn as sns
import numpy as np
def plot_correlation_matrix(df, decimal=2, **kwargs):
kwargs["cmap"] = kwargs.get("cmap", "vlag")
kwargs["center"] = kwargs.get("center", 0) # 0 will be white if you use vlag cmap
kwargs["fmt"] = kwargs.get("fmt", f".{decimal}f")
corr = df.corr()
corr_reduced = corr.iloc[1:,:-1] # No need for first row, last column
mask = np.triu(np.ones_like(corr_reduced, dtype=bool), k=1) # No need for upper triangle
sns.heatmap(corr_reduced, annot=True, mask=mask, **kwargs)
# Using the function
df_ir = sns.load_dataset("iris")
df_ir.petal_length = - df_ir.petal_length # creating negative correlation
plot_correlation_matrix(df_ir)
Answer: There are few things you can improve or add to your function: | {
"domain": "codereview.stackexchange",
"id": 44247,
"lm_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, machine-learning, matplotlib",
"url": null
} |
python, machine-learning, matplotlib
Answer: There are few things you can improve or add to your function:
You can add a title to the plot using the title parameter in the heatmap function. This will make it easier to interpret the plot.
Specify to range of values that the color map can have by using the vmin and vmax parameters in the heatmap function.
You can disable the color bar by using the cbar parameter in the heatmap function. If you are displaying a lot if matrices, you should save some space
using the square parameter to force the plot to be a square. If you have a big number of columns the plot would be very wide.
To improve the visual appeal you can use linecolor and linewidth to specify the color and width of the lines between the cells.
you can use the xticklabels and yticklabels parameters to disable the x and y-axis. Again if you have a big number of columns, you may want to save space.
You can also use annot_kws to use additional formatting options e.g. fontsize
Using the numpy function triu_indices to remove the need of the mask parameter in the heatmap function
import seaborn as sns
import numpy as np | {
"domain": "codereview.stackexchange",
"id": 44247,
"lm_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, machine-learning, matplotlib",
"url": null
} |
python, machine-learning, matplotlib
import seaborn as sns
import numpy as np
def plot_correlation_matrix(df, decimal=2, **kwargs):
kwargs["cmap"] = kwargs.get("cmap", "vlag")
kwargs["center"] = kwargs.get("center", 0) # 0 will be white if you use vlag cmap
kwargs["fmt"] = kwargs.get("fmt", f".{decimal}f")
kwargs["vmin"] = kwargs.get("vmin", -1) # specify the minimum value for the color map
kwargs["vmax"] = kwargs.get("vmax", 1) # specify the maximum value for the color map
kwargs["cbar"] = kwargs.get("cbar", False) # specify whether or not to display a color bar
kwargs["square"] = kwargs.get("square", True) # specify whether or not to force the plot to be a square
kwargs["linecolor"] = kwargs.get("linecolor", "gray") # specify the color of the lines separating the cells
kwargs["linewidth"] = kwargs.get("linewidth", 0.5) # specify the width of the lines separating the cells
kwargs["xticklabels"] = kwargs.get("xticklabels", True) # specify whether or not to display x-axis labels
kwargs["yticklabels"] = kwargs.get("yticklabels", True) # specify whether or not to display y-axis labels
kwargs["annot_kws"] = kwargs.get("annot_kws", {"fontsize": 8}) # specify additional formatting options for the annotation text
corr = df.corr()
corr_reduced = corr.iloc[1:,:-1] # No need for first row, last column
mask = np.triu_indices(corr_reduced.shape[0], k=1)
corr_reduced[mask] = 0
ax = sns.heatmap(corr_reduced, annot=True, **kwargs)
ax.set_title("Correlation Matrix") # add a title to the plot
# Using the function
df_ir = sns.load_dataset("iris")
df_ir.petal_length = - df_ir.petal_length # creating negative correlation
plot_correlation_matrix(df_ir) | {
"domain": "codereview.stackexchange",
"id": 44247,
"lm_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, machine-learning, matplotlib",
"url": null
} |
rust, lexical-analysis
Title: top-down lexer in rust
Question: the other day, i decided to build a top-down lexer in rust, just for fun.
this is what i have so far:
use std::str::Chars;
use std::env;
use std::fs;
#[derive(Debug, Clone)]
enum Op {
Plus,
Minus,
Multiply,
Divide,
Modulo,
Equal,
Not,
NotEqual,
Greater,
GreaterOrEqual,
Less,
LessOrEqual,
}
#[derive(Debug, Clone)]
enum TokenKind {
Opr(Op),
Ident(String),
Str(String),
Num(String),
}
#[derive(Debug, Clone)]
struct Lexer<'a> {
// string containing entire program
source: &'a str,
// the peekable character
peek: Option<char>,
// the characters iterator
chars: Chars<'a>,
// utf-8 position in the string
pos: usize,
// the bottom two are for error reporting/debugging
row: usize,
col: usize
}
#[allow(unused)]
impl<'a> Lexer<'a> {
fn new(source: &'a str) -> Self {
let mut chars = source.chars();
Self {
source,
peek: chars.next(),
chars,
pos: 0,
row: 1,
col: 1
}
}
#[inline]
fn position(&self) -> (usize, usize) {
(self.row, self.col)
}
#[inline]
fn is_over(&self) -> bool {
self.peek().is_none()
}
#[inline]
fn bump(&mut self) {
if let Some(ch) = self.chars.next() {
self.pos += ch.len_utf8();
self.col += 1;
if ch == '\n' {
self.col = 0;
self.row += 1;
}
self.peek = Some(ch);
} else {
self.peek = None;
}
}
#[inline]
fn peek(&self) -> Option<char> {
self.peek
} | {
"domain": "codereview.stackexchange",
"id": 44248,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, lexical-analysis",
"url": null
} |
rust, lexical-analysis
#[inline]
fn peek(&self) -> Option<char> {
self.peek
}
#[inline]
fn unicode_escape(&mut self, ch: char) -> Option<char> {
// e.g. \n \t \u{...}
let res = match ch {
'n' => '\n',
't' => '\t',
'r' => '\r',
'u' => todo!("implement unicode character codes"),
'x' => todo!("implement hex character codes"),
other => other
};
Some(res)
}
fn trim_ident(&mut self) -> TokenKind {
let start_pos = self.pos;
while let Some(s) = self.peek() {
if !(s.is_alphanumeric() || s == '_') {
break;
}
self.bump();
}
TokenKind::Ident(self.source[start_pos..self.pos].to_owned())
}
fn trim_number(&mut self) -> TokenKind {
let start_pos = self.pos;
while let Some(s) = self.peek() {
if !s.is_numeric() {
break;
}
self.bump();
}
TokenKind::Num(self.source[start_pos..self.pos].to_owned())
}
fn trim_string(&mut self) -> TokenKind {
self.bump();
let start_pos = self.pos;
while let Some(s) = self.peek() {
if s == '"' {
break
}
if s == '\\' {
self.bump();
}
self.bump();
}
if self.is_over() {
todo!("Could not lex string");
}
self.bump();
TokenKind::Str(self.source[start_pos..self.pos-1].to_owned())
}
#[inline]
fn trim_comment(&mut self) {
while let Some(s) = self.peek() {
if s == '\n' {
self.row = 0;
self.col += 1;
break
}
self.bump();
}
} | {
"domain": "codereview.stackexchange",
"id": 44248,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, lexical-analysis",
"url": null
} |
rust, lexical-analysis
#[inline]
fn trim_block_comment(&mut self) {
let mut recursion: usize = 1;
while let Some(s) = self.next() {
match s {
'\n' => {
self.row = 0;
self.col += 1;
},
'/' => {
if let Some('*') = self.peek() {
self.bump();
recursion += 1;
}
},
'*' => {
if let Some('/') = self.peek() {
self.bump();
recursion -= 1;
}
}
_ => {},
}
if recursion == 0 {
break
}
}
}
#[inline]
fn trim_whitespace(&mut self) {
while let Some(s) = self.peek() {
if !s.is_whitespace() {
break;
}
self.bump();
}
}
#[inline]
fn next_char(&mut self) -> Option<char> {
let peek = self.peek;
self.bump();
peek
}
}
impl<'a> Iterator for Lexer<'a> {
type Item = TokenKind; | {
"domain": "codereview.stackexchange",
"id": 44248,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, lexical-analysis",
"url": null
} |
rust, lexical-analysis
impl<'a> Iterator for Lexer<'a> {
type Item = TokenKind;
fn next(&mut self) -> Option<TokenKind> {
loop {
self.trim_whitespace();
return match self.peek()? {
x if x.is_alphabetic() => return Some(self.trim_ident()),
x if x.is_numeric() => return Some(self.trim_number()),
'"' => {
Some(self.trim_string())
},
'+' => {
self.bump();
Some(TokenKind::Opr(Op::Plus))
},
'-' => {
self.bump();
Some(TokenKind::Opr(Op::Minus))
},
'*' => {
self.bump();
Some(TokenKind::Opr(Op::Multiply))
},
'/' => {
self.bump();
if let Some('/') = self.peek() {
self.trim_comment();
continue;
}
if let Some('*') = self.peek() {
self.trim_block_comment();
continue;
}
Some(TokenKind::Opr(Op::Divide))
},
'%' => { | {
"domain": "codereview.stackexchange",
"id": 44248,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, lexical-analysis",
"url": null
} |
rust, lexical-analysis
self.bump();
Some(TokenKind::Opr(Op::Modulo))
},
'=' => {
self.bump();
Some(TokenKind::Opr(Op::Equal))
},
'!' => {
self.bump();
if let Some('=') = self.peek() {
self.bump();
Some(TokenKind::Opr(Op::NotEqual))
} else {
Some(TokenKind::Opr(Op::Not))
}
},
'>' => {
self.bump();
if let Some('=') = self.peek() {
self.bump();
Some(TokenKind::Opr(Op::GreaterOrEqual))
} else {
Some(TokenKind::Opr(Op::Greater))
}
},
'<' => {
self.bump();
if let Some('=') = self.peek() {
self.bump();
Some(TokenKind::Opr(Op::LessOrEqual))
} else {
Some(TokenKind::Opr(Op::Less))
}
},
_ => None
};
}
}
}
macro_rules! elapsed {
($($code:tt)*) => {
{
let start = std::time::Instant::now();
$($code)*;
println!("Time elapsed is: {:?}", start.elapsed());
}
}
}
fn main() {
for (i, arg) in env::args().enumerate() {
if i == 0 { continue }
let file = fs::read_to_string(arg).expect("failed to read file");
let lexer: Lexer<'_> = Lexer::new(&file);
elapsed!(for tok in lexer {
//println!("{tok:?}");
})
}
} | {
"domain": "codereview.stackexchange",
"id": 44248,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, lexical-analysis",
"url": null
} |
rust, lexical-analysis
HOWEVER i am sure there are many ways i could improve this code, readability and performance-wise. for instance, the loop {} in Lexer::next should be removed, but that messes up comments. also, as a side note, whenever i see other people implement lexers, their .peek() method clones the chars iterator and then calls .next(). my version stores peek as a separate value. can you tell me which is better?
EXAMPLES
"Hello, World!" -> Str("Hello, World!")
36 -> Num("36")
/* /* nested block comment */ */ -> nothing
foo_bar_baz_23 -> Ident("foo_bar_baz_23")
+ - / * % = ! != < > <= >= -> Opr(Plus) Opr(Minus) Opr(Divide) Opr(Multiply) Opr(Modulo) ...
```
Answer: Instead of using .chars() and keeping track of pos I suggest using char_indices() which gives you an iterator over tuples of the position and char.
Instead of carefully tracking row and col in bump as part of the lexer, I'd create a custom iterator on top of char_indices() which iterates over something like:
struct CharInfo {
ch: char,
pos: usize,
row: usize,
col: usize
}
Instead of having a peek member in the lexer, I'd use a .peekable() on the CharInfo iterator to have an iterator that I could peek into.
Alternately, I might not use a peeking technique here. In this case your iterator is trivially cloneable. You can rewind the iterator by using a combination of .clone() and overwriting.
For example, with a peeking approach, you might use next_if to conditionally pull chars out of while they are whitespace.
loop {
if self.chars.peek().map_or(false, |x| x.ch.is_whitespace()) {
self.next(); // consume whitespace
}
}
With a cloning approach, you might do:
loop {
let current = self.chars.clone();
if !self.chars.next().map_or(false, |x| x.ch.is_whitespace()) {
self.chars = current;
break;
}
} | {
"domain": "codereview.stackexchange",
"id": 44248,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, lexical-analysis",
"url": null
} |
rust, lexical-analysis
But either way, you might get good mileage out of iterator methods (which you can use because you use a peekable iterator), this includes the builtin methods, methods from itertools or possibly other crates. | {
"domain": "codereview.stackexchange",
"id": 44248,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, lexical-analysis",
"url": null
} |
python, strings, formatting, natural-language-processing
Title: Short Text Pre-processing
Question: For educational purpose I am preprocessing multiple short texts containing the description of the symptoms of cars fault.
The text is written by humans and is rich in misspelling, capital letters and other stuff.
I wanted to write a short pre-processing function and I have three questions:
Why I get two different results based on how I format the re.escape() (the first one is the correct piece of code)
Can I adapt to f-string formatting in this section re.compile('[%s]' % ?re.escape(string.punctuation)).sub(' ', text)
There is any way I improve readability and performance of this code?
example = "This, is just an example! Nothing serious :) "
#convert to lowercase, strip and remove punctuations
def preprocess(text):
"""convert to lowercase, strip and remove punctuations"""
text = text.lower()
text=text.strip()
text=re.compile('<.*?>').sub('', text)
text = re.compile('[%s]' % re.escape(string.punctuation)).sub(' ', text)
text = re.sub('\s+', ' ', text)
text = re.sub(r'\[[0-9]*\]',' ',text)
text=re.sub(r'[^\w\s]', '', str(text).lower().strip())
text = re.sub(r'\d',' ',text)
text = re.sub(r'\s+',' ',text)
return text
The wrong one:
#convert to lowercase, strip and remove punctuations
def preprocess(text):
"""convert to lowercase, strip and remove punctuations"""
text = text.lower()
text=text.strip()
text=re.compile('<.*?>').sub('', text)
escaping = re.escape(string.punctuation)
test = re.compile('[{}s]'.format(escaping)).sub(' ',text)
text = re.sub('\s+', ' ', text)
text = re.sub(r'\[[0-9]*\]',' ',text)
text=re.sub(r'[^\w\s]', '', str(text).lower().strip())
text = re.sub(r'\d',' ',text)
text = re.sub(r'\s+',' ',text)
return text | {
"domain": "codereview.stackexchange",
"id": 44249,
"lm_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, strings, formatting, natural-language-processing",
"url": null
} |
python, strings, formatting, natural-language-processing
Answer: To be PEP-8 compliant, you may wish to review your spacing. Specifically, text=text.strip() into text = text.strip() with spaces surrounding the assignment operator. This is done in some locations within your code, but not others - I would recommend consistency.
Some parts of your code are redundant - in this statement text = re.compile('[%s]' % re.escape(string.punctuation)).sub(' ', text) you are removing square brackets (and additional characters). In a following line text = re.sub(r'\[[0-9]*\]',' ',text) you are removing digits which are surrounded by square brackets. But since you have already removed square brackets, it will never find anything which matches this condition!
Also, be aware that \ is an escape character. When you wish to use it as itself within a regular expression, it must be escaped itself \\ or a raw string must be used. This occurs in this line of code: text = re.sub('\s+', ' ', text)
re.compile() followed by .sub() could just be re.sub(). You are not saving the compiled regular expression to use again.
Characters can be replaced with spaces - if your text ended in a number, it would be replaced by a space at the end of your string. You want text = text.strip() to be one of the last things your code does.
text=re.sub(r'[^\w\s]', '', str(text).lower().strip()) has redundancy - you already converted everything to lowercase, so you do not need another .lower() here. Your variable, text, is already a string, and so str(text) is converting it unnecessarily. As mentioned, you want .strip() at the end - if doing so, the one in this block of code is not needed.
You should use type hints: def preprocess(text: str) -> str: to document that the function takes type string, and returns type string.
Reworked code:
import string
import re
def preprocess(text: str) -> str:
"""convert to lowercase, strip and remove punctuations""" | {
"domain": "codereview.stackexchange",
"id": 44249,
"lm_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, strings, formatting, natural-language-processing",
"url": null
} |
python, strings, formatting, natural-language-processing
def preprocess(text: str) -> str:
"""convert to lowercase, strip and remove punctuations"""
text = text.lower()
text = re.sub('<.*?>', '', text)
text = re.sub(f'[{re.escape(string.punctuation)}]', ' ', text)
text = re.sub(r'[^\w\s]', '', text)
text = re.sub(r'[\d\s]+', ' ', text)
text = text.strip()
return text | {
"domain": "codereview.stackexchange",
"id": 44249,
"lm_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, strings, formatting, natural-language-processing",
"url": null
} |
react.js, react-native
Title: Preferable ways for reusing input components in react native?
Question: I am using react native 0.68.5
When I call the renderReusableTextInput method in Main.js I am sending all the styles including the needed and unneeded styles. This can lead performance penalty.
So, is there a way that I can send the only needed styles to the renderReusableTextInput method.
I also want to know is the code reusing approach of mine correct or there are better ways.
I have the following code-logic structure:
(i) A Reusable component; It has only structure no style or state
(ii) A file that includes reusable methods
(iii) The Main component, which contains components, styles and states
ReusableTextInput.js
// import ...
const ReusableTextInput = forwardRef(({
inputName,
inputLabel,
inputValue,
secureTextEntry,
textInputContainerWarperStyle,
textInputContainerStyle,
textInputLabelStyle,
textInputStyle,
textInputHelperStyle,
textInputErrorStyle,
helperText,
inputError,
onFocus,
onChangeText,
onBlur,
}, inputRef) => {
return (
<View style={[textInputContainerWarperStyle]}>
<View style={[textInputContainerStyle]}>
<Text style={[textInputLabelStyle]}>
{inputLabel}
</Text>
<TextInput
ref={(elm) => inputRef[inputName] = elm}
style={[textInputStyle]}
value={inputValue}
secureTextEntry={secureTextEntry}
onChangeText={onChangeText}
onFocus={onFocus}
onBlur={onBlur}
/>
</View>
{
((inputRef[inputName]) && (inputRef[inputName].isFocused()) && (!inputValue))
?
<Text style={[textInputHelperStyle]}>
{helperText}
</Text>
:
null
}
{
((inputError) && (inputValue))
?
<Text style={[textInputErrorStyle]}>
{inputError}
</Text>
:
null
}
</View>
);
});
export default memo(ReusableTextInput);
reusableMethods.js | {
"domain": "codereview.stackexchange",
"id": 44250,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, react-native",
"url": null
} |
react.js, react-native
export default memo(ReusableTextInput);
reusableMethods.js
// import ...
const handleFocus = (state, setState, styles) => {
// here styles contains all style key which I do not want
// I only want the required styles
const stateData = { ...state };
stateData.styleNames.textInputContainer = {
...styles.textInputContainer,
...styles[`${stateData.name}ExtraTextInputContainer`],
...styles.textInputContainerFocus,
};
stateData.styleNames.textInputLabel = {
...styles.textInputLabel,
...styles[`${stateData.name}ExtraTextInputLabel`],
...styles.textInputLabelFocus,
};
stateData.styleNames.textInput = {
...styles.textInput,
...styles[`${stateData.name}ExtraTextInput`],
...styles.textInputFocus,
};
// other logics...
setState(stateData);
};
const handleChangeText = (state, setState, text) => {
const stateData = { ...state };
// individual validation
const schemaData = Joi.object().keys(stateData.validationObj); // I used Joi for validation
const inputData = { [stateData.name]: text };
const options = { abortEarly: false, errors: { label: false } };
const result = schemaData.validate(inputData, options);
// -----
stateData.error = (result.error) ? result.error.details[0].message : '';
stateData.value = text;
// other logics...
setState(stateData);
};
const handleBlur = (state, setState, styles) => {
// here styles contains all style key which I do not want
// I only want the required styles
const stateData = { ...state }; | {
"domain": "codereview.stackexchange",
"id": 44250,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, react-native",
"url": null
} |
react.js, react-native
const stateData = { ...state };
if (stateData.value) {
stateData.styleNames.textInputContainer = {
...styles.textInputContainer,
...styles[`${stateData.name}ExtraTextInputContainer`],
...styles.textInputContainerFocus,
...styles[`${stateData.name}ExtraTextInputContainerFocus`],
...styles.textInputContainerBlurText,
...styles[`${stateData.name}ExtraTextInputContainerBlurText`],
};
stateData.styleNames.textInputLabel = {
...styles.textInputLabel,
...styles[`${stateData.name}ExtraTextInputLabel`],
...styles.textInputLabelFocus,
...styles[`${stateData.name}ExtraTextInputLabelFocus`],
...styles.textInputLabelBlurText,
...styles[`${stateData.name}ExtraTextInputLabelBlurText`],
};
stateData.styleNames.textInput = {
...styles.textInput,
...styles[`${stateData.name}ExtraTextInput`],
...styles.textInputFocus,
...styles[`${stateData.name}ExtraTextInputFocus`],
...styles.textInputBlurText,
...styles[`${stateData.name}ExtraTextInputBlurText`],
};
}
else {
stateData.styleNames.textInputContainer = { ...styles.textInputContainer, ...styles[`${stateData.name}ExtraTextInputContainer`] };
stateData.styleNames.textInputLabel = { ...styles.textInputLabel, ...styles[`${stateData.name}ExtraTextInputLabel`] };
stateData.styleNames.textInput = { ...styles.textInput, ...styles[`${stateData.name}ExtraTextInput`] };
}
// other logics...
setState(stateData);
};
// other methods...
export const renderReusableTextInput = (
state,
setState,
inputRef,
styles, // contains all the styles from Main component
) => { | {
"domain": "codereview.stackexchange",
"id": 44250,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, react-native",
"url": null
} |
react.js, react-native
return (
<ReusableTextInput
inputName={state.name}
inputLabel={state.label}
inputValue={state.value}
inputRef={inputRef}
secureTextEntry={state.secureTextEntry}
textInputContainerWarperStyle={{...styles.textInputContainerWarper, ...styles[`${state.name}ExtraTextInputContainerWarper`]}}
textInputContainerStyle={state.styleNames.textInputContainer}
textInputLabelStyle={state.styleNames.textInputLabel}
textInputStyle={state.styleNames.textInput}
textInputHelperStyle={{...styles.textInputHelper, ...styles[`${state.name}ExtraTextInputHelper`]}}
textInputErrorStyle={{...styles.textInputError, ...styles[`${state.name}ExtraTextInputError`]}}
helperText={state.helperText}
inputError={state.error}
onFocus={() => handleFocus(state, setState, styles)}
onChangeText={(text) => handleChangeText(state, setState, text)}
onBlur={() => handleBlur(state, setState, styles)}
/>
);
};
Main.js
// import Joi from 'joi';
// import { joiPasswordExtendCore } from 'joi-password';
// import { renderReusableTextInput } from ''; ...
const schema =
{
email: Joi.string().strict()
.case("lower")
.min(5)
.max(30)
.email({ minDomainSegments: 2, tlds: { allow: ["com", "net", "org"] } })
.required(),
countryCode: // Joi.string()...,
phoneNumber: // Joi.string()...,
password: // Joi.string()...,
// ...
};
const Main = () => {
const { width: windowWidth, height: windowHeight, scale, fontScale } = useWindowDimensions();
const minimumWidth = (windowWidth <= windowHeight) ? windowWidth : windowHeight;
const styles = useMemo(() => currentStyles(minimumWidth), [minimumWidth]); | {
"domain": "codereview.stackexchange",
"id": 44250,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, react-native",
"url": null
} |
react.js, react-native
const styles = useMemo(() => currentStyles(minimumWidth), [minimumWidth]);
const [email, setEmail] = useState({
name: 'email', // unchangeable
label: 'Email', // unchangeable
value: '',
error: '',
validationObj: { email: schema.email }, // unchangeable
trailingIcons: [require('../../file/image/clear_trailing_icon.png')], // unchangeable
helperText: 'only .com, .net and .org allowed', // unchangeable
styleNames: {
textInputContainer: { ...styles.textInputContainer, ...styles.emailExtraTextInputContainer },
textInputLabel: { ...styles.textInputLabel, ...styles.emailExtraTextInputLabel },
textInput: { ...styles.textInput, ...styles.emailExtraTextInput },
},
});
const [phoneNumber, setPhoneNumber] = useState({
});
const [countryCode, setCountryCode] = useState({
});
const [password, setPassword] = useState({
});
// ...
const references = useRef({});
return (
<View style={[styles.mainContainer]}>
{
useMemo(() => renderReusableTextInput(email, setEmail, references.current, styles), [email, minimumWidth])
}
</View>
);
}
export default memo(Main);
const styles__575 = StyleSheet.create({
// 320 to 575
mainContainer: {
},
textInputContainerWarper: {
},
emailExtraTextInputContainerWarper: {
},
countryCodeExtraTextInputContainerWarper: {
},
phoneNumberExtraTextInputContainerWarper: {
},
passwordExtraTextInputContainerWarper: {
},
textInputContainer: {
},
emailExtraTextInputContainer: {
},
textInputContainerFocus: {
},
textInputContainerBlurText: {
},
textInputLabel: {
},
emailExtraTextInputLabel: {
},
textInputLabelFocus: {
},
textInputLabelBlurText: {
},
textInput: {
},
emailExtraTextInput: {
},
textInputFocus: {
},
textInputBlurText: {
},
textInputHelper: {
},
emailExtraTextInputHelper: {
},
textInputError: {
},
emailExtraTextInputError: {
},
// other styles...
}); | {
"domain": "codereview.stackexchange",
"id": 44250,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, react-native",
"url": null
} |
react.js, react-native
// other styles...
});
const styles_576_767 = StyleSheet.create({
// 576 to 767
});
const styles_768_ = StyleSheet.create({
// 768; goes to 1024;
});
const currentStyles = (width, stylesInitial = { ...styles__575 }, styles576 = { ...styles_576_767 }, styles768 = { ...styles_768_ }) => {
let styles = {};
if (width < 576) {
}
else if ((width >= 576) && (width < 768)) {
}
else if (width >= 768) {
}
return styles;
};
Answer: First, I think you want global styles, so that you can access it from anywhere and you can also be able to execute needed code.
Make sure you use useMemo, useCallback in right manner, for better performance.
Move all Schema and Styles and Methods of your screens inside the reusableMethods.js file (at most case). It will act like the controller of all screens of your app, also make a demo method which return a tiny component and this method execute another method, so that you can get styles for different dimentions(see below code)
Store only changeable and needed properties in state variables.
Is code reusing approach of yours, correct? I can't say about that. I will say that it depends on developer choice.
you can try like below:
reusableMethods.js
// import all schema, style variants, utility methods and other
let screenStyles = {};
const executeDimensionBasedMethods = (width, screenName) => {
if (screenName === 'a_screen_name') screenStyles[screenName] = currentStyles(width, otherParameter);
// else if()
// ...
};
export const renderDimension = (width, screenName) => {
executeDimensionBasedMethods(width, screenName);
return (
<Text style={{ width: 0, height: 0 }}></Text>
);
};
// all method definitions and logics | {
"domain": "codereview.stackexchange",
"id": 44250,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, react-native",
"url": null
} |
react.js, react-native
// all method definitions and logics
export const renderReusableTextInput = (
state,
setState,
inputRef,
screenName
) => {
return (
<ReusableTextInput
inputName={state.name}
inputLabel={state.label}
inputValue={state.value}
inputRef={inputRef}
secureTextEntry={state.secureTextEntry}
textInputContainerWarperStyle={{ ...screenStyles[screenName].textInputContainerWarper, ...screenStyles[screenName][`${state.name}ExtraTextInputContainerWarper`] }}
textInputContainerStyle={state.styleNames.textInputContainer || { ...screenStyles[screenName].textInputContainer }
textInputLabelStyle={state.styleNames.textInputLabel || { ...screenStyles[screenName].textInputLabel }
textInputStyle={state.styleNames.textInput || { ...screenStyles[screenName].textInput }
textInputHelperStyle={{ ...screenStyles[screenName].textInputHelper, ...screenStyles[screenName][`${state.name}ExtraTextInputHelper`] }}
textInputErrorStyle={{ ...screenStyles[screenName].textInputError, ...screenStyles[screenName][`${state.name}ExtraTextInputError`] }}
helperText={state.helperText}
inputError={state.error}
onFocus={() => handleFocus(state, setState, screenStyles[screenName])}
onChangeText={(text) => handleChangeText(state, setState, text)}
onBlur={() => handleBlur(state, setState, screenStyles[screenName])}
/>
);
};
Main.js
const Main = () => {
const { width: windowWidth, height: windowHeight} = useWindowDimensions();
const minimumWidth = (windowWidth <= windowHeight) ? windowWidth : windowHeight; | {
"domain": "codereview.stackexchange",
"id": 44250,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, react-native",
"url": null
} |
react.js, react-native
const minimumWidth = (windowWidth <= windowHeight) ? windowWidth : windowHeight;
const [email, setEmail] = useState({
name: 'email', // unchangeable
label: 'Email', // unchangeable
value: '',
error: '',
trailingIcons: [require('../../file/image/clear_trailing_icon.png')], // unchangeable
helperText: 'only .com, .net and .org allowed', // unchangeable
styleNames: {
textInputContainer: undefined,
textInputLabel: undefined,
textInput: undefined,
},
});
// other states
const references = useRef({});
return (
<>
{
useMemo(() => renderDimension(minimumWidth), [minimumWidth])
}
<View style={{ // inline style}}>
{
useMemo(() => renderReusableTextInput(email, setEmail, references.current, 'nameofscreen'), [email, minimumWidth])
}
</View>
</>
}
export default memo(Main);
``` | {
"domain": "codereview.stackexchange",
"id": 44250,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, react-native",
"url": null
} |
beginner, verilog
Title: Variable output stream delay no shift register | {
"domain": "codereview.stackexchange",
"id": 44251,
"lm_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, verilog",
"url": null
} |
beginner, verilog
Question: I'm looking to improve my Verilog coding form by reducing utilization and learning any tricks more experienced Verilogers may know.
This module takes in a pulse data stream with pulses occurring between 500 and 12500 clk cycles, and it needs to delay the stream by a specified number of clk cycles between 500 and 12500 clk cycles. But without using a 12500 bit shift register.
The process I was thinking to use was have 25, 14 bit registers as memory to handle the worst case of a pulse every 500 cycles and max delay of 12500 cycles, count the cycles to each pulse store them in memory, wait for the delay and output the pulses according to what's stored in memory. And I needed to add that unusedStorage parameter in order to ensure it always used each stored memory delay only once.
The current code is shown below:
module data_delay_counter(
input clk,
input en,
input [13:0] ShiftNum,
input s_IN,
output reg s_OUT
);
// what is the minimum pulse rate (ie every 12500 clk cycles)
// what is the maximum pulse rate (ie every 500 clk cycles)
// what is the maximum delay (ie 12500 clk cycles)
// if maximum delay is 12500, and maximum pulse rate is 500, and minimum pulse rate is 12500
// then need to store a number up to 12500 so 14 bits, and store a maximum of 12500/500 = 25 numbers
// need memory that stores 25, 14 bit numbers
// if operating at a pulse every 500 cycles then max delay must be kept at 12500, but increasing cycles between pulses allows the delay to be increased
/////////////////
// counting phase
reg [13:0] cyclesToInputPulse = 0; // counted clk cycles before a pulse
// storage phase
reg [4:0] memoryIndxWrite = 0; // index to write pulse information to
reg [13:0] storage [0:24]; // memory for pulse information
// delay phase
reg [13:0] delayCounter = 0; // output delay counter
// output phase | {
"domain": "codereview.stackexchange",
"id": 44251,
"lm_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, verilog",
"url": null
} |
beginner, verilog
// delay phase
reg [13:0] delayCounter = 0; // output delay counter
// output phase
reg [4:0] memoryIndxRead = 0; // index to read out pulse information from
reg [13:0] cyclesToOutputPulse = 0; // counted clk cycles up to number read out from storage
reg [24:0] unusedStorage = 0; // specifies if storage pulse info has been used or not, 1 for unused 0 for used
// old shiftnum
reg [13:0] oldShiftNum = 0; // stores the old ShiftNum to check if it has changed
always @(posedge clk) begin
if(ShiftNum != oldShiftNum) begin // check if ShiftNum has changed and reset parameters
oldShiftNum = ShiftNum;
cyclesToInputPulse = 0;
memoryIndxWrite = 0;
delayCounter = 0;
cyclesToOutputPulse = 0;
memoryIndxRead = 0;
unusedStorage = 0;
end
else if (en == 1) begin
// counting phase
if (s_IN != 1)
cyclesToInputPulse = cyclesToInputPulse + 14'd1;
else begin
// storage phase
cyclesToInputPulse = cyclesToInputPulse + 14'd1;
storage[memoryIndxWrite] = cyclesToInputPulse;
cyclesToInputPulse = 14'd0;
// when storage is written to unused storage at that index is set to 1, signifying its unused or "fresh"
unusedStorage[memoryIndxWrite] = 1;
memoryIndxWrite = memoryIndxWrite + 14'd1;
if (memoryIndxWrite == 25)
memoryIndxWrite = 14'd0;
end
// delay phase
if (delayCounter != ShiftNum)
delayCounter = delayCounter + 1;
// output phase
else begin
// counts up to delay specified in storage and outputs pulse if stored delay is unused
cyclesToOutputPulse = cyclesToOutputPulse + 14'd1; | {
"domain": "codereview.stackexchange",
"id": 44251,
"lm_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, verilog",
"url": null
} |
beginner, verilog
cyclesToOutputPulse = cyclesToOutputPulse + 14'd1;
if (cyclesToOutputPulse == storage[memoryIndxRead] && unusedStorage[memoryIndxRead] == 1) begin
s_OUT = 1;
cyclesToOutputPulse = 14'd0;
// specifies stored value has been used for an output pulse and sets unusedStorage at that indx to zero
unusedStorage[memoryIndxRead] = 0;
memoryIndxRead = memoryIndxRead + 14'd1;
if (memoryIndxRead == 25)
memoryIndxRead = 0;
end
else begin
s_OUT = 0;
end
end
end
else begin
cyclesToInputPulse = 0;
memoryIndxWrite = 0;
delayCounter = 0;
cyclesToOutputPulse = 0;
memoryIndxRead = 0;
unusedStorage = 0;
s_OUT = 0;
end
end
endmodule | {
"domain": "codereview.stackexchange",
"id": 44251,
"lm_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, verilog",
"url": null
} |
beginner, verilog
And the simulation results are shown here and don't change much pre or post synthesis:
There's lots for me to improve on. I know nonblocking assignments should be used as much as possible within clocked always blocks. In these situations it seems like I need to use a stored value then update its contents. I don't really understand how to use a nonblocking assignment in a situation like that. I appreciate all the guidance. I'm new to Verilog and appreciate everyone taking the time to help me improve
Answer: Generally speaking, the code has consistent layout and is easy to understand. It uses descriptive variable names and comments. I don't see much room for improvement.
The recommended Verilog coding style is to use nonblocking assignments (<=) to describe sequential logic. Since your code consists of a single always block, and this block is sequential (it has posedge clk), all the assignments should be nonblocking. For example:
oldShiftNum <= ShiftNum;
This recommendation is mainly to achieve predictable simulation results.
The remaining suggestions are purely for improved coding style.
I see repeated use of fixed numeric constants 13 and 14. You could consider replacing those with a named constant. For example:
parameter WIDTH = 14;
// ...
reg [WIDTH-1:0] cyclesToInputPulse | {
"domain": "codereview.stackexchange",
"id": 44251,
"lm_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, verilog",
"url": null
} |
beginner, verilog
This is a standard practice. You would use a name that is more descriptive in your design (but WIDTH may suffice here). It is a common convention to use all caps for constant names so that they stand out from variable signal names. Using names instead of numbers can make the code easier to understand. It also makes the code easier to change. For example, if you realize you need 16 bits instead of 14, you can just change one line of code instead of several lines.
When I see a line that has several operators, I sometimes find that hard to read. I prefer to use extra parentheses to separate the individual terms. For example:
if ((cyclesToOutputPulse == storage[memoryIndxRead]) && (unusedStorage[memoryIndxRead] == 1)) begin
I added 2 sets of extra parens. Sometimes this also avoids functional bugs due to operator precedence.
You have one very long comment line. You should definitely split that up into at least 2 lines.
When you have multiple single-line comments one after the other like that, you could convert that into a block comment using /**/. I find block comments to be easier to read and to maintain.
Currently, all your code is contained in a single always block. This is fine, especially since it fits all on one screen. If you need to make changes to the design to add logic, I would consider splitting it up into multiple always blocks. It could make the design easier to understand and maintain in the future.
SystemVerilog features
You could start adopting some newer features of the language. This may require you to explicitly enable these features in your tool set (or they may even be enabled by default).
One feature simplifies the design be replacing zero constants like 14'd0 with '0. This eliminates the need to specify the bit width.
Another feature is the always_ff keyword. Replace:
always @(posedge clk) begin
with:
always_ff @(posedge clk) begin | {
"domain": "codereview.stackexchange",
"id": 44251,
"lm_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, verilog",
"url": null
} |
beginner, verilog
with:
always_ff @(posedge clk) begin
This better conveys the design intent, and it also allows tools to perform additional checks.
Refer to the IEEE Std 1800-2017 document for further details.
Here is a modified version of your code, employing several (but not all) the suggestions above. CAUTION: the code compiles without errors, but I did not simulate it.
I made a couple other style changes.
All the if/else clauses now use begin/end for consistency. I also prefer to keep end else begin on one line to save some vertical whitespace.
/*
what is the minimum pulse rate (ie every 12500 clk cycles)
what is the maximum pulse rate (ie every 500 clk cycles)
what is the maximum delay (ie 12500 clk cycles)
if maximum delay is 12500, and maximum pulse rate is 500, and minimum pulse rate is 12500
then need to store a number up to 12500 so 14 bits, and store a maximum of 12500/500 = 25 numbers
need memory that stores 25, 14 bit numbers
if operating at a pulse every 500 cycles then max delay must be kept at 12500,
but increasing cycles between pulses allows the delay to be increased
*/
module data_delay_counter (
input clk,
input en,
input [13:0] ShiftNum,
input s_IN,
output reg s_OUT
); | {
"domain": "codereview.stackexchange",
"id": 44251,
"lm_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, verilog",
"url": null
} |
beginner, verilog
// counting phase
reg [13:0] cyclesToInputPulse = 0; // counted clk cycles before a pulse
// storage phase
reg [4:0] memoryIndxWrite = 0; // index to write pulse information to
reg [13:0] storage [0:24]; // memory for pulse information
// delay phase
reg [13:0] delayCounter = 0; // output delay counter
// output phase
reg [4:0] memoryIndxRead = 0; // index to read out pulse information from
reg [13:0] cyclesToOutputPulse = 0; // counted clk cycles up to number read out from storage
reg [24:0] unusedStorage = 0; // specifies if storage pulse info has been used or not, 1 for unused 0 for used
// old shiftnum
reg [13:0] oldShiftNum = 0; // stores the old ShiftNum to check if it has changed
always @(posedge clk) begin
if (ShiftNum != oldShiftNum) begin // check if ShiftNum has changed and reset parameters
oldShiftNum <= ShiftNum;
cyclesToInputPulse <= 0;
memoryIndxWrite <= 0;
delayCounter <= 0;
cyclesToOutputPulse <= 0;
memoryIndxRead <= 0;
unusedStorage <= 0;
end else if (en) begin
// counting phase
if (s_IN != 1) begin
cyclesToInputPulse <= cyclesToInputPulse + 14'd1;
end else begin
// storage phase
cyclesToInputPulse <= cyclesToInputPulse + 14'd1;
storage[memoryIndxWrite] <= cyclesToInputPulse;
cyclesToInputPulse <= 14'd0;
// when storage is written to unused storage at that index is set to 1, signifying its unused or "fresh"
unusedStorage[memoryIndxWrite] <= 1;
memoryIndxWrite <= memoryIndxWrite + 14'd1;
if (memoryIndxWrite == 25) begin
memoryIndxWrite <= 14'd0;
end
end
// delay phase
if (delayCounter != ShiftNum) begin | {
"domain": "codereview.stackexchange",
"id": 44251,
"lm_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, verilog",
"url": null
} |
beginner, verilog
end
// delay phase
if (delayCounter != ShiftNum) begin
delayCounter <= delayCounter + 1;
// output phase
end else begin
// counts up to delay specified in storage and outputs pulse if stored delay is unused
cyclesToOutputPulse <= cyclesToOutputPulse + 14'd1;
if ((cyclesToOutputPulse == storage[memoryIndxRead]) && (unusedStorage[memoryIndxRead] == 1)) begin
s_OUT <= 1;
cyclesToOutputPulse <= 14'd0;
// specifies stored value has been used for an output pulse and sets unusedStorage at that indx to zero
unusedStorage[memoryIndxRead] <= 0;
memoryIndxRead <= memoryIndxRead + 14'd1;
if (memoryIndxRead == 25) begin
memoryIndxRead <= 0;
end
end else begin
s_OUT <= 0;
end
end
end else begin
cyclesToInputPulse <= 0;
memoryIndxWrite <= 0;
delayCounter <= 0;
cyclesToOutputPulse <= 0;
memoryIndxRead <= 0;
unusedStorage <= 0;
s_OUT <= 0;
end
end
endmodule | {
"domain": "codereview.stackexchange",
"id": 44251,
"lm_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, verilog",
"url": null
} |
python, beginner, game
Title: Spin the wheel game | {
"domain": "codereview.stackexchange",
"id": 44252,
"lm_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, game",
"url": null
} |
python, beginner, game
Question: I'm new to Python and coded this spin-the-wheel game where the user can bet on each spin of the wheel and either double their money, 1.5x their money, lose their money or keep it.
It all seems to be working fine (I think), but I was wondering if there were any improvements to the structure and efficiency of my code I could make. Or a new feature I could add.
#Spin the wheel game
bet = 0
print("=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=")
print(" Welcome to spin the wheel")
print(" With bets")
print("=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=")
print("There is 5 options on the wheel:")
print("Green doubles your money")
print("Blue loses your money")
print("Yellow 1.5x your money")
print("Red returns your money")
print("Orange loses your money")
ballance = 0
money = False
while money == False:
deposit = input("Please deposit money to play: £")
if deposit.isdigit():
deposit = int(deposit)
if deposit > 0:
print("Thank you your balance is currently: £",ballance+deposit)
money = True
ballance = deposit + ballance
else:
print("Please deposit at least £1.")
else:
print("Please enter a numerical amount.")
play = True
while play == True:
money = False
while money == False:
bet = input("Please enter how much you'd like to bet on this spin: £")
if bet.isdigit():
bet = int(bet)
if bet <= ballance:
print("Thank you, you have just bet: £",bet)
ballance = ballance - bet
money = True
else:
print("Please bet an amount that is no larger than your balance of: £",ballance)
else:
print("Please enter a numerical amount or a an amount above 0.")
colour = "green"
import random
spin = random.randint(1,5)
if spin == 1:
outcome = bet*2
elif spin == 2:
outcome = bet - bet | {
"domain": "codereview.stackexchange",
"id": 44252,
"lm_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, game",
"url": null
} |
python, beginner, game
if spin == 1:
outcome = bet*2
elif spin == 2:
outcome = bet - bet
colour = "Blue"
elif spin == 3:
outcome = bet*1.5
colour = "Yellow"
elif spin == 4:
outcome = bet
colour = "Red"
else:
outcome = bet - bet
colour = "Orange"
start = input("Hit enter to spin the wheel")
while start != "":
quit()
print("It landed on:",colour)
if outcome == 0:
print("That means you lost your bet of £",bet)
if outcome == bet:
print("You got your money back.")
if outcome > bet:
print("You made: £",outcome - bet,"So got £",outcome,"back.")
print("Your balance is now: £",ballance+outcome)
ballance = ballance+outcome
again = input("Would you like to play another round? ").lower()
if again in ["yes","y"]:
if ballance >= 1:
play = True
else:
money = False
while money == False:
deposit = input("You have run out of money. Please deposit more money to keep playing. £")
if deposit.isdigit():
deposit = int(deposit)
if deposit > 0:
print("Thank you your balance is currently: £",ballance+deposit)
ballance = deposit + ballance
money = True
else:
print("Please deposit at least £1.")
else:
print("Please enter a numerical amount.")
else:
play = False
print("Thank you for playing")
print("Your final balance was: £", ballance)
if ballance > 0:
withdraw = input("Would you like to withdraw your money? ").lower()
if withdraw in ["yes","y","please"]:
print("We have deposited your balance of £",ballance,"into your bank account.")
ballance = ballance - ballance | {
"domain": "codereview.stackexchange",
"id": 44252,
"lm_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, game",
"url": null
} |
python, beginner, game
ballance = ballance - ballance
print("Your balance is now: £",ballance)
else:
print("That's ok, we will keep your money for next time you play.") | {
"domain": "codereview.stackexchange",
"id": 44252,
"lm_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, game",
"url": null
} |
python, beginner, game
Answer: I think the biggest improvement that you can make is to use functions instead of putting all functionality in one big block of code. The main advantage of functions is that it will be easier to understand and maintain the code, and another advantage is that you can avoid global variables, which are generally considered bad practice.
Another improvement is to avoid the use of "flags" (i.e. variables such as money and play in your code) for program control. Besides that the names are not really descriptive, most programming languages have easier constructs to achieve the same. For example break or return. You will see that this makes your code shorter and simpler.
Other remarks:
Place imports at the top of your file.
In Python, it is more common to write while x: than while x == True:.
Instead of balance = balance - balance you could write balance = 0.
quit() is intended to be used in the interpreter and should not be used in scripts. They can cause problems in the future. Use sys.exit() instead.
Using pylint and/or an IDE will help you quickly identify potential coding issues and get free tips on improving your code.
Following the style guide PEP 8 will help you improve your code and make it more recognizable for others around the world.
I partly implemented above tips in the following code. It is not completely rewritten, but I think it demonstrates the above points.
# Spin the wheel game
import random
import sys
def print_intro_text():
print('=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=')
print(' Welcome to spin the wheel')
print(' With bets')
print('=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=')
print('There is 5 options on the wheel:')
print('Green doubles your money')
print('Blue loses your money')
print('Yellow 1.5x your money')
print('Red returns your money')
print('Orange loses your money') | {
"domain": "codereview.stackexchange",
"id": 44252,
"lm_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, game",
"url": null
} |
python, beginner, game
def get_deposit(old_balance=0):
while True:
deposit = input('Please deposit money to play: £')
if deposit.isdigit():
deposit = int(deposit)
if deposit > 0:
new_balance = old_balance + deposit
print('Thank you your balance is currently: £', new_balance)
return new_balance
print('Please deposit at least £1.')
else:
print('Please enter a numerical amount.')
def get_bet(balance):
while True:
bet = input('Please enter how much you\'d like to bet on this spin: £')
if bet.isdigit():
bet = int(bet)
if bet <= balance:
print('Thank you, you have just bet: £', bet)
return bet
print('Please bet an amount that is no larger than your balance of: £', balance)
else:
print('Please enter a numerical amount or a an amount above 0.')
def play(balance):
while True:
bet = get_bet(balance)
balance -= bet
# The rest of this code is left as an exercise to improve / refactor. | {
"domain": "codereview.stackexchange",
"id": 44252,
"lm_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, game",
"url": null
} |
python, beginner, game
colour = 'green'
spin = random.randint(1, 5)
if spin == 1:
outcome = bet * 2
elif spin == 2:
outcome = bet - bet
colour = 'Blue'
elif spin == 3:
outcome = bet * 1.5
colour = 'Yellow'
elif spin == 4:
outcome = bet
colour = 'Red'
else:
outcome = bet - bet # FIXME
colour = 'Orange'
start = input('Hit enter to spin the wheel')
while start != '':
sys.exit()
print('It landed on:', colour)
if outcome == 0:
print('That means you lost your bet of £', bet)
if outcome == bet:
print('You got your money back.')
if outcome > bet:
print('You made: £', outcome - bet, 'So got £', outcome, 'back.')
print('Your balance is now: £', balance + outcome)
balance = balance+outcome
again = input('Would you like to play another round? ').lower()
if again in ['yes', 'y']:
if balance < 1:
money = False
while not money:
deposit = input('You have run out of money. Please deposit more money to keep playing. £')
if deposit.isdigit():
deposit = int(deposit)
if deposit > 0:
print('Thank you your balance is currently: £', balance + deposit)
balance = deposit + balance
money = True
else:
print('Please deposit at least £1.')
else:
print('Please enter a numerical amount.')
else:
print('Thank you for playing')
print('Your final balance was: £', balance)
if balance > 0:
withdraw = input('Would you like to withdraw your money? ').lower() | {
"domain": "codereview.stackexchange",
"id": 44252,
"lm_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, game",
"url": null
} |
python, beginner, game
withdraw = input('Would you like to withdraw your money? ').lower()
if withdraw in ['yes', 'y', 'please']:
print('We have deposited your balance of £', balance, 'into your bank account.')
balance = balance - balance
print('Your balance is now: £', balance)
else:
print('That\'s ok, we will keep your money for next time you play.')
break | {
"domain": "codereview.stackexchange",
"id": 44252,
"lm_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, game",
"url": null
} |
python, beginner, game
def main():
print_intro_text()
balance = get_deposit()
play(balance)
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 44252,
"lm_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, game",
"url": null
} |
php, url-routing
Title: PHP Router For MVC with strict routing requirements
Question: I had previously asked the question here.
The response was pretty much "wow this is bad".
So I learned everything I could and wrote what I believe to be better using TDD.
The strict requirement is that the url will be parsed as /controller/action/everything/else/is/a/parameter.
So here is what I wrote:
The router class
<?php
declare(strict_types=1);
namespace xxxx\xxxx\Router;
use xxxx\xxxx\Util\StorageUtils;
class Router{
public array $defaultRoute;
public array $notFoundRoute;
public array $urlSegments;
public $controller;
public $action;
public $parameters;
public $controllerName;
public $view;
public function setDefaultRoute($controller, $action): void{
$this->defaultRoute = [$controller, $action];
}
public function setNotFoundRoute($controller, $action): void{
$this->notFoundRoute = [$controller, $action];
}
public function execute($url): void{
$this->getUrlSegments($url)
->determineController()
->createController()
->determineParameters()
->determineAction()
->executeAction()
->determineView();
}
public function executeView(){
$this->controller->initData();
if($this->controller->data != null){
extract($this->controller->data, EXTR_PREFIX_SAME, 'wddx');
}
if($this->view != null){
$viewPath = StorageUtils::getFullPath($this->getViewFile($this->controllerName, $this->view));
if($this->controller->useTemplate){
$templatePath = StorageUtils::getFullPath($this->getViewFile('Template', $this->controller->template));
require_once($templatePath);
}else{
require_once($viewPath);
}
}
$this->controller->init();
} | {
"domain": "codereview.stackexchange",
"id": 44253,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, url-routing",
"url": null
} |
php, url-routing
$this->controller->init();
}
public function executeAction(): self{
$action = $this->action;
$this->controller->$action($this->parameters);
return $this;
}
public function getUrlSegments($url): self{
$url = explode('/', ltrim($url,'/'));
$this->urlSegments = $url;
return $this;
}
public function determineController(): self{
if(count($this->urlSegments) > 0){
$controller = ucfirst($this->urlSegments[0]);
if(empty($controller)){
$this->controllerName = $this->defaultRoute[0];
return $this;
}
if($this->controllerExist($controller)){
$this->controllerName = $controller;
return $this;
}
}
$this->controllerName = $this->notFoundRoute[0];
return $this;
}
public function createController(): self{
$controllerName = $this->controllerName;
$this->requireFile($this->getControllerFile($controllerName));
$this->controller = new $controllerName();
return $this;
}
public function determineParameters(): self{
$this->parameters = array_slice($this->urlSegments, 2);
return $this;
}
public function determineAction(): self{
$action = 'index';
if(count($this->urlSegments) > 1){
if(strlen($this->urlSegments[1]) > 0){
$action = $this->urlSegments[1];
}
}
if(!$this->actionExist($action)){
$this->controllerName = 'ErrorPages';
$this->createController();
$action = $this->notFoundRoute[1];
}
$this->action = $action;
return $this;
}
public function determineView(): self{
$this->view = $this->controller->view;
if(!is_string($this->view)){
$this->view = null;
} | {
"domain": "codereview.stackexchange",
"id": 44253,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, url-routing",
"url": null
} |
php, url-routing
if(!is_string($this->view)){
$this->view = null;
}
if(!$this->viewExist($this->controllerName, $this->view) && $this->view != null){
$this->controllerName = 'ErrorPages';
$this->createController();
$this->action = $this->notFoundRoute[1];
$this->executeAction();
$this->view = '404';
}
return $this;
}
public function controllerExist($controllerName): bool{
return StorageUtils::fileExist(StorageUtils::getFullPath($this->getControllerFile($controllerName)));
}
public function actionExist($action): bool{
return method_exists($this->controller, $action);
}
public function viewExist($controllerName, $view): bool{
return StorageUtils::fileExist(StorageUtils::getFullPath($this->getViewFile($controllerName, $view)));
}
public function getControllerFile($controllerName): string{
return "/src/Application/$controllerName/Controller/$controllerName.php";
}
public function getViewFile($controllerName, $viewName): string{
return "/src/Application/$controllerName/View/$viewName.php";
}
private function requireFile($route): void{
require_once(StorageUtils::getFullPath($route));
}
}
?>
The corresponding test class
<?php
namespace xxxx\xxxx\Test;
use PHPUnit\Framework\TestCase;
use xxxx\xxxx\Router\Router;
class RouterTest extends TestCase{
private $router;
public function setUp(): void{
$this->router = new Router();
$this->router->setDefaultRoute('Home', 'index');
$this->router->setNotFoundRoute('ErrorPages', 'notFound');
}
/**
* @covers getUrlSegments
*/
public function testGetUrlSegments(){
$returnValue = $this->router->getUrlSegments('/test/index/111/222'); | {
"domain": "codereview.stackexchange",
"id": 44253,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, url-routing",
"url": null
} |
php, url-routing
$this->assertNotEmpty($this->router->urlSegments);
$this->assertIsArray($this->router->urlSegments);
$this->assertEquals('test', $this->router->urlSegments[0]);
$this->assertEquals('index', $this->router->urlSegments[1]);
$this->assertEquals('111', $this->router->urlSegments[2]);
$this->assertEquals('222', $this->router->urlSegments[3]);
$this->assertEquals(Router::class, $returnValue::class);
}
/**
* @covers setDefaultRoute
*/
public function testSetDefaultRoute(){
$this->assertEquals('Home', $this->router->defaultRoute[0]);
$this->assertEquals('index', $this->router->defaultRoute[1]);
}
/**
* @covers setNotFoundRoute
*/
public function testSetNotFoundRoute(){
$this->assertEquals('ErrorPages', $this->router->notFoundRoute[0]);
$this->assertEquals('notFound', $this->router->notFoundRoute[1]);
}
public function routeProvider(){
return [
['/test', 'Test'],
['/test/sdf24', 'Test'],
['/home', 'Home'],
['/', 'Home'],
['', 'Home'],
['/home/', 'Home'],
['adafeadsdas', 'ErrorPages'],
['ad/asd/efwefd/qed', 'ErrorPages'],
['!@#@!#@', 'ErrorPages'],
['/!@@$2323', 'ErrorPages'],
['/.html', 'ErrorPages'],
['/someNonExistentController', 'ErrorPages'],
['/%', 'ErrorPages'],
['/@@$%$%%5E', 'ErrorPages']
];
}
/**
* @covers determineController
* @dataProvider routeProvider
*/
public function testDetermineController($url, $expectedResult){
$this->router->getUrlSegments($url)
->determineController();
$this->assertEquals($expectedResult, $this->router->controllerName);
} | {
"domain": "codereview.stackexchange",
"id": 44253,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, url-routing",
"url": null
} |
php, url-routing
$this->assertEquals($expectedResult, $this->router->controllerName);
}
/**
* @covers createController
* @dataProvider routeProvider
*/
public function testCreateController($url, $expected){
$this->router->getUrlSegments($url)
->determineController()
->createController();
$this->assertEquals($expected, $this->router->controller::class);
}
public function actionDataProvider(){
return [
['/test', 'index'],
['/test/doesNotExist', 'notFound'],
['/test/test', 'test'],
['/test/!#$@#$ad', 'notFound'],
['/test/', 'index']
];
}
/**
* @covers determineAction
* @dataProvider actionDataProvider
*/
public function testDetermineAction($url, $expected){
$this->router->getUrlSegments($url)
->determineController()
->createController()
->determineAction();
$this->assertEquals($expected, $this->router->action);
}
/**
* @covers determineAction
*/
public function testDetermineActionChangesControllerOnActionNotExist(){
$this->router->getUrlSegments('/test/doesNotExist')
->determineController()
->createController()
->determineAction();
$this->assertEquals($this->router->notFoundRoute[0], $this->router->controllerName);
$this->assertEquals($this->router->notFoundRoute[1], $this->router->action);
$this->assertEquals(\ErrorPages::class, $this->router->controller::class);
}
public function parameterDataProvider(){
return [
['/test', []],
['/test/index', []],
['/test/index/one', ['one']],
['/test/index/one/two/three', ['one', 'two', 'three']],
['/test/index/3,d,/!#$/', ['3,d,', '!#$', '']],
['/text/index/index.html', ['index.html']]
];
} | {
"domain": "codereview.stackexchange",
"id": 44253,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, url-routing",
"url": null
} |
php, url-routing
/**
* @covers determineParameters
* @dataProvider parameterDataProvider
*/
public function testDetermineParameters($url, $expected){
$this->router->getUrlSegments($url)
->determineParameters();
$this->assertEquals($expected, $this->router->parameters);
}
public function viewDataProvider(){
return [
['/test/validView', 'ValidView'],
['/test/invalidView', '404']
];
}
/**
* @covers determineView
* @dataProvider viewDataProvider
*/
public function testDetermineView($url, $expected){
$this->router->execute($url);
$this->assertEquals($expected, $this->router->view);
}
public function printedReturnDataProvider(){
return [
['/test/printedReturnView', null],
['/test/printRReturnView', null]
];
}
/**
* @covers determineView
* @dataProvider printedReturnDataProvider
*/
public function testDetermineViewWithPrintedReturnData($url, $expected){
$this->router->execute($url);
$this->expectOutputString('{"randomData":"dsdsddd"}');
$this->assertEquals($expected, $this->router->view);
}
/**
* @covers determineView
*/
public function testDetermineViewChangesControllerOnViewNotExist(){
$this->router->execute('/test/invalidView');
$this->assertEquals('ErrorPages', $this->router->controllerName);
}
}
I realize that there is probably a lot of room to grow here and I'm curious to know how I did this time around and where improvements can be made.
Almost forgot to add what the index.php file looks like now.
use xxxx\xxxx\Util\StorageUtils;
use xxxx\xxxx\Router\Router;
if(isset($argv)){
$options = getopt('', ['uri::']);
$url = $options['uri'];
}else{
if($engine == 'nginx'){
$url = $_SERVER['REQUEST_URI'];
}else if($engine == 'apache'){
$url = $_SERVER['PATH_INFO'];
}
} | {
"domain": "codereview.stackexchange",
"id": 44253,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, url-routing",
"url": null
} |
php, url-routing
$router = new Router();
$router->setDefaultRoute('Home', 'index');
$router->setNotFoundRoute('ErrorPages', 'notFound');
$router->execute($url);
$router->executeView(); | {
"domain": "codereview.stackexchange",
"id": 44253,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, url-routing",
"url": null
} |
php, url-routing
Answer: Your router is doing too much.
Router should do one thing and one thing only. It should map request uri to a specific request handler (controller action).
You may get a better architecture if you think of router as being stateless. Actually this principle will serve you well far beyond just router.
Router should not instantiate controllers. That's job of controller factory. Furthermore controllers usually need some services to act upon. These services should be injected to the controller via constructor injection (there are other means of injection, but constructor injection is by far the best). Even if you don't see the need now, believe me it will show itself later. Unless you're doing something like calling everything via static methods, which is kinda bad on its own.
Router should not render views. That's job of your rendering engine to execute it. And it's job of controllers to invoke the execution.
Router also should not try to be the entire application. There usually is yet another class that uses a router to determine controller, but it is the application which then asks controller factory to instantiate controller and then it executes it but this happens after the router's job is already done.
Another way to think of router is just that it is a request handler itself. It is the controller for all routes and if receives a specific route for which there is a specific handler/controller, it delegates to it.
When I say "request handler" I mean specifically the RequestHandlerInterface of PSR-15
https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-15-request-handlers.md#21-psrhttpserverrequesthandlerinterface. | {
"domain": "codereview.stackexchange",
"id": 44253,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, url-routing",
"url": null
} |
php, url-routing
Consider implementing router such that it implements this interface and such that the handle method is the only public method of the router. To achieve configurabiloty of the router, you should split the implementation into two objects - router builder and the router itself. The builder has methods for configuration and creating of the router. Router is the RequestHandlerInterface implementation and all configuration is passed to it via constructor (inside the RouterBuilder::build() method).
$builder = new RouterBuilder($controllerFactory);
$builder->get('/test', 'Test', 'index');
$router = $builder->build();
$request = ServerRequest::fromGlobals();
$response = $router->handle($request);
sendResponse($response); | {
"domain": "codereview.stackexchange",
"id": 44253,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, url-routing",
"url": null
} |
sorting, shell, posix, sh
Title: Find first or last argument lexicographically or temporally
Question: I often find I need to find the earliest or latest file matching a given pattern, and sometimes to choose the lowest or highest string from several possibilities.
The following four functions provide that functionality, and are robust enough to work correctly with all possible inputs. They do require the GNU implementations of sort and head that work with NUL-separated input.
#!/bin/sh
set -eu
first_sorted() {
${1+true} return 1
printf '%s\0' "$@" | sort -z | head -z -n1 | tr '\0' '\n'
}
last_sorted() {
${1+true} return 1
printf '%s\0' "$@" | sort -rz | head -z -n1 | tr '\0' '\n'
}
first_mtime() {
test -e "${1-}" || return 1
first=$1; shift
for i
do
test -e "$i" || return 1
test "$first" -ot "$i" || first=$i
done
printf '%s\n' "$first"
}
last_mtime() {
test -e "${1-}" || return 1
last=$1; shift
for i
do
test -e "$i" || return 1
test "$last" -nt "$i" || last=$i
done
printf '%s\n' "$last"
}
Unit tests:
# Unit tests of string ops
LC_COLLATE=C
export LC_COLLATE
nl='
'
first_sorted && exit 1
test "twenty${nl}seven" = "$(first_sorted "twenty${nl}seven")"
test "twenty${nl}five" = "$(first_sorted "twenty${nl}seven" "twenty${nl}five")"
test "" = "$(first_sorted '' "twenty${nl}five")"
last_sorted && exit 1
test "twenty${nl}seven" = "$(last_sorted "twenty${nl}seven")"
test "twenty${nl}seven" = "$(last_sorted "twenty${nl}seven" "twenty${nl}five")"
test "twenty${nl}five" = "$(last_sorted '' "twenty${nl}five")"
# Unit tests of file ops
d=$(mktemp -d)
trap 'rm -r "$d"' EXIT
cd "$d"
touch -t 12310900 "Hogmanay${nl}morning"
touch -t 12311200 "Hogmanay${nl}midday"
touch -t 12311500 "Hogmanay${nl}afternoon"
touch -t 12312200 "Hogmanay${nl}evening"
first_mtime && return 1
test "Hogmanay${nl}morning" = "$(first_mtime H*)"
last_mtime && return 1
test "Hogmanay${nl}evening" = "$(last_mtime H*)" | {
"domain": "codereview.stackexchange",
"id": 44254,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sorting, shell, posix, sh",
"url": null
} |
sorting, shell, posix, sh
last_mtime && return 1
test "Hogmanay${nl}evening" = "$(last_mtime H*)"
Answer: Avoiding duplication
The pairs of functions have duplicated logic in them.
I would extract the comparator to avoid it.
Avoiding clever code
I find this a bit too clever:
${1+true} return 1
This alternative will have the same effect and I think looks more familiar and thereby easier to read:
test $# -gt 0 || return 1
Similarly, I find this one a bit clever too, because it combines two things, validating that there is a parameter and that it's a file:
test -e "${1-}" || return 1
I would spell out the two conditions, to separate the two intents:
test $# -gt 0 || return 1
test -e "$1" || return 1
A note on time complexity
I would be remiss to not point out that sorting (a log-linear operation) to find the first item feels a waste, when the task can be done with a linear operation.
If these functions will be used with at most hundreds of files, and not in a loop, then of course it doesn't matter much.
Using descriptive name instead of i
I only use i in counting loops.
In the posted code path would be a natural name.
Possible bug in the tests
If the posted test code runs in a function, then it's ok.
If not, then the return statement here is invalid:
first_mtime && return 1
I suspect you meant to write exit 1 instead of return 1 consistently everywhere in the test code.
Missing tests
The mtime functions fail when a parameter is not a valid file, but this case is not covered.
Simple remedy:
first_mtime 'nonexistent' && exit 1
last_mtime 'nonexistent' && exit 1
Alternative implementation
The main benefits of this alternative:
Reduced duplicated logic: one common function does the main work
Pure shell implementation (no sort, head, tr), linear logic | {
"domain": "codereview.stackexchange",
"id": 44254,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sorting, shell, posix, sh",
"url": null
} |
sorting, shell, posix, sh
Note that the functions starting with underline _ are meant as private.
That's why I didn't add the usual recommended parameter validation.
They assume they are only called correctly as intended.
_first_by_comparator() {
validator=$1; shift
comparator=$1; shift
test $# -gt 0 || return 1
first=$1; shift
"$validator" "$first" || return 1
for item
do
"$validator" "$item" || return 1
test "$first" "$comparator" "$item" || first=$item
done
echo "$first"
}
first_sorted() {
_first_by_comparator true '<' "$@"
}
last_sorted() {
_first_by_comparator true '>' "$@"
}
_file_exists() {
test -e "$1"
}
first_mtime() {
_first_by_comparator _file_exists '-ot' "$@"
}
last_mtime() {
_first_by_comparator _file_exists '-nt' "$@"
} | {
"domain": "codereview.stackexchange",
"id": 44254,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sorting, shell, posix, sh",
"url": null
} |
python, python-2.x
Title: JSON Lexer code
Question: How does the following look for a json lexer? Are there any things that can be improved upon? Does the pattern look general-purpose enough to be able to generalize it to make it into a useful program, beyond just my personal tokenization of json?
import re
TOKENS = [
# (name, regex)
('OPEN_BRACE', r'{'),
('CLOSE_BRACE', r'}'),
('OPEN_BRACKET', r'\['),
('CLOSE_BRACKET', r'\]'),
('COMMA', r','),
('SPACE', r'\s'),
('COLON', r':'),
('NULL', r'null'),
('TRUE', r'true'),
('FALSE', r'false'),
('NUMBER', r'-?(?:0|[1-9]\d*)(?:\.\d+)?(?:e[-+]\d+)?'),
('STRING', r'"[^"\\]*(\\"[^"\\]*)*"'),
('EOF', r'^$')
]
class Token:
def __init__(self, type, value):
self.type=type
self.value=value
def __eq__(self, other):
return other == self.value
def __str__(self):
return '<%s -- %s>' % (self.type, self.value)
class Lexer:
def __init__(self, input):
self.input = input
self.idx = 0
self.tokens = []
def pprint(self):
print [str(token) for token in self.tokens]
def getNextToken(self):
substring = self.input[self.idx:] if self.idx < len(self.input) else ''
for token in TOKENS:
s = re.match(token[1], substring)
if s:
self.idx += s.end()
token = Token(token[0], s.group())
self.tokens.append(token)
return token
raise RuntimeError("Unrecognized token at position %d -- '%s'" % (self.idx, substring[:5]))
def parse(self):
tok = True
while tok:
tok = self.getNextToken()
if tok == '':break
return self.tokens
l = Lexer('{"name": "david"}')
l.parse()
l.pprint() | {
"domain": "codereview.stackexchange",
"id": 44255,
"lm_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-2.x",
"url": null
} |
python, python-2.x
l = Lexer('{"name": "david"}')
l.parse()
l.pprint()
Answer: Some basic advice. Use Python 3. Put some blank lines between your methods
and functions to make the code easier to read and edit.
Your Token class is a perfect candidate for a dataclass. It has
a tiny number of attributes and is also well-suited to be immutable.
It is handy for a Token to know where it came from. This is not
required for lexing, but I would typically include a pos attribute in a Token
class. That allows to to trace a token back to its origin during a debugging
scenario.
A Token should not have a sneaky definition of equality for no good reason.
Your Token.__eq__() method says a string equals a token if their text values
are the same. That's non-intuitive and the benefit it provides your program is
tiny (it allows you to terminate the lexing loop with if tok == ''). Much
better is to play by the book and stop lexing when you hit EOF. The code is
just as easy to write and a lot more straightforward for the reader.
Unless you have a reason for it, don't tokenize whitespace one space at a
time. It spawns lots of unhelpful tokens that can be condensed to one. I converted your SPACE token definition to the following:
('WHITESPACE', r'\s+'), | {
"domain": "codereview.stackexchange",
"id": 44255,
"lm_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-2.x",
"url": null
} |
python, python-2.x
Pay careful attention to naming. A couple examples. (1) Your TOKENS are
not actually tokens (ie, instances of the Token class). They are token
definitions, or something along those lines. (2) A lexer does not parse; it
tokenizes. Give its primary method a proper name like lex() or tokenize().
Speaking of lexing and parsing. A now-deleted comment implied that your
lexer is ill-conceived because it fails to enforce the syntax rules of JSON.
That is both incorrect and a common error when first trying build a lexer: we
let our brains get ahead of ourselves and start smuggling higher-level concepts
(like the syntax for JSON) into a low-level task (writing a lexer that converts
text to narrowly-valid tokens). Your lexer should accept a sequences of valid
tokens even if they are JSON gibberish.
Token-defintion order matters. When lexing you have to take special care to
attempt to match the token definitions in an order that will avoid confusion,
which can occur if one definition embraces a simpler definition (for example,
a quoted string can contain lots of other stuff). One strategy to avoid such
problems it to attempt the "bigger" entities first. Even though I found
no specific problems along these lines in your lexer, on general principle
I rearranged the ordering of the token definitions.
Your lexer generates a lot of substrings. Each time the next token is
requested, you first have to create a string representing the rest-of-the-text
(everything after self.idx). That's not necessary if you take advantage of
the fact that compiled regular expression objects take an optional pos
parameter telling them where to start matching. In the illustration below, I
pre-compiled all of the regexes when defining TOKEN_DEFINITIONS.
When to return information and where to accumulate it. Since the lexer is accumulating the tokens, it's not clear to me that Lexer.lex() should return anything (I opted for no).
Another question is which method should accumulate the tokens? | {
"domain": "codereview.stackexchange",
"id": 44255,
"lm_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-2.x",
"url": null
} |
python, python-2.x
Another question is which method should accumulate the tokens?
At least to my eye, that seems more appropriate for lex() than get_next_token().
Your quoted-string regex doesn't work correctly. What you want to match is easy
to describe in words:
" Initial double-quote.
.*? Stuff, non-greedy (otherwise we'll go to the last double-quote).
" Closing double-quote (details to follow). | {
"domain": "codereview.stackexchange",
"id": 44255,
"lm_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-2.x",
"url": null
} |
python, python-2.x
The tricky part is that closing double-quote. It cannot be preceded by a
backslash. That calls for a negative-lookbehind. So the components of the
necessary regex look like this:
"
.*?
(?<!\\)"
It can be confusing to test stuff like this because you have to correctly
navigate the string processing happening at the level of your Python syntax.
One strategy is to create a variety of quoted strings in Python, put them into
a dict, use the json library to created valid JSON text, and then make sure
that your lexer can handle it.
Speaking of testing, set your programs up to facilitate testing. In a real
project of my own, I would use proper unit tests, but even in a code review
context I typically start by rearranging the author's code into a form that I
can subject to experimentation and testing. As shown below, I created a
top-level main() function and an easy way to add examples as I checked and
edited your code.
import re
import json
import sys
from dataclasses import dataclass
def json_simple():
# A simple chunk of JSON with various data types.
d = dict(
msg = "hello world",
n = 99.34,
status = True,
other = None,
)
return json.dumps(d, indent = 4)
def good_tokens_bad_json():
# The lexer should accept this. Let the parser reject it.
return ''' true null "hi" } 123 { '''
def json_quoting_example():
# Some strings with internal double-quotes and backslashes.
examples = (
# Just quotes.
r'__"foo"__',
r'__"foo__',
r'__foo"__',
# Quotes with leading backslashes.
r'__\"foo\"__',
r'__\"foo__',
r'__foo\"__',
# Quotes with 2 leading backslashes.
r'__\\"foo\\"__',
r'__\\"foo__',
r'__foo\\"__',
)
# Convert those examples into a dict and then JSON text.
d = {
f'ex{i}' : ex
for i, ex in enumerate(examples)
}
return json.dumps(d, indent = 4) | {
"domain": "codereview.stackexchange",
"id": 44255,
"lm_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-2.x",
"url": null
} |
python, python-2.x
def invalid_text():
return '''{"a": 123, blort: 99}'''
EXAMPLES = dict(
quoting = json_quoting_example(),
goodbad = good_tokens_bad_json(),
simple = json_simple(),
invalid = invalid_text(),
)
def main():
args = sys.argv[1:] + ['simple']
k = args[0]
text = EXAMPLES[k]
lex = Lexer(text)
lex.lex()
for tok in lex.tokens:
print(tok)
EOF = 'EOF'
TOKEN_DEFINITIONS = [
# Try to match these bigger concepts first.
('QUOTED_STRING', r'".*?(?<!\\)"'),
('NUMBER', r'-?(?:0|[1-9]\d*)(?:\.\d+)?(?:e[-+]\d+)?'),
# Everything else is atomic and simple, so no confusion to worry about.
('OPEN_BRACE', r'{'),
('CLOSE_BRACE', r'}'),
('OPEN_BRACKET', r'\['),
('CLOSE_BRACKET', r'\]'),
('COMMA', r','),
('WHITESPACE', r'\s+'),
('COLON', r':'),
('NULL', r'null'),
('TRUE', r'true'),
('FALSE', r'false'),
(EOF, r'$')
]
TOKEN_DEFINITIONS = [
(type, re.compile(pattern))
for type, pattern in TOKEN_DEFINITIONS
]
@dataclass(frozen = True)
class Token:
pos: int
type: str
value: str
class Lexer:
def __init__(self, text):
self.text = text
self.pos = 0
self.tokens = []
def lex(self):
while True:
tok = self.get_next_token()
self.tokens.append(tok)
if tok.type == EOF:
break
def get_next_token(self):
for tok_type, rgx in TOKEN_DEFINITIONS:
m = rgx.match(self.text, pos = self.pos)
if m:
value = m.group()
self.pos += len(value)
return Token(self.pos, tok_type, value)
chunk = self.text[self.pos : self.pos + 20]
msg = f'Unrecognized token: position={self.pos} content={chunk!r}'
raise ValueError(msg)
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 44255,
"lm_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-2.x",
"url": null
} |
python, python-2.x
if __name__ == '__main__':
main()
Postscript: my regular expression for quoted strings is also bad. It fails
when the string actually ends with a backslash. I believe that this
answer shows how to do it
correctly (but I did not test it extensively, which one really must do this
these sorts of things). Here are the components of the regular expression
broken down and applied to your situation (double-quoted strings only):
" # Opening quote.
(
(\\{2})* # Just an even N of backslashes.
| # OR ...
(
.*? # Stuff, non-greedy.
[^\\] # Non backslash.
(\\{2})* # Even N of backslashes.
)
)
" # Closing quote. | {
"domain": "codereview.stackexchange",
"id": 44255,
"lm_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-2.x",
"url": null
} |
c#, design-patterns
Title: Singleton design pattern
Question: as a practice and selfdevelopment exercise I have decided to implement design patterns in C#. I am using polish cuisine as an example in my implementations. In this project I implemented Singleton design pattern. I kindly ask for a review :D Here is the code:
Model:
public sealed class Pierogi
{
public Guid Guid { get; }
public int Count { get; }
public string Type { get; }
public Pierogi(int count, string type)
{
Guid = Guid.NewGuid();
Count = count;
Type = type;
}
public override string ToString()
{
return $"Guid: {Guid}, Count: {Count}, Type: {Type}";
}
}
public static class PierogiTypes
{
public const string WithPotatoesAndCheese = "with potatoes and cheese";
public const string WithGroat = "with groat";
public const string WithCabbage = "with cabbage";
public const string WithMeat = "with meat";
public const string WithStrawberries = "with strawberries";
public const string WithBlueberries = "with blueberries";
public const string WithPotatoesAndCheeseButAlsoWithYoghurtAndKetchup = "with potatoes and cheese but also with yoghurt and ketchup";
}
Singleton:
public sealed class PierogiSingleton : IPierogi
{
private static readonly Lazy<PierogiSingleton> LazyInstance = new(() => new PierogiSingleton());
public static PierogiSingleton Instance => LazyInstance.Value;
public static bool IsInstanceCreated => LazyInstance.IsValueCreated;
public int PlatesServed = 0;
private PierogiSingleton()
{
}
public Pierogi ServePierogiWithPotatoesAndCheese()
{
PlatesServed += 1;
return new Pierogi(10, PierogiTypes.WithPotatoesAndCheese);
}
public Pierogi ServePierogiWithGroat()
{
PlatesServed += 1;
return new Pierogi(10, PierogiTypes.WithGroat);
} | {
"domain": "codereview.stackexchange",
"id": 44256,
"lm_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#, design-patterns",
"url": null
} |
c#, design-patterns
public Pierogi ServePierogiWithCabbage()
{
PlatesServed += 1;
return new Pierogi(10, PierogiTypes.WithCabbage);
}
public Pierogi ServePierogiWithMeat()
{
PlatesServed += 1;
return new Pierogi(10, PierogiTypes.WithMeat);
}
public Pierogi ServePierogiWithStrawberries()
{
PlatesServed += 1;
return new Pierogi(10, PierogiTypes.WithStrawberries);
}
public Pierogi ServePierogiWithBlueberries()
{
PlatesServed += 1;
return new Pierogi(10, PierogiTypes.WithBlueberries);
}
public Pierogi ServePierogiWithPotatoesAndCheeseButAlsoWithYoghurtAndKetchup()
{
PlatesServed += 1;
return new Pierogi(10, PierogiTypes.WithPotatoesAndCheeseButAlsoWithYoghurtAndKetchup);
}
}
Program.cs:
class Program
{
public static async Task Work(int delay)
{
await Task.Delay(delay);
Console.WriteLine($"Is pierogi singleton instantiated: {PierogiSingleton.IsInstanceCreated}");
await Task.Delay(delay);
var firstPortionOfPierogi = PierogiSingleton.Instance.ServePierogiWithBlueberries();
Console.WriteLine($"{firstPortionOfPierogi}, Yummy :D");
Console.WriteLine($"Is pierogi singleton instantiated: {PierogiSingleton.IsInstanceCreated}");
await Task.Delay(delay);
var secondPortionOfPierogi = PierogiSingleton.Instance.ServePierogiWithPotatoesAndCheeseButAlsoWithYoghurtAndKetchup();
Console.WriteLine($"{secondPortionOfPierogi}, aaaah what is this sacrilege? :O");
Console.WriteLine($"Plates served {PierogiSingleton.Instance.PlatesServed}");
}
public static async Task Main()
{
Task.WaitAll(new Task[]
{
Task.Run(() => Work(500)),
Task.Run(() => Work(2500))
});
}
} | {
"domain": "codereview.stackexchange",
"id": 44256,
"lm_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#, design-patterns",
"url": null
} |
c#, design-patterns
Answer: You want a Singleton, you got a Singleton with these three(ish) lines:
private static readonly Lazy<PierogiSingleton> LazyInstance = new(() => new PierogiSingleton());
public static PierogiSingleton Instance => LazyInstance.Value;
private PierogiSingleton()
{
}
QED. However, naming the class PierogiSingleton is not indicative of the purpose of the class, but rather of how it is implemented. Implementation details should be of no concern to its consumer. From what it seems to do, it manages assembling and serving up Pierogi dishes of varying sorts. But it also seems to keep track of the number of dishes served up. This may be indicative of splitting the responsibilities into separate classes. Let's name one PierogiFactory (to use a software term), create a second one called PierogiDishCounter and lastly one that brings those two together and call it PierogiRestaurant . Also, you could consider more strongly-typing your Pierogis by using an enum rather than a string for its type. And there are multiple ways a search away to add textual descriptors to enums via attributes. So let's bring that together:
public sealed class Pierogi
{
public Guid Guid { get; }
public int Count { get; }
public PierogiTypes Type { get; }
public Pierogi(int count, PierogiTypes type)
{
Guid = Guid.NewGuid();
Count = count;
Type = type;
}
public override string ToString()
{
return $"Guid: {Guid}, Count: {Count}, Type: {Type}";
}
}
public enum PierogiTypes
{
[Description("with potatoes and cheese")]
WithPotatoesAndCheese,
[Description("with groat")]
WithGroat,
[Description("with cabbage")]
WithCabbage,
[Description("with meat")]
WithMeat,
[Description("with strawberries")]
WithStrawberries,
[Description("with blueberries")]
WithBlueberries, | {
"domain": "codereview.stackexchange",
"id": 44256,
"lm_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#, design-patterns",
"url": null
} |
c#, design-patterns
[Description("with blueberries")]
WithBlueberries,
[Description("with potatoes and cheese but also with yoghurt and ketchup")]
WithPotatoesAndCheeseButAlsoWithYoghurtAndKetchup,
}
public interface IPierogi // guessing
{
Pierogi ServePierogiWithPotatoesAndCheese();
Pierogi ServePierogiWithGroat();
Pierogi ServePierogiWithCabbage();
Pierogi ServePierogiWithMeat();
Pierogi ServePierogiWithStrawberries();
Pierogi ServePierogiWithBlueberries();
Pierogi ServePierogiWithPotatoesAndCheeseButAlsoWithYoghurtAndKetchup();
}
public sealed class PierogiRestaurant : IPierogi
{
private static readonly Lazy<PierogiRestaurant> LazyInstance = new(() => new PierogiRestaurant(PierogiDishCounter.Instance, PierogiFactory.Instance));
private readonly IPierogiDishCounter pierogiDishCounter;
private readonly IPierogi pierogiFactory;
public static PierogiRestaurant Instance => LazyInstance.Value;
public static bool IsInstanceCreated => LazyInstance.IsValueCreated;
private PierogiRestaurant(IPierogiDishCounter pierogiDishCounter, IPierogi pierogiFactory)
{
this.pierogiDishCounter = pierogiDishCounter;
this.pierogiFactory = pierogiFactory;
}
public int PlatesServed => pierogiDishCounter.PlatesServed;
public Pierogi ServePierogiWithPotatoesAndCheese()
{
pierogiDishCounter.ServePlate();
return pierogiFactory.ServePierogiWithPotatoesAndCheese();
}
public Pierogi ServePierogiWithGroat()
{
pierogiDishCounter.ServePlate();
return pierogiFactory.ServePierogiWithGroat();
}
public Pierogi ServePierogiWithCabbage()
{
pierogiDishCounter.ServePlate();
return pierogiFactory.ServePierogiWithCabbage();
} | {
"domain": "codereview.stackexchange",
"id": 44256,
"lm_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#, design-patterns",
"url": null
} |
c#, design-patterns
public Pierogi ServePierogiWithMeat()
{
pierogiDishCounter.ServePlate();
return pierogiFactory.ServePierogiWithMeat();
}
public Pierogi ServePierogiWithStrawberries()
{
pierogiDishCounter.ServePlate();
return pierogiFactory.ServePierogiWithStrawberries();
}
public Pierogi ServePierogiWithBlueberries()
{
pierogiDishCounter.ServePlate();
return pierogiFactory.ServePierogiWithBlueberries();
}
public Pierogi ServePierogiWithPotatoesAndCheeseButAlsoWithYoghurtAndKetchup()
{
pierogiDishCounter.ServePlate();
return pierogiFactory.ServePierogiWithPotatoesAndCheeseButAlsoWithYoghurtAndKetchup();
}
}
public sealed class PierogiFactory : IPierogi
{
private static readonly Lazy<PierogiFactory> LazyInstance = new(() => new PierogiFactory());
public static PierogiFactory Instance => LazyInstance.Value;
public static bool IsInstanceCreated => LazyInstance.IsValueCreated;
private PierogiFactory()
{
}
public Pierogi ServePierogiWithPotatoesAndCheese()
{
return new Pierogi(10, PierogiTypes.WithPotatoesAndCheese);
}
public Pierogi ServePierogiWithGroat()
{
return new Pierogi(10, PierogiTypes.WithGroat);
}
public Pierogi ServePierogiWithCabbage()
{
return new Pierogi(10, PierogiTypes.WithCabbage);
}
public Pierogi ServePierogiWithMeat()
{
return new Pierogi(10, PierogiTypes.WithMeat);
}
public Pierogi ServePierogiWithStrawberries()
{
return new Pierogi(10, PierogiTypes.WithStrawberries);
}
public Pierogi ServePierogiWithBlueberries()
{
return new Pierogi(10, PierogiTypes.WithBlueberries);
} | {
"domain": "codereview.stackexchange",
"id": 44256,
"lm_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#, design-patterns",
"url": null
} |
c#, design-patterns
public Pierogi ServePierogiWithPotatoesAndCheeseButAlsoWithYoghurtAndKetchup()
{
return new Pierogi(10, PierogiTypes.WithPotatoesAndCheeseButAlsoWithYoghurtAndKetchup);
}
}
public interface IPierogiDishCounter
{
int PlatesServed { get; }
void ServePlate();
}
public sealed class PierogiDishCounter : IPierogiDishCounter
{
private static readonly Lazy<PierogiDishCounter> LazyInstance = new(() => new PierogiDishCounter());
public int PlatesServed { get; private set; } = 0;
public static PierogiDishCounter Instance => LazyInstance.Value;
private PierogiDishCounter()
{
}
public void ServePlate()
{
PlatesServed += 1;
}
}
class Program
{
public static async Task Work(int delay)
{
await Task.Delay(delay);
Console.WriteLine($"Is pierogi singleton instantiated: {PierogiRestaurant.IsInstanceCreated}");
await Task.Delay(delay);
var firstPortionOfPierogi = PierogiRestaurant.Instance.ServePierogiWithBlueberries();
Console.WriteLine($"{firstPortionOfPierogi}, Yummy :D");
Console.WriteLine($"Is pierogi singleton instantiated: {PierogiRestaurant.IsInstanceCreated}");
await Task.Delay(delay);
var secondPortionOfPierogi =
PierogiRestaurant.Instance.ServePierogiWithPotatoesAndCheeseButAlsoWithYoghurtAndKetchup();
Console.WriteLine($"{secondPortionOfPierogi}, aaaah what is this sacrilege? :O");
Console.WriteLine($"Plates served {PierogiRestaurant.Instance.PlatesServed}");
}
public static async Task Main()
{
Task.WaitAll(new Task[] { Task.Run(() => Work(500)), Task.Run(() => Work(2500)) });
}
}
``` | {
"domain": "codereview.stackexchange",
"id": 44256,
"lm_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#, design-patterns",
"url": null
} |
bash, shell
Title: Print full path to last modified file in a given location
Question: Background
I've provided two simple functions that I use to print a full path to the last modified file within a directory. I don't code in bash frequently so I'm looking for a generic feedback on what to do / avoid when writing small utility functions in bash.
Code
Last file
The function prints a full path to last modified file in a specific or current directory (if no path is provided).
function last_file () {
if [[ -n "$1" ]]
then
(cd "$1" && echo "$(pwd -P)/$(ls -rt | tail -n 1)")
else
echo "$(pwd -P)/$(ls -rt | tail -n 1)"
fi
}
Last download
As above but prints last modified file in the ~/Downloads.
function last_download () {
(cd ~/Downloads && last_file)
}
Answer: I would like to remove the duplicated command.
last_file () {
(
set -e
[[ -n "$1" ]] && cd "$1"
printf '%s/%s\n' "$(pwd -P)" "$(ls -rt | tail -n 1)"
)
}
The whole body is run in a subshell.
set -e makes the subshell abort if the given argument is not a directory. You did something similar with cd "$1" && echo ...
printf is better than echo | {
"domain": "codereview.stackexchange",
"id": 44257,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash, shell",
"url": null
} |
c, linked-list, pointers
Title: C void* Generic Linked List
Question: I once tried to make a generic linked list in pure C (no external libraries, only the C standard library) here using C macros. With the same restrictions as in the previous attempt, this time I'm trying to use void*s.
linkedlist.h:
#include <stdbool.h>
#include <stddef.h>
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
typedef struct LinkedList LinkedList;
typedef struct LinkedListNode LinkedListNode;
struct LinkedListNode {
LinkedListNode *next;
void *data;
};
struct LinkedList {
LinkedList *this;
LinkedListNode *head;
size_t size;
void (*destructor)(LinkedList *this);
int (*dataComparer)(void *, void *);
void (*dataDestroyer)(void *);
int (*add)(LinkedList *this, void *data);
void *(*find)(LinkedList *this, bool (*comparer)(void *));
void (*removeByIndex)(LinkedList *this, size_t index);
void (*removeByObject)(LinkedList *this, void *object);
void (*clear)(LinkedList *this);
};
LinkedList *newLinkedList(int (*dataComparer)(void *, void *), void (*dataDestroyer)(void *));
void deleteLinkedList(LinkedList *list);
#endif
linkedlist.c:
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include "linkedlist.h"
int ll_default_dataComparer(void *a, void *b) {
int *castedA = (int *) a;
int *castedB = (int *) b;
return *castedA - *castedB;
}
void ll_default_dataDestroyer(void *data) {
free(data);
}
void ll_default_destructor(LinkedList *this) {
if (this == NULL) return;
LinkedListNode *node = this->head;
while (node != NULL) {
LinkedListNode *prev = node;
node = node->next;
this->dataDestroyer(prev);
}
}
int ll_default_add(LinkedList *this, void *data) {
if (this == NULL) return -1;
LinkedListNode *newNode = malloc(sizeof(LinkedListNode));
if (newNode == NULL) return -2;
newNode->next = NULL;
newNode->data = data;
LinkedListNode *node = this->head; | {
"domain": "codereview.stackexchange",
"id": 44258,
"lm_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, linked-list, pointers",
"url": null
} |
c, linked-list, pointers
newNode->next = NULL;
newNode->data = data;
LinkedListNode *node = this->head;
if (node == NULL) {
this->head = newNode;
} else {
while (node->next != NULL) node = node->next;
node->next = newNode;
}
this->size++;
return 0;
}
void *ll_default_find(LinkedList *this, bool (*comparer)(void *)) {
if (this == NULL) return NULL;
LinkedListNode *node = this->head;
while (node != NULL) {
if (comparer(node->data)) return node->data;
node = node->next;
}
return NULL;
}
void ll_default_removeByIndex(LinkedList *this, size_t index) {
if (this == NULL) return;
if (index >= this->size) return;
LinkedListNode *prevNode = NULL;
LinkedListNode *currNode = this->head;
for (size_t i = 0; i < index; i++) {
if (currNode == NULL) return;
prevNode = currNode;
currNode = currNode->next;
}
if (prevNode != NULL) {
prevNode->next = currNode->next;
this->dataDestroyer(prevNode->data);
} else {
this->head = currNode->next;
}
free(prevNode);
this->size--;
}
void ll_default_removeByObject(LinkedList *this, void *object) {
if (this == NULL) return;
LinkedListNode *prevNode = NULL;
LinkedListNode *currNode = this->head;
while (currNode != NULL) {
if (this->dataComparer(currNode->data, object) == 0) {
if (prevNode != NULL) {
prevNode->next = currNode->next;
this->dataDestroyer(currNode->data);
} else {
this->head = currNode->next;
}
free(currNode);
this->size--;
return;
}
prevNode = currNode;
currNode = currNode->next;
}
}
void ll_default_clear(LinkedList *this) {
if (this == NULL) return;
LinkedListNode *prevNode = NULL;
LinkedListNode *currNode = this->head; | {
"domain": "codereview.stackexchange",
"id": 44258,
"lm_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, linked-list, pointers",
"url": null
} |
c, linked-list, pointers
LinkedListNode *prevNode = NULL;
LinkedListNode *currNode = this->head;
while (currNode != NULL) {
prevNode = currNode;
currNode = currNode->next;
this->dataDestroyer(prevNode->data);
free(prevNode);
}
}
LinkedList *newLinkedList(int (*dataComparer)(void *, void *), void (*dataDestroyer)(void *)) {
LinkedList *list = malloc(sizeof(LinkedList));
if (list == NULL) return NULL;
list->this = list;
list->destructor = ll_default_destructor;
list->dataComparer = dataComparer != NULL ? dataComparer : ll_default_dataComparer;
list->dataDestroyer = dataDestroyer != NULL ? dataDestroyer : ll_default_dataDestroyer;
list->add = ll_default_add;
list->find = ll_default_find;
list->removeByIndex = ll_default_removeByIndex;
list->removeByObject = ll_default_removeByObject;
list->head = NULL;
list->size = 0;
return list;
}
void deleteLinkedList(LinkedList *list) {
list->destructor(list->this);
}
main.c (testing code, not as rigorously written as the main linked list code):
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "linkedlist.h"
typedef struct Cake {
char name[256];
size_t size;
} Cake;
bool finder(Cake *c) {
// i forgot c doesn't have lambdas so this is going to be awkward to use
if (c->size == 69420) return true;
return false;
}
int compare(Cake *a, Cake *b) {
return strcmp(a->name, b->name);
}
void destroyCake(Cake *cake) {
// stub
//
// struct Cake has no dynamic allocations, we don't have to do anything
// to clean it up afterwards
}
void print(LinkedList *list) {
printf("[\n");
LinkedListNode *node = list->head;
while (node != NULL) {
Cake *cake = node->data;
printf("\t{ name: \"%s\", size: %zu },\n", cake->name, cake->size);
node = node->next;
}
printf("]\n\n");
} | {
"domain": "codereview.stackexchange",
"id": 44258,
"lm_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, linked-list, pointers",
"url": null
} |
c, linked-list, pointers
printf("]\n\n");
}
void cakeprinter(Cake *cake) {
if (cake == NULL) printf("NULL\n");
printf("{ name: \"%s\", size: %zu }\n\n", cake->name, cake->size);
}
int main(void) {
LinkedList *list = newLinkedList(compare, destroyCake);
if (list == NULL) {
printf("Something went wrong\n");
return -1;
}
Cake *c1 = malloc(sizeof(Cake));
strcpy(c1->name, "Cakeus Smallus");
c1->size = 420;
Cake *c2 = malloc(sizeof(Cake));
strcpy(c2->name, "Cakeus Enormous");
c2->size = 69420;
Cake *c3 = malloc(sizeof(Cake));
strcpy(c3->name, "Cakeus Tinyeus");
c3->size = 69;
Cake *c4 = malloc(sizeof(Cake));
strcpy(c4->name, "Cakeus Biggus");
c4->size = 42069;
list->add(list->this, c1);
list->add(list->this, c2);
list->add(list->this, c3);
list->add(list->this, c4);
// did we make cakes?
printf("const cakes = ");
print(list);
// can we find a cake?
Cake *tc1 = list->find(list->this, finder);
printf("const cake69420 = ");
cakeprinter(tc1);
// lets destroy a cake by index and see if it's gone
list->removeByIndex(list->this, 0); // should be the first cake
printf("const cakesnoind = ");
print(list);
// lets destroy a cake by object and see if it's gone
list->removeByObject(list->this, tc1);
printf("const cakesnoobj = ");
print(list);
return 0;
}
Output as tested with ./main > res.txt:
const cakes = [
{ name: "Cakeus Smallus", size: 420 },
{ name: "Cakeus Enormous", size: 69420 },
{ name: "Cakeus Tinyeus", size: 69 },
{ name: "Cakeus Biggus", size: 42069 },
]
const cake69420 = { name: "Cakeus Enormous", size: 69420 }
const cakesnoind = [
{ name: "Cakeus Enormous", size: 69420 },
{ name: "Cakeus Tinyeus", size: 69 },
{ name: "Cakeus Biggus", size: 42069 },
]
const cakesnoobj = [
{ name: "Cakeus Tinyeus", size: 69 },
{ name: "Cakeus Biggus", size: 42069 },
] | {
"domain": "codereview.stackexchange",
"id": 44258,
"lm_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, linked-list, pointers",
"url": null
} |
c, linked-list, pointers
The driver code is for quick testing only and is not as rigorously written as the main linked list code is. It compiles with clang -Wall -Wextra -pedantic *.c -o main, albeit with multiple warnings about incompatible function pointer types (the linked list takes in a function taking void pointers, but I shoved in a function taking pointers to the object I'm trying to store).
As with my previous attempt, looking for feedback for potential improvements.
Thank you for your time.
Answer:
potential improvements.
Merry Christmas
Return a flag
void *ll_default_find(LinkedList *this, bool (*comparer)(void *)) returns NULL when not found. For a linked list of void *, better to not assume NULL is available for ll_...() use. Return a flag on success/failure and pass in a place to store the found value.
Remove functions do not return success indication
I'd expect something indicating success/failure.
Extensions
Consider an apply function. A function that does something to every node in the link-list
I'd expect a size_t LinkedList_Count(const LinkedList *this); to return the list count.
Documentation
Code, especially linkedlist.h lacks documentation. A good model is to assume the user only sees the .h file. Express, especially at the high level there, what code does.
Use const for reference data
When the reference data is not altered, used const. It allows for greater functional use, convey code's intent and helps some compilers.
Example:
// int ll_default_dataComparer(void *a, void *b) {
int ll_default_dataComparer(const void *a, const void *b) {
Avoid overflow
*castedA - *castedB; may overflow. Use a full range compare. Compilers commonly see the below idiom and emit efficient code.
// return *castedA - *castedB;
return (*castedA > *castedB) - (*castedA < *castedB);
-2??
Functions lack documentation about the meaning of return values like -2 from ll_default_add(LinkedList).
Out of order code guard
// #include <stdbool.h>
// #include <stddef.h> | {
"domain": "codereview.stackexchange",
"id": 44258,
"lm_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, linked-list, pointers",
"url": null
} |
c, linked-list, pointers
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
// Move here
#include <stdbool.h>
#include <stddef.h>
Allocate to the reference object, not type
Allocate to the referenced object. It is easier to code right, review and maintain.
// c1 = malloc(sizeof(Cake));
c1 = malloc(sizeof c1[0]);
Robust code would check allocation success. | {
"domain": "codereview.stackexchange",
"id": 44258,
"lm_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, linked-list, pointers",
"url": null
} |
c#, design-patterns
Title: Prototype design pattern
Question: As a practice and self-development exercise I have decided to implement design patterns in C#.
I am using polish cuisine as an example in my implementations. In this project I implemented Prototype design pattern.
Model:
public static class PierogiTypes
{
public const string WithPotatoesAndCheese = "with potatoes and cheese";
public const string WithGroat = "with groat";
public const string WithCabbage = "with cabbage";
public const string WithMeat = "with meat";
public const string WithStrawberries = "with strawberries";
public const string WithBlueberries = "with blueberries";
public const string WithPotatoesAndCheeseButAlsoWithYoghurtAndKetchup = "with potatoes and cheese but also with yoghurt and ketchup";
}
Desgin Pattern:
using Creational.Prototype.Model;
namespace Creational.Prototype.DesignPatters;
public abstract class PierogiPrototype
{
public Guid Guid { get; }
public int Count { set; get; }
public string Type { get; set; }
public PierogiPrototype(int count)
{
Guid = Guid.NewGuid();
Count = count;
}
public abstract PierogiPrototype Clone();
public override string ToString()
{
return $"Guid: {Guid}, Count: {Count}, Type: {Type}";
}
}
public class PierogiWithPotatoesAndCheese : PierogiPrototype
{
public PierogiWithPotatoesAndCheese(int count) : base(count)
{
Type = PierogiTypes.WithPotatoesAndCheese;
}
public override PierogiPrototype Clone()
{
return (PierogiPrototype)MemberwiseClone();
}
}
.
.
.
.
.
public class PierogiWithBlueberries : PierogiPrototype
{
public PierogiWithBlueberries(int count) : base(count)
{
Type = PierogiTypes.WithBlueberries;
}
public override PierogiPrototype Clone()
{
return (PierogiPrototype)MemberwiseClone();
}
} | {
"domain": "codereview.stackexchange",
"id": 44259,
"lm_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#, design-patterns",
"url": null
} |
c#, design-patterns
Program:
class Program
{
public static void Main()
{
var firstPortion = new PierogiWithBlueberries(10);
Console.WriteLine(firstPortion);
var secondPortion = firstPortion.Clone();
Console.WriteLine(secondPortion);
firstPortion.Count = 5;
Console.WriteLine(firstPortion);
Console.WriteLine(secondPortion);
}
}
Answer: Problem scope
The prototype design pattern is usually used whenever you want to minimize the creation time and/or resources of a complex or costly object
Complex: it has several nested data structures (in other words it is a data rich object)
Costly: either from time or resource (like CPU or I/O) perspective (like using network/database calls to retrieve initial values)
According to my understanding none of the above can be said about your derived classes of the PierogiPrototype
Shallow or Deep copy
The MemberwiseClone method performs a shallow copying which means only the top-level properties are copied over
In case of a complex object you want to copy all the nested structures as well not just their references
I'm unsure that you are aware of the ICloneable interface but it might make sense to take a look at it
Registry or Catalogue
The prototype pattern can be extended in a way that there is a central place where you store the prototypes and from where you can create copies
In your case you could store all the variants and create a copy by using the Type string | {
"domain": "codereview.stackexchange",
"id": 44259,
"lm_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#, design-patterns",
"url": null
} |
haskell
Title: Update `ith` element from Array of List[Int] in haskell
Question: I am implementing a function that receives a list of list integers and updates the list appending to the ith element a number x, for example:
list = [[1], [], []]
update(list, 0, 3)
> [[1, 3], [], []]
I implemented this in haskell:
updateArray :: Int -> Int -> [[Int]] -> [[Int]]
updateArray idx y [] = []
updateArray idx y arr
| idx < 0 = arr
| idx > (length arr) = arr
| otherwise = updateArray' idx y (length arr) arr
where
updateArray' :: Int -> Int -> Int -> [[Int]] -> [[Int]]
updateArray' idx y n (x:[])
| idx == 0 = (([(x ++ [y])]))
| otherwise = [x]
updateArray' idx y n arr
| n == (idx + 1) = (updateArray' idx y (n - 1) (take (n - 1) arr)) ++ ([((arr !! (n - 1)) ++ [y])])
| otherwise = (updateArray' idx y (n - 1) (take (n - 1) arr)) ++ [arr !! (n - 1)]
Some tests:
ghci> updateArray 2 2 [[], [], [3], [4]]
[[],[],[3,2],[4]]
ghci> updateArray 2 3 [[], [], [3], [4]]
[[],[],[3,3],[4]]
ghci> updateArray 0 7 [[], [], [3], [4]]
[[7],[],[3],[4]]
ghci> updateArray 0 2 [[]]
[[2]]
However I find the code difficult to read. How could I refactor this? And what if the requirement is updated to accept as input list of lists of any type?
Answer: This started out as a comment, but I figured I'd convert it into an answer. Please pardon the lack of testing: some code I've written may be wrong.
Let's start with your second question,
And what if the requirement is updated to accept as input lists of lists of any type?
I pasted your function into GHCi without type signatures, i.e. omitting the lines
updateArray :: Int -> Int -> [[Int]] -> [[Int]]
updateArray' :: Int -> Int -> Int -> [[Int]] -> [[Int]]
I then asked it for the type
ghci> :t updateArray
updateArray :: Int -> t -> [[t]] -> [[t]] | {
"domain": "codereview.stackexchange",
"id": 44260,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
haskell
I then asked it for the type
ghci> :t updateArray
updateArray :: Int -> t -> [[t]] -> [[t]]
So your function is already polymorphic. You specialized it more than you needed when you wrote its type signature.
Now to your first question.
How could I refactor this?
My first observation is that your code looks kind of imperative. In particular, it looks like you started with something like
def update_at(idx, y, arr):
if idx < 0 or idx > len(arr):
return arr
else:
return update_at_prime(idx, y, arr)
def update_at_prime(idx, y, arr):
arr_copy = arr[:]
arr_copy[idx] = arr_copy[idx] + [y]
return arr_copy
and then translated it to Haskell. update_at translates almost directly to updateAt, the prime version doesn't quite because Haskell doesn't have as good syntactic sugar for working with lists.
Because Haskell doesn't have this syntactic sugar (or comparable standard library functions -- at least I couldn't find any), you'll need to traverse the list recursively. In a language like Python, you might want to explicitly check the index because you're not explicitly iterating over the list. In Haskell, however, we can move the checks into a base case.
I've refactored your code to do this, plus also to make more use of pattern matching. I also done some small style changes like adding an underscore before variables that aren't going to be used (the compiler should complain about this unless you've disabled that option). One tricky thing here is that that I removed the idx > (length arr) check because if the index is greater than the length of the list, we will end up with the empty list base case. Often (but not always) you won't need to use a function like length in Haskell when you're modifying the elements of a list.
updateArray :: Int -> a -> [[a]] -> [[a]]
updateArray _idx _y [] = []
updateArray idx _y arr
| idx < 0 = arr
updateArray 0 y (x:arr) = (x ++ [y]) : arr
updateArray idx y (x:arr) = x : updateArray (idx - 1) y arr | {
"domain": "codereview.stackexchange",
"id": 44260,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
haskell
If I had more time, I would've walked through why the definition of updateArray' was overly complicated. Hopefully the broad strokes are clear.
Now there is a way to do this using a common library called (micro)lens. I'm adding this part for completeness's sake. I expect that if you're asking a question at this level you haven't even heard of lenses. I would focus on understanding my above refactoring instead of this "fancy" way of getting things done.
You can accomplish this by combining ix and over.
import Lens.Micro (ix, over)
updateArray :: Int -> a -> [[a]] -> [[a]]
updateArray idx y arr = over (ix idx) (addElemToEnd y) arr
where
addElemToEnd elem list = list ++ [elem]
Or the shorter way that uses the operator alias for over, which is (%~), and the operator way of writing addElemToEnd.
import Lens.Micro (ix, (%~), (&))
updateArray :: Int -> a -> [[a]] -> [[a]]
updateArray idx y arr = arr & ix idx %~ (++ [y])
Now, lenses are infamously much more difficult to understand than to use. I do not expect you to understand what is going on here, but I would hope that by looking through the documentation and some examples online you could get enough of a gist of them to use them if you desired. | {
"domain": "codereview.stackexchange",
"id": 44260,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
java, mysql, jdbc
Title: Company management app: Extracting data with JDBC and java.sql
Question: I'm currently working on a company management system as a university project, and I have to get my hands in java.sql.
I have come to struggle with extracting a query result from a ResultSet object, as I find its usage is a bit complex. I have written this code to automatically extract all the entries of a ResultSet in a List<Map<String, String>>; this solution surely works, but the usage of this API looks really complicated, wordy and not so intuitive to me.
The code you are seeing below is the one related to checking if id, name and password inserted by the user matches the data stored in the database (and is the one using the API discussed above):
/**
* Estrae tutte le righe del resultSet specificato, convertendole in mappe (nome_colonna, valore_colonna).
*/
private List<HashMap<String, String>> extractResults(ResultSet resultSet) throws SQLException {
var results = new ArrayList<HashMap<String, String>>();
/* Fino a quando c'è un'altra riga, vacci ed estrai i risultati in una mappa */
while (resultSet.next()) {
var rowMap = extractRow(resultSet);
results.add(rowMap); /* Aggiungi la mappa all'array di mappe */
}
return results;
}
/**
* Estrae una riga dal resultSet specificato e la converte in una mappa (nome_colonna, valore_colonna).
*/
private HashMap<String, String> extractRow(ResultSet resultSet) throws SQLException {
var labels = getColumnLabels(resultSet);
var rowMap = new HashMap<String, String>();
/* Per ogni colonna del risultato */
for (String label : labels) {
rowMap.put(label, resultSet.getString(label));
}
return rowMap;
}
/**
* Ottiene i nomi delle colonne del resultSet specificato.
*/
private String[] getColumnLabels(ResultSet resultSet) throws SQLException {
var meta = resultSet.getMetaData();
var labels = new ArrayList<String>(); | {
"domain": "codereview.stackexchange",
"id": 44261,
"lm_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, mysql, jdbc",
"url": null
} |
java, mysql, jdbc
/* 1 ... il numero delle colonne + 1, poiché gli indici vanno da 1 */
for (var i = 1; i < meta.getColumnCount() + 1; i++) {
labels.add(meta.getColumnLabel(i));
}
return labels.toArray(new String[0]);
}
/**
* Ritorna vero se il resultSet specificato è vuoto.
*/
private boolean isResultEmpty(ResultSet resultSet) {
try {
return !resultSet.isBeforeFirst();
} catch (SQLException e) {
e.printStackTrace();
}
return true;
}
This one is instead the method that fetches the db data and compares it with the inserted one:
/**
* Verifica che le credenziali specificate esistano e corrispondano con quelle nel database.
* @param id la matricola da controllare
* @param name il nome da controllare
* @param surname il cognome da controllare
* @return true se le credenziali corrispondono, false altrimenti
* @throws SQLException se si verifica un errore di qualunque tipo, in relazione al database
*/
public boolean checkCredentials(String id, String name, String surname) throws SQLException {
try (
var st = connection.prepareStatement("""
select w.ID, w.workerName, w.workerSurname
from worker w
where w.ID = ?
""")
) {
st.setString(1, id);
var resultSet = st.executeQuery();
if (isResultEmpty(resultSet)) {
/* Se la query ha ritornato l'insieme vuoto, la matricola non esiste */
return false;
} else {
/* Altrimenti ottieni le credenziali dal resultSet e controlla che corrispondano */
List<HashMap<String, String>> maps = extractResults(resultSet);
assert maps.size() == 1; /* Dovrebbe esserci solo una tupla nel risultato */
HashMap<String, String> result = maps.get(0);
var dbId = result.get("ID");
var dbName = result.get("workerName");
var dbSurname = result.get("workerSurname"); | {
"domain": "codereview.stackexchange",
"id": 44261,
"lm_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, mysql, jdbc",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.