text stringlengths 1 2.12k | source dict |
|---|---|
python, python-3.x, numpy, pandas
DATA = [
[0.045750000000000984, 0.04939999999999974, 0.05244999999999857, 0.054399999999998436, 0.056099999999999456, 0.05375000000000011, 0.047700000000000985, 0.053700000000000594, 0.053249999999999686, 16.81209831859011, 27.983008063348617, 20.301826794339316, 13.421484359287598,
17.10557180223468, 14.686987606192902, 41.18082589372154, 13.065486605460656, 4.608155337880411, 0.7571951341718915, 0.3457777398771206, 0.46056961460740087, 0.2819901554949584, 0.7205708724903156, -0.00040991561554303056, 0.3860776453927442, 0.09629955035400072, 0.2468722764784534],
[0.03290000000000123, 0.033550000000000045, 0.03949999999999949, 0.035550000000001615, 0.03725000000000067, 0.03515000000000022, 0.03714999999999999, 0.041350000000001316, 0.03869999999999882, 14.902912040542054, 15.452401255651447, 12.5484544315597, 10.83783196920491,
13.246734412134916, 12.636336066844674, 19.61093585673077, 8.898327945757917, 26.237157593452878, 0.36589566404637536, 0.5140598344685876, 0.06092353057665044, 0.5433592643289422, 0.3300217799943245, 0.1295695630661193, 0.5813772760582753, 0.97888742111902, 0.2144469684077374],
[0.15945000000000153, 0.1419000000000014, 0.1346, 0.14314999999999908, 0.14485000000000084, 0.1293000000000014, 0.14264999999999992, 0.1434499999999994, 0.08944999999999861, 39.54982055905117, 67.05598966736439, 14.170464300161013, 25.57103344352307, 22.224605807376317,
28.901343579758898, 19.05130673155152, 25.61289901736464, 122.31441473369556, 0.5250514668415044, 0.3119136953061388, 0.3818093125132205, 0.2669557624118119, -0.4876722558321518, 0.03814067199937899, -0.07502082862542193, 0.15371372713178985, -1.1026290280269917],
[0.00340000000000014, 0.0066000000000002515, 0.008499999999999603, 0.007999999999999518, 0.0065500000000002015, 0.008100000000000543, 0.0032500000000004834, 0.018350000000000196, 0.020150000000000542, 22.364276562983136, 20.506557739907425, 6.243036570120132, 19.3458717607394, | {
"domain": "codereview.stackexchange",
"id": 43130,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, numpy, pandas",
"url": null
} |
python, python-3.x, numpy, pandas
10.456833536986126, 19.65879720239808, 14.307243539019602, 9.091403905263792, 18.47420699835527, 0.8485690702159555, 0.40094252533477115, 0.1157765828210181, 0.6944022345849206, 0.46766736064272035, 1.153657712332056, 0.7600461290670872, 0.4170470750740715, 0.49920935232659946],
[None, None, 0.003549999999999955, 0.005799999999999788, 0.005799999999999788, 0.006900000000000275, 0.007049999999999682, 0.006800000000000173, 0.005200000000000045, None, None, 8.06110268044255, 13.695219329907925, 0.0,
12.81872890572318, 6.190861120089245, 3.9861242549543703, 4.403761437912741, None, None, -0.8342338501323102, -0.35990880371032785, 0.0, -2.9708131816772876, -0.12378167714772335, -1.4646911328887278, -2.475146432921943]
]
INDEX = ['89234', '89467', '89519', '89680', '90104'] | {
"domain": "codereview.stackexchange",
"id": 43130,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, numpy, pandas",
"url": null
} |
python, python-3.x, numpy, pandas
DATE_RANGE = pd.to_datetime(range(9), unit='m', origin=pd.Timestamp('1960-01-01'))
MULTI_COLUMN = pd.MultiIndex.from_tuples((
(date, param) for param in ('area', 'MPS', 'azimuth')
for date in DATE_RANGE), names=['validTime', 'parameters'])
def outliers2nan(bad_df: pd.DataFrame, bad_means: pd.DataFrame, thresh: pd.DataFrame) -> pd.DataFrame:
"""
where a parameter is greater than the minimum mean threshold set the value to NaN
"""
area_mps_means = bad_means.loc[:, ('area', 'MPS')] # Means (area and MPS)
area_mps = bad_df.loc[:, ('area', 'MPS')] # Dataframe (area and MPS)
lhs = (area_mps - area_mps_means).abs() # Left-hand side for comparison
rhs_unaligned = area_mps_means * thresh.loc[:, ('area', 'MPS')].values # Right-hand side: index on polygon level only
_, rhs = lhs.align(rhs_unaligned) # Join-repeat the threshold side to the second level
good_df = bad_df.copy() # Good dataframe starts out same as bad
good_df[lhs > rhs] = np.nan # Anything over the threshold becomes NaN
deg_diff = np.rad2deg(bad_df.azimuth - bad_means.azimuth) # Difference in rad, to deg
lhs = ((deg_diff + 180) % 360 - 180).abs() # Left-hand side for comparison
good_df.loc[lhs > thresh.azimuth.values[0], 'azimuth'] = np.nan # Anything over the threshold becomes NaN
return good_df
def _mean_azimuth_reduction(col1: np.ndarray, col2: np.ndarray) -> np.ndarray:
col1 = np.nan_to_num(col1, nan=col2)
mean_rads = np.arctan2(
np.sin(col1) + np.sin(col2),
np.cos(col1) + np.cos(col2),
)
return mean_rads
def get_means(df: pd.DataFrame) -> pd.DataFrame:
means = df.loc[:, ('MPS', 'area')].groupby(level='polygon_id').mean() | {
"domain": "codereview.stackexchange",
"id": 43130,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, numpy, pandas",
"url": null
} |
python, python-3.x, numpy, pandas
grouped_azimuth = np.reshape(
df.azimuth.values,
(len(df.groupby(level='polygon_id')), -1)
).T
means['azimuth'] = functools.reduce(_mean_azimuth_reduction, grouped_azimuth)
return means
def start() -> None:
"""construct df and display means"""
thresh = pd.DataFrame.from_records(
[{'area': .65, 'MPS': .65, 'azimuth': 60.0}]
)
bad_df = pd.DataFrame(
DATA, index=INDEX, columns=MULTI_COLUMN,
).stack(level=0, dropna=False).rename_axis(('polygon_id', 'validTime'))
bad_means = get_means(bad_df)
good_df = outliers2nan(bad_df, bad_means, thresh)
good_means = get_means(good_df)
print(f"""
BAD
{bad_df}
GOOD
{good_df}
BAD
{bad_means}
GOOD
{good_means}
DIF
{(bad_means-good_means).abs()}
""")
if __name__ == '__main__':
start() | {
"domain": "codereview.stackexchange",
"id": 43130,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, numpy, pandas",
"url": null
} |
c++, memory-management, raii
Title: C++ RAII helper classes for malloc arrays and files
Question: I'm going to use these classes in a program I'm working on, so I want to see if they're correct or could be improved.
https://pastebin.com/qx7ccteT
#include <cstdio>
#include <cstdlib>
class FileHelper
{
public:
FILE* f = NULL;
char buffer[8192];
int bufferPosition = 0;
int bytesRead = 0;
FileHelper(const char* filePath)
{
f = std::fopen(filePath, "rb");
if (!f)
{
throw "FileHelper fopen failure in constructor";
}
}
~FileHelper()
{
if (f)
{
std::fclose(f);
f = NULL;
}
}
bool getCharacter(char& ch)
{
if (bufferPosition == 8192 || bufferPosition == bytesRead)
{
bufferPosition = 0;
bytesRead = fread(buffer, sizeof(char), 8192, f);
if (!bytesRead)
{
return false;
}
}
ch = buffer[bufferPosition++];
return true;
}
};
template <typename T>
class ArrayHelper
{
public:
T* arr = NULL;
size_t capacity = 0;
size_t arrPosition = 0;
ArrayHelper()
{
arr = (T*)std::malloc(8 * sizeof(T));
if (!arr)
{
throw "ArrayHelper malloc failure in constructor";
}
capacity = 8;
}
~ArrayHelper()
{
if (arr)
{
std::free(arr);
arr = NULL;
}
} | {
"domain": "codereview.stackexchange",
"id": 43131,
"lm_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++, memory-management, raii",
"url": null
} |
c++, memory-management, raii
void append(T value)
{
if (arrPosition == capacity)
{
// python's overallocation
int newCapacity = ((size_t)(capacity + 1) + ((capacity + 1) >> 3) + 6) & ~(size_t)3;
T* temp = arr;
arr = (T*)std::realloc(arr, newCapacity * sizeof(T));
if (!arr)
{
arr = temp;
throw "ArrayHelper realloc failure in append method";
}
capacity = newCapacity;
}
arr[arrPosition++] = value;
}
void clear()
{
arrPosition = 0;
}
// copies given to PointerArrayHelper
T* copy()
{
if (!arrPosition)
{
return NULL;
}
T* arrCopy = (T*)std::malloc(arrPosition * sizeof(T));
if (!arrCopy)
{
throw "ArrayHelper malloc failure in copy method";
}
for (size_t i = 0; i < arrPosition; i++)
{
arrCopy[i] = arr[i];
}
return arrCopy;
}
};
template <typename T>
class PointerArrayHelper
{
public:
T* arr = NULL;
size_t capacity = 0;
size_t arrPosition = 0;
PointerArrayHelper()
{
arr = (T*)std::malloc(8 * sizeof(T));
if (!arr)
{
throw "PointerArrayHelper malloc failure in constructor";
}
capacity = 8;
}
~PointerArrayHelper()
{
if (arr)
{
for (size_t i = 0; i < arrPosition; i++)
{
if (arr[i])
{
std::free(arr[i]);
arr[i] = NULL;
}
}
std::free(arr);
arr = NULL;
}
} | {
"domain": "codereview.stackexchange",
"id": 43131,
"lm_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++, memory-management, raii",
"url": null
} |
c++, memory-management, raii
template <typename U>
void append(ArrayHelper<U>& arrHelper)
{
if (arrPosition == capacity)
{
// python's overallocation
int newCapacity = ((size_t)(capacity + 1) + ((capacity + 1) >> 3) + 6) & ~(size_t)3;
T* temp = arr;
arr = (T*)std::realloc(arr, newCapacity * sizeof(T));
if (!arr)
{
arr = temp;
throw "PointerArrayHelper realloc failure in append method";
}
capacity = newCapacity;
}
arr[arrPosition++] = arrHelper.copy();
}
void shrink()
{
T* temp = arr;
arr = (T*)std::realloc(arr, arrPosition * sizeof(T));
if (!arr)
{
arr = temp;
throw "PointerArrayHelper realloc failure in shrink method";
}
capacity = arrPosition;
}
};
int main()
{
try
{
FileHelper fh("test.txt");
PointerArrayHelper<char*> ptrArrHelper;
ArrayHelper<char> arrHelper;
char ch = '\0';
while (fh.getCharacter(ch))
{
if (ch == '\n')
{
arrHelper.append('\0');
ptrArrHelper.append(arrHelper);
arrHelper.clear();
}
else
{
arrHelper.append(ch);
}
}
if (ch != '\n')
{
arrHelper.append('\0');
ptrArrHelper.append(arrHelper);
}
ptrArrHelper.shrink();
for (size_t i = 0; i < ptrArrHelper.capacity; i++)
{
std::printf("%s\n", ptrArrHelper.arr[i]);
}
}
catch (char const* e)
{
std::printf("%s\n", e);
}
return 0;
}
Answer: Overview:
I would note that there a great working versions of these in C++. So you should not do them yourself.
But if we consider this an exercise in learning how to use C++ then lets have a look.
Big Issues: | {
"domain": "codereview.stackexchange",
"id": 43131,
"lm_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++, memory-management, raii",
"url": null
} |
c++, memory-management, raii
FileHelper: Does not implement the rule of 3.
ArrayHelper: Does not implement the rule of 3
ArrayHelper: Does not work for objects with constructor / destructor
Minor Issues:
FileHelper: Does not implement move semantics.
ArrayHelper: Does not implement move semantics.
ArrayHelper: Introduces extra copy on insertion.
ArrayHelper: Does not have move insertion.
ArrayHelper: Does not support emplacing objects
Code Review:
Quick note: FILE* is already buffered.
char buffer[8192];
Sure that is a good constructor.
FileHelper(const char* filePath)
I can see a lot of situations where you don't know the filePath immediately and may want to create the object then open it later. So haveing a default constructor may be useful.
~FileHelper()
{
if (f)
{
std::fclose(f);
// This is a bad idea.
f = NULL;
}
}
The reason it is a bad idea is that it is not necessary (the object is about to not exist the value in the memory it used to occupy does not matter, so waste of an instruction.
But the real reason that it is bad idea is that some debugging environments will help you find double deletes of pointers. If you don't know the rule of three and have created a copy of the object and the constructor is called twice on the same pointer then the debug environment will help you find this situation (but not if you null out the pointer it is using to help you). | {
"domain": "codereview.stackexchange",
"id": 43131,
"lm_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++, memory-management, raii",
"url": null
} |
c++, memory-management, raii
Talking about the rule of three. You did not follow it.
If you do not define a copy constructor or copy assignment operator then the compiler will generate them for you. These will normally do the correct thing. APART from when you have an owned resource in the object that is cleaned up by the destructor. Then it will fail.
Your object has an owned resource FILE* that you clean up in the destructor. As a result the default copy constructor and copy assignment will not work.
{
FileHelper test("Bob");
FileHelper test2(test1);
}
// Blows up here because you have a double delete on the same FILE*
bool getCharacter(char& ch)
{
if (bufferPosition == 8192 || bufferPosition == bytesRead)
^^^^^^^^^^^^^^^^^^^^^^^^^
// This seems like it is not needed.
// If you fill the buffer than would bytesRead not be 8192?
Also there are two different types of situation here:
if (!bytesRead)
{
return false;
}
There is End Of File and there is an error condition. End of file is pretty normal but other situations seem like they would need some extra ability to check for.
In C++ we use nullptr not NULL.
T* arr = NULL;
The macro NULL has issues while nullptr solves these.
You have an issue with you destructor if the type T has a destructor as the array does not clean up the objects by calling it. Thus makes me think you don't call the constructor of T either.
You can limit your ArrayHelper to only support objects that don't have constructor/destructor then you would be fine.
~ArrayHelper()
{
// Add a static assert here that checks that T
// does not have a destructor.
if (arr)
{
// Or make sure you call the destructor of all constructed
// members of the array before you release the memory.
std::free(arr); | {
"domain": "codereview.stackexchange",
"id": 43131,
"lm_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++, memory-management, raii",
"url": null
} |
c++, memory-management, raii
// Like your file helper this is a waste of time.
// And a bad idea as it stops the system from helping you
// debug.
arr = NULL;
}
}
I would break the reallocation part of this function into its own named function. That will make your code easier to read.
Passing the parameter by value:
void append(T value)
This forces a copy of the parameter (this can be expensive for some types of T). Note: It is OK to use a value here as a parameter if you know about and use move semantics. BUT you don't so you should be passing the parameter by reference.
// python's overallocation
int newCapacity = ((size_t)(capacity + 1) + ((capacity + 1) >> 3) + 6) & ~(size_t)3;
OK. That looks complicated. There should be a comment here. You don't need to explain the exact meaning but at least have a link so people can follow the link the explanation.
You correctly handle failed re-allocation.
T* temp = arr;
arr = (T*)std::realloc(arr, newCapacity * sizeof(T));
if (!arr)
{
arr = temp;
throw "ArrayHelper realloc failure in append method";
}
capacity = newCapacity;
But I think it can be written more simply as:
T* temp = (T*)std::realloc(arr, newCapacity * sizeof(T));
if (!temp)
{
throw "ArrayHelper realloc failure in append method";
}
arr = temp;
capacity = newCapacity;
Sure.
arr[arrPosition++] = value;
But if T has a constructor the object is not correctly constructed. You need to construct the value in place.
new (arr + arrPosition) T(value);
++arrPosition;
Like the destructor you need to destroy objects that are no longer in the array.
void clear()
{
arrPosition = 0;
} | {
"domain": "codereview.stackexchange",
"id": 43131,
"lm_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++, memory-management, raii",
"url": null
} |
c++, memory-management, raii
Note this will not correctly copy objects that have constructors.
T* arrCopy = (T*)std::malloc(arrPosition * sizeof(T)); | {
"domain": "codereview.stackexchange",
"id": 43131,
"lm_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++, memory-management, raii",
"url": null
} |
c++, numerical-methods
Title: Calculating sine and cosine
Question: Are there any thing that I have to consider to improve the following code in either performance and others? Any comments and suggestions are welcome!
#include <iostream>
#define PI 3.1415926535897932
double sin(double x, int n = 100)
{
double term = x;
double sum = term;
for (int i = 1; i < n; ++i)
{
term *= -x * x / ((2 * i + 1) * (2 * i));
sum += term;
}
return sum;
}
double cos(double x, int n = 100)
{
double term = 1;
double sum = term;
for (int i = 1; i < n; ++i)
{
term *= -x * x / ((2 * i) * (2 * i - 1));
sum += term;
}
return sum;
}
double sind(double x, int n = 100)
{
return sin(x * PI / 180, n);
}
double cosd(double x, int n = 100)
{
return cos(x * PI / 180, n);
}
int main()
{
std::cout << cosd(180) << std::endl;
}
Answer:
Are there any thing that I have to consider to improve the following code in either performance and others?
Argument reduction
Both sin() and cos() benefit greatly with argument reduction.
Instead of many iterations, first reduce the angle to the primary range.
Following applies to sin(), but similar ideas applies to cos().
Reduce the angle to +/-45° (π/4 radians) using common trigonometry identities.
sin(x + 2*π*n) = sin(x)
sin(x + π) = -sin(x)
sin(x + π/2) = cos(x)
Now apply your polynomial approximation. The Taylor series converges well enough and not so many terms as 100 are needed. (More like < 10.)
Some sample code below that quits iterating once the terms are so small as to not make a difference. It uses the same Taylor series as OP but in a different form. It is from a recursive implementation, yet more often a simple loop is used.
Try x = π/4. (For me: 9 iterations are enough.)
static double my_sin_helper(double xx, double term, unsigned n) {
if (term + 1.0 == 1.0) {
return term;
}
return term - my_sin_helper(xx, xx * term / ((n + 1) * (n + 2)), n + 2);
} | {
"domain": "codereview.stackexchange",
"id": 43132,
"lm_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++, numerical-methods",
"url": null
} |
c++, numerical-methods
// valid for [-pi/2 + pi/2]
static double my_sin_primary(double x) {
return x * my_sin_helper(x * x, 1.0, 1);
}
You will get better and faster results, especially for large x.
Crafted polynomials
Advanced: Crafted polynomials (see Chebyshev polynomials) improve on the Taylor series and can reach the same precision with fewer terms.
This really is how many many good sin() functions work, but beyond the scope of this post.
Only fair argument reduction
π is an irrational number. All finite double are rational. It is impossible to code π exactly as a double. Instead a nearby value is used called machine pi.
Thus the argument reduction of dividing by 2*machine_pi rather than 2π can inject a small error that manifests itself sometimes.
Advanced: Real good radian argument reduction requires extended precision math and is itself a very challenging problem. ARGUMENT REDUCTION FOR HUGE ARGUMENTS:
Good to the Last Bit
Machine pi
Since we cannot code π , use machine pi. #define PI 3.1415926535897932 is OK for common double, but there is no harm in using more precise values like 3.1415926535897932384626433832795. This benefits should code get ported to a more precise double. If using long double, append an L, float an f.
Not so advanced: degree argument reduction
In essence, do a mod 360. Then the sind(360.0) will be 0.0 and not some annoying value like 2.449e-16.
Really good degree argument reduction is far simpler. Research fmod() or remquo(). The reduction can be exact.
Example degree argument reduction. | {
"domain": "codereview.stackexchange",
"id": 43132,
"lm_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++, numerical-methods",
"url": null
} |
c++, game, event-handling
Title: Basic Event manager implementation
Question: I have written a very simple algorithm vizualizer where all input is coming from the mouse and I needed an event manager for that. Since I never wrote one before, I wrote a 30 min implementation to act as a placeholder. Now my question is, whether or not I get the idea of an event manager right, does it look the right way? if not can some of you give me some tipps or links to tutorials.
Mouse event:
#ifndef B9E46EEC_476A_469D_9500_CFB8E28280E2
#define B9E46EEC_476A_469D_9500_CFB8E28280E2
#include <SFML/Window/Event.hpp>
namespace Pathfinding::Events
{
struct MouseEvent
{
MouseEvent(bool eventOnly_, sf::Event::EventType event_, sf::Mouse::Button button_)
: eventOnly(eventOnly_), event(event_), button(button_) {}
bool eventOnly = false;
sf::Event::EventType event;
sf::Mouse::Button button;
};
}
#endif /* B9E46EEC_476A_469D_9500_CFB8E28280E2 */
Mouse data:
#ifndef EF091C2C_702A_4E72_882C_6AB418436A17
#define EF091C2C_702A_4E72_882C_6AB418436A17
#include <SFML\System\Vector2.hpp>
namespace Pathfinding::Events
{
struct MouseData
{
MouseData(sf::Vector2i cursorPosition_) : cursorPosition(cursorPosition_) {}
MouseData(sf::Vector2i cursorPosition_, int32_t wheelDelta_)
: cursorPosition(cursorPosition_), wheelDelta(wheelDelta_) {}
sf::Vector2i cursorPosition;
int32_t wheelDelta;
};
}
#endif /* EF091C2C_702A_4E72_882C_6AB418436A17 */
Event manager headaer
#ifndef D9DC23B1_9143_4917_B212_390EBA2EE1DF
#define D9DC23B1_9143_4917_B212_390EBA2EE1DF
#include <functional>
#include <deque>
#include <SFML/Window/Event.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <vector>
#include "MouseEvent.hpp"
#include "IEventManager.hpp"
#include "MouseData.hpp" | {
"domain": "codereview.stackexchange",
"id": 43133,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, event-handling",
"url": null
} |
c++, game, event-handling
#include "MouseEvent.hpp"
#include "IEventManager.hpp"
#include "MouseData.hpp"
namespace Pathfinding::Events
{
class EventManager final : public Pathfinding::Abstract::IEventManager
{
public:
EventManager() = default;
explicit EventManager(sf::RenderWindow *window);
void addBinding(MouseEvent event, std::function<void(MouseData)> callbackFunc) override;
void pushEvent(sf::Event event) override;
void processEvents() override;
private:
sf::RenderWindow *windowPtr;
std::deque<sf::Event> eventQueue;
std::vector<std::pair<MouseEvent, std::function<void(MouseData)>>> callBacks;
};
}
#endif /* D9DC23B1_9143_4917_B212_390EBA2EE1DF */
Event manager implementation:
#include "EventManager.hpp"
#include <SFML/Window/Event.hpp>
#include "MouseData.hpp"
namespace Pathfinding::Events
{
EventManager::EventManager(sf::RenderWindow *window)
: windowPtr(window)
{
}
void EventManager::addBinding(MouseEvent event, std::function<void(MouseData)> callback)
{
callBacks.push_back({event, callback});
}
void EventManager::pushEvent(sf::Event event)
{
if (event.type == sf::Event::EventType::Closed)
{
windowPtr->close();
}
eventQueue.push_back(event);
} | {
"domain": "codereview.stackexchange",
"id": 43133,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, event-handling",
"url": null
} |
c++, game, event-handling
void EventManager::processEvents()
{
while (!eventQueue.empty())
{
sf::Event ¤tEvent = eventQueue[0];
sf::Vector2i mousePos = sf::Mouse::getPosition(*windowPtr);
for (auto &callBack : callBacks)
{
if (currentEvent.type == callBack.first.event)
{
if (callBack.first.eventOnly || currentEvent.key.code == callBack.first.button)
{
callBack.second(MouseData(mousePos, currentEvent.mouseWheel.delta));
}
}
}
eventQueue.pop_front();
}
}
}
Use case:
auto eventManagerUPtr = std::make_unique<EventManager>(&applicationUPtr->window);
eventManagerUPtr->addBinding({EVENT_AND_KEY, MouseButtonPressed, sf::Mouse::Left},
std::bind(&IGraphOperations::leftMouseButtonPressed, applicationUPtr->graphOpsUPtr.get(), _1));
eventManagerUPtr->addBinding({EVENT_AND_KEY, MouseButtonPressed, sf::Mouse::Right},
std::bind(&IGraphOperations::rightMouseButtonPressed, applicationUPtr->graphOpsUPtr.get(), _1));
eventManagerUPtr->addBinding({EVENT_ONLY, MouseButtonReleased, NO_MOUSE_BUTTON},
std::bind(&IGraphOperations::mouseButtonReleased, applicationUPtr->graphOpsUPtr.get(), _1));
eventManagerUPtr->addBinding({EVENT_ONLY, MouseMoved, NO_MOUSE_BUTTON},
std::bind(&IGraphOperations::mouseMoved, applicationUPtr->graphOpsUPtr.get(), _1));
eventManagerUPtr->addBinding({EVENT_ONLY, MouseMoved, NO_MOUSE_BUTTON},
std::bind(&IGraphOperations::nodeUnderCursor, applicationUPtr->graphOpsUPtr.get(), _1));
eventManagerUPtr->addBinding({EVENT_ONLY, MouseWheelMoved, NO_MOUSE_BUTTON},
std::bind(&IGraphOperations::mouseWheelMoved, applicationUPtr->graphOpsUPtr.get(), _1));
...
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
eventManagerUPtr->pushEvent(event);
}
eventManagerUPtr->processEvents();
draw();
}
... | {
"domain": "codereview.stackexchange",
"id": 43133,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, event-handling",
"url": null
} |
c++, game, event-handling
Answer:
MouseEvent(bool eventOnly_, sf::Event::EventType event_, sf::Mouse::Button button_)
: eventOnly(eventOnly_), event(event_), button(button_) {}
...
MouseData(sf::Vector2i cursorPosition_) : cursorPosition(cursorPosition_) {}
MouseData(sf::Vector2i cursorPosition_, int32_t wheelDelta_)
: cursorPosition(cursorPosition_), wheelDelta(wheelDelta_) {}
We don't need constructors like this in modern C++, as we can use aggregate initialization to initialize structs (including designators for specific members in C++20).
EventManager() = default;
Is this necessary? An EventManager created like this could never be used (due to the invalid windowPtr).
void EventManager::pushEvent(sf::Event event)
{
if (event.type == sf::Event::EventType::Closed)
{
windowPtr->close();
}
eventQueue.push_back(event);
}
Checking for the Closed event and closing the window here is a bit unexpected. It might be better to do it in the processEvents() loop instead.
We probably shouldn't store the callbacks / bindings in the EventManager class itself. At the moment, if we want to use a different set of bindings, we'd have to recreate the EventManager. If we have a separate class, we could pass the bindings into the processEvents() function:
struct EventCallbacks
{
std::vector<std::pair<MouseEvent, std::function<void(MouseData)>>> mouseCallbacks;
// ... keyboard, etc...
};
class EventManager
{
public:
...
void processEvents(EventCallbacks const& callbacks);
};
That way, we can easily switch out the callbacks if we want to move to a different app state / input mode.
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
eventManagerUPtr->pushEvent(event);
}
eventManagerUPtr->processEvents();
draw();
} | {
"domain": "codereview.stackexchange",
"id": 43133,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, event-handling",
"url": null
} |
c++, game, event-handling
Right now there doesn't seem to be a reason to have a second queue to push events to before processing them, so we could just process events directly (either pass individual events into processEvents, or do the polling in processEvents). | {
"domain": "codereview.stackexchange",
"id": 43133,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game, event-handling",
"url": null
} |
python, regex
Title: Automate the Boring Stuff CH 7: password strength test
Question: This exercise comes from Automate the Boring Stuff Ch 7. The assignment is to use regular expressions to test the strength of a password. Password must be >= 8 characters, contain at least one uppercase letter, one lowercase letter, and one number.
Any and all criticisms/suggestions for improving the code are welcome.
# function to test the strength of a password
import re
# pw = password
# function receives user input (password) as argument
def pw_strength_test(pw: str) -> bool:
is_strong = True # final return value, change to False if test fails
# lowercase, uppercase, and number regexes
lower_regex = re.compile(r"[a-z]")
upper_regex = re.compile(r"[A-Z]")
num_regex = re.compile(r"\d")
# store matches into lists
lower_groups = lower_regex.findall(pw)
upper_groups = upper_regex.findall(pw)
num_groups = num_regex.findall(pw)
# def a function to iterate over the regex lists
# pass list and type into function
# return number of items of that type
def count_matches(match_list, match_type):
count = 0
try:
if match_type == str and match_list[0].islower() == True:
count = len(match_list)
elif match_type == str and match_list[0].isupper() == True:
count = len(match_list)
elif match_type == int:
count = len(match_list)
# if no items in list, IndexError will be thrown
except IndexError:
print('IndexError thrown. One or more match lists are empty.')
return count | {
"domain": "codereview.stackexchange",
"id": 43134,
"lm_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, regex",
"url": null
} |
python, regex
return count
# store count into variables
lower_count = count_matches(lower_groups, str)
upper_count = count_matches(upper_groups, str)
num_count = count_matches(num_groups, int)
# if any list contains 0 items, pw test fails
if lower_count == 0 or upper_count == 0 or num_count == 0:
is_strong = False
print("Error: password strength test failed.")
# if less than 8 characters, pw test fails
elif (lower_count + upper_count + num_count) < 8:
is_strong = False
print("Error: password strength test failed.")
else:
print("Password strength test passed.")
return is_strong
print('Please enter your password.')
pw_strength_test(str(input()))
```
Answer: The current implementation is too complex. As soon as you get the results
from the three findall() calls, you have essentially everything you need, but
the function continues with over a dozen lines of unnecessary stuff. Remember
that an empty collection evaluates to false in boolean terms, so if the goal is
just to write a function that returns true or false, you could wrap up the
logic as simply as this:
return lower_groups and upper_groups and num_groups and len(pw) >= 8 | {
"domain": "codereview.stackexchange",
"id": 43134,
"lm_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, regex",
"url": null
} |
python, regex
A password checker should not print. A password testing function should be
a purely data-oriented function: it should take a password and return data; it
should not have other side effects, such as printing. The returned data could be a
bool (the simplest implementation) or it could be some other type of object:
for example, a (bool, error_message) tuple; or just an error_message or
None (the code example below takes the latter approach, reframing the
function as a password-error-finder). In any case, you want to keep the
in-depth checking logic in an easily-tested, data-oriented function. Leave the
printing to a different part of the program.
Collections are often more powerful than separate variables. If you do want
the function to provide a helpful error message (the current messages are not
helpful, because they do not tell the user specifically what's wrong), you
should consider bundling the checks into a collection so that any failed check
can be linked to its corresponding message. The code
below illustrates one way to do that kind of
thing. It also provides a compact illustration of how data-centric
thinking can radically simplify code. The function focuses
nearly all of its attention on building a convenient data
structure. And once we have that data, the rest of the algorithm/logic becomes almost trivial.
import re
from typing import Tuple
def check_password(pw: str) -> Tuple[str]:
checks = {
'must be at least 8 characters': r'.{8}',
'must contain lowercase letter': r'[a-z]',
'must contain uppercase letter': r'[A-Z]',
'must contain digit': r'\d',
}
return tuple(
err_msg
for err_msg, pattern in checks.items()
if not re.search(pattern, pw)
) | {
"domain": "codereview.stackexchange",
"id": 43134,
"lm_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, regex",
"url": null
} |
python, datetime, pandas
Title: Extraction of subsets by date and intervals from a dataframe with a specific date format
Question: Given the following dataframe:
| ID | date |
|---------------------|--------------------------------|
| 1 | 2022-02-03 22:01:12+01:00 |
| 2 | 2022-02-04 21:11:21+01:00 |
| 3 | 2022-02-05 11:11:21+01:00 |
| 4 | 2022-02-07 23:01:12+01:00 |
| 5 | 2022-02-07 14:31:14+02:00 |
| 6 | 2022-02-08 18:12:01+02:00 |
| 7 | 2022-02-09 20:21:02+02:00 |
| 8 | 2022-02-11 15:41:25+02:00 |
| 9 | 2022-02-15 11:21:27+02:00 |
I would like to optimise the code of the following function:
Returns all rows whose date (YYYY-MM-DD) matches the date passed by parameter.
# Function to search by exact %Y-%m-%d date
def select_exact_date(df, date):
date = pd.to_datetime(date, format='%Y-%m-%d %H:%M:%S')
date_dt = date.date()
# Create a copy of the original df
subset = df.copy()
# Creates a temporary column to store the values related to the specific date
subset['tmp_date'] = subset['date'].apply(lambda a: a.date())
mask = (subset['tmp_date'] == date_dt)
df = df.loc[mask]
return df
Result:
select_exact_date(df, '2022-02-07')
#Output
| ID | date |
|---------------------|--------------------------------|
| 4 | 2022-02-07 23:01:12+01:00 |
| 5 | 2022-02-07 14:31:14+02:00 |
I hope you can help me. Thank you in advance.
Answer:
That doesn't matter | {
"domain": "codereview.stackexchange",
"id": 43135,
"lm_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, datetime, pandas",
"url": null
} |
python, datetime, pandas
I hope you can help me. Thank you in advance.
Answer:
That doesn't matter
Context does matter. A strict interpretation of the site guidelines would consider your question off-topic due to insufficient context, since code can't be reviewed in a vacuum (a black box, as you put it). If you think context doesn't matter in a review, then you might as well say that reviewing the code doesn't matter, either.
In this case, it does matter where your date comes from, because you've failed to type-hint it so it could be anything that pd.to_datetime accepts:
arg: int, float, str, datetime, list, tuple, 1-d array, Series, DataFrame/dict-like
I'm going to make a sweeping assumption: that your date parameter is a datetime.date object, as it should be.
It seems that you've left the date column full of datetime.datetime timezone-aware objects. Working with Pandas will be made more difficult than it needs to be using this approach. Consider instead coercing the date column to an actual Pandas UTC datetime, avoiding apply() like the plague:
from datetime import date
from io import StringIO
import pandas as pd
# ...
f = StringIO(
'''ID,date
1,2022-02-03 22:01:12+01:00
2,2022-02-04 21:11:21+01:00
3,2022-02-05 11:11:21+01:00
4,2022-02-07 23:01:12+01:00
5,2022-02-07 14:31:14+02:00
6,2022-02-08 18:12:01+02:00
7,2022-02-09 20:21:02+02:00
8,2022-02-11 15:41:25+02:00
9,2022-02-15 11:21:27+02:00'''
)
df = pd.read_csv(
f,
parse_dates=['date'],
index_col='ID',
)
date_to_select = date(2022, 2, 7)
utc_dates = pd.to_datetime(df.date, utc=True).dt.date
matching_rows = df[utc_dates == date_to_select]
If it matters that the exact local timezone's day boundaries be respected you'll need to get more creative. | {
"domain": "codereview.stackexchange",
"id": 43135,
"lm_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, datetime, pandas",
"url": null
} |
c#
Title: Align Members in a ListBox – get correct number of needed TABs | {
"domain": "codereview.stackexchange",
"id": 43136,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
c#
Question: I am currently still using a ListBox. In this, all products are displayed one below the other. For each individual product, properties are separated with tab characters. I would like to align the properties sensibly, but only look at the BrandName for now. Therefore, I get the length of the longest brand name and check for each individual name how many characters I must bridge and fill these gaps with tabs.
I think I've already built a sufficient function here, but I think you guys can do better.
Yes, I know a DataGridView is better compared to a ListBox, but my point today is to make it look reasonable for now.
The font is Segoe UI, font size is 12. I couldn't figure out the right TabWidth unfortunately – I've seen questions on Stack Overflow where they tried to use a comma number, based on “average width of a char” (I guess that's only valid for the English language).
Microsoft Visual Studio Community 2019; version 16.11.11.
WinForms application (.NET Framework 4.8) with C#.
private void update_ListBox()
{
ListBoxEx1.Items.Clear();
//ListBoxEx1.Items.AddRange(AllEntries.Select(x => $"{x.product.BrandName}{"\t"}{x.product.ModelName}{"\t"}{x.CreationTime.ToString("d", Deu)}{"\t"}{x.product.DescriptionOrNotes}{"\t"}{Math.Round(x.product.SellingPrice, 2)} €").ToArray());
int Max = 0;
for (int i = 0; i < AllEntries.Count; i++)
{
if (AllEntries[i].product.BrandName.Length > Max)
{
Max = AllEntries[i].product.BrandName.Length;
}
}
for(int i = 0; i < AllEntries.Count; i++)
{
ListBoxEx1.Items.Add(ToStringForListbox(Max,
AllEntries[i].product.BrandName,
AllEntries[i].product.ModelName, | {
"domain": "codereview.stackexchange",
"id": 43136,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
c#
AllEntries[i].product.ModelName,
AllEntries[i].CreationTime,
AllEntries[i].product.DescriptionOrNotes,
AllEntries[i].product.SellingPrice));
}
} | {
"domain": "codereview.stackexchange",
"id": 43136,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
c#
private string ToStringForListbox(int Maximum_length,
string BrandName,
string ModelName,
DateTime CreationTime,
string DescriptionOrNotes,
decimal SellingPrice)
{
if (!string.IsNullOrEmpty(BrandName))
{
string MultiTab;
// zu überbrückende Länge
int Length_to_be_overridden = Maximum_length - BrandName.Length;
int TabWidth = 10;
int how_many_Tabs = Length_to_be_overridden / TabWidth;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("\t");
for (int i = 0; i < how_many_Tabs; i++)
{
sb.Append("\t");
}
MultiTab = sb.ToString();
return $"{BrandName}{MultiTab}{ModelName}{"\t"}{CreationTime.ToString("d", Deu)}{"\t"}{DescriptionOrNotes}{"\t"}{Math.Round(SellingPrice, 2)} €";
}
else
{
// Macron ¯
return $"{Convert.ToChar(0xAF)}{"\t"}{ModelName}{"\t"}{CreationTime.ToString("d", Deu)}{"\t"}{DescriptionOrNotes}{"\t"}{Math.Round(SellingPrice, 2)} €";
}
}
Answer: The naming guidelines for .NET should be used to name things, because reading and understanding code which follows such guidelines is much easier for other developers.
For .NET:
methods should be named using PascalCase casing
method arguments should be named using camelCase casing
local and class variables/fields should be named using camelCase casing
snake_case casing should't be used | {
"domain": "codereview.stackexchange",
"id": 43136,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
c#
ToStringForListbox()
Returning early by changing the if condition will save you one level of indentation, which makes your code more readable.
if (string.IsNullOrEmpty(BrandName))
{
// Macron ¯
return $"{Convert.ToChar(0xAF)}{"\t"}{ModelName}{"\t"}{CreationTime.ToString("d", Deu)}{"\t"}{DescriptionOrNotes}{"\t"}{Math.Round(SellingPrice, 2)} €";
}
string MultiTab;
// zu überbrückende Länge
...
return $"{BrandName}{MultiTab}{ModelName}{"\t"}{CreationTime.ToString("d", Deu)}{"\t"}{DescriptionOrNotes}{"\t"}{Math.Round(SellingPrice, 2)} €";
Comments should be used to tell why something is done in the way it is done. What is done should be told by the code itself by using meaningful names for naming things. In addition in software-development it is common to use english for comments as well.
This
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("\t");
for (int i = 0; i < how_many_Tabs; i++)
{
sb.Append("\t");
}
MultiTab = sb.ToString();
can be simplified by using the overloaded constructor of the string class like so
MultiTab = new string('\t', how_many_Tabs + 1);
Instead of passing 6 arguments to the method it would be more readable to just pass Maximum_length and an item of whatever type AllEntries[i] is.
update_ListBox()
Like already mentioned, naming things is important. You should be able to grasp at first glance what something is about. Looking at ListBoxEx1 Sam the maintainter whould need to guess what this is. Sure a ListBox but what will it contain? Sam the maintainer would need to read more code only to check what and how it is used. Are there more ListBoxExs because of the 1? Such stuff makes finding bugs hard and should be avoided.
Finding the Max of the BrandName.Length can be simplified by using some linq-magic like so
int Max = AllEntries.Max(entry => entry.product.BrandName.Length); | {
"domain": "codereview.stackexchange",
"id": 43136,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
c, array, stack, macros
Title: Pseudo-Generic Array Stack in C
Question: I have implemented an array based pseudo-generic stack in C using macros. The code works fine for all data types. Is it a good idea to implement such a data structure using macros?
array_stack.h
#ifndef ARRAY_STACK_H
#define ARRAY_STACK_H
#include<stdlib.h>
#define array_stack(type) struct{size_t _size;size_t _capacity;type*_arr;}
#define stack_init(stack) do{\
stack._capacity=1;\
stack._size=0;\
stack._arr=calloc(stack._capacity,sizeof(*stack._arr));\
}while(0)
#define stack_push(stack,data) do{\
if(stack._size==stack._capacity)\
{\
stack._capacity*=2;\
void*new_array=realloc(stack._arr,stack._capacity*sizeof(*stack._arr));\
stack._arr=new_array;\
}\
stack._arr[stack._size]=data;\
stack._size++;\
\
}while(0)
#define stack_pop(stack) if(stack._size!=0) stack._size--
#define stack_top(stack) (stack._size>0) ? stack._arr[stack._size-1] : *stack._arr //returns address of array if stack is empty
#define stack_empty(stack) (stack._size==0)
#define stack_length(stack) stack._size
#endif
Usage in main.c
#include<stdio.h>
#include<stdlib.h>
#include"array_stack.h"
#include<string.h>
int main(int argc,char**argv)
{
array_stack(char)chars;
array_stack(double)nums;
stack_init(chars);
stack_init(nums);
const char*text="AzZbTyU";
for (size_t i = 0; i < strlen(text); i++)
stack_push(chars,text[i]);
stack_push(nums,3.14);
stack_push(nums,6.67);
stack_push(nums,6.25);
stack_push(nums,0.00019);
stack_push(nums,22.2222);
printf("Printing character stack: ");
while(!stack_empty(chars))
{
printf("%c ",stack_top(chars));
stack_pop(chars);
}
printf("\n");
printf("Printing double stack: ");
while(!stack_empty(nums))
{
printf("%lf ",stack_top(nums));
stack_pop(nums);
}
printf("\n");
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 43137,
"lm_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, array, stack, macros",
"url": null
} |
c, array, stack, macros
Answer: A better than usual implementation.
Is it a good idea to implement such a data structure using macros?
It is tricky to do well. User code looks like it is using non-macro code, yet the usual concerns about multiple execution of arguments and lack of function addresses occur.
Unnecessary asymmetry
stack_init() and stack_push() are wrapped in a do { ... } while (0).
Why stack_pop() not wrapped?
Do you want to allow:
stack_pop(stack)
else puts("Hmmm");
How to create a pointer to a function? How to create a pointer to the stack?
// Does not work
size_t (*f)() = stack_empty;
array_stack(char)chars;
what_type_here *p = &chars;
Misleading comment
#define stack_top(stack) (stack._size>0) ? stack._arr[stack._size-1] : *stack._arr
//returns address of array if stack is empty
Code does not return an address ... if stack is empty. Instead it returns the data type like char or double.
(Comment hidden in the far right. Consider formatting to a smaller nominal line length.)
Lack of documentation
array_stack.h deserves comments describing the overall functionality and limitations. I'd comment each "function" as well.
Other
Test include *.h independence
Someplace, code as follows to test that "array_stack.h" does not rely on the .c file first including other include files.
// #include<stdio.h>
// #include<stdlib.h>
// #include"array_stack.h"
#include"array_stack.h"
#include<stdio.h>
#include<stdlib.h>
Overly compact style
// array_stack(char)chars;
array_stack(char) chars;
// ^ space
Growth
Consider starting stack with size 0.
#define stack_init(stack) do{\
stack._capacity=0;\
stack._size=0;\
stack._arr=NULL;\
}while(0)
Grow with ._capacity = ._capacity*2 + 1.
Avoid repeated O(n) calls
// for (size_t i = 0; i < strlen(text); i++)
for (size_t i = 0; text[i]; i++) | {
"domain": "codereview.stackexchange",
"id": 43137,
"lm_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, array, stack, macros",
"url": null
} |
c#, unity3d
Title: Moving GameObject in a square pattern (C# Unity)
Question: I'm new to Unity/C# and I'm trying to get a 3D GameObject in a square pattern, using transform.position:
void Update()
{
bool flag = true;
if (transform.position.x < 4 && transform.position.y >= -4 && flag == true)
{
Debug.Log("right");
transform.position = new Vector3(transform.position.x + 1, transform.position.y, 0);
}
else if (transform.position.x == 4 && transform.position.y >= -4 && transform.position.y <= 4 && flag == true)
{
transform.position = new Vector3(transform.position.x, transform.position.y + 1, 0);
Debug.Log("up");
if (transform.position.y >= 4)
{
flag = false;
}
}
else if (transform.position.x <= 4 && transform.position.x > -4 && transform.position.y == 4 && flag == false)
{
transform.position = new Vector3(transform.position.x - 1, transform.position.y, 0);
Debug.Log("left");
}
else if (transform.position.x == -4 && transform.position.y <= 4 && flag == false)
{
transform.position = new Vector3(transform.position.x, transform.position.y - 1, 0);
Debug.Log("down");
if (transform.position.y == -4)
{
flag = true;
}
}
As you can see, it's very limited in it's functionality because it uses hardcoded values on position to work.
Is there any way to improve this? Thanks so much! | {
"domain": "codereview.stackexchange",
"id": 43138,
"lm_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#, unity3d",
"url": null
} |
c#, unity3d
Answer: General development and readability advice
This code may make sense to you because you wrote it, but it doesn't make sense to a reader who has no context.
The first example here: what is flag? What does it represent? What does it do? Based on my prior knowledge I can make an educated guess that it involves keeping track of the direction of travel, but if you were to ask me "what happens when flag is set to false?", I wouldn't be able to answer you even after having read your code several times.
There were claims in the comments that your code does not currently work as intended. I am genuinely uncertain of that, simply because your logic is so hard to follow.
This is one of those cases where you took a very complex route from the beginning, which made it hard to spot any alleged mistakes in the described behavior. Had you take a step back, analysed and abstracted your approach, and then implemented it; it would've been easier to keep it all straight.
The problem here is that you've overly condensed your logic. You've done the precise math and logic on what you want to have happen, and then you wrote it in the most terse and dense way you could.
This may be very efficient to write, but it is horribly inefficient to read. Code is read more than it is written, and you should invest more effort into the writing of your code in ways that it saves you effort on having to read the code afterwards.
To that end, let's start cleaning up the code by labeling things clearly, rather than putting the raw numbers in the logic directly. A prime candidate here is the logic for executing a move.
Move execution logic
Did you know that you can add Vector3 together without needing to pull it apart into its coordinates, individually adjust those, and then put it back together? This significantly simplifies the code.
First, define the vectors that describe the movement:
private const Vector3 MoveUp = new Vector3( 0, -1, 0); | {
"domain": "codereview.stackexchange",
"id": 43138,
"lm_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#, unity3d",
"url": null
} |
c#, unity3d
private const Vector3 MoveUp = new Vector3( 0, -1, 0);
private const Vector3 MoveDown = new Vector3( 0, 1, 0);
private const Vector3 MoveLeft = new Vector3(-1, 0, 0);
private const Vector3 MoveRight = new Vector3( 1, 0, 0); | {
"domain": "codereview.stackexchange",
"id": 43138,
"lm_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#, unity3d",
"url": null
} |
c#, unity3d
And then your logic can simply add this vector to the original position:
if (...)
{
Debug.Log("right");
transform.position += this.MoveRight;
}
// and so on | {
"domain": "codereview.stackexchange",
"id": 43138,
"lm_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#, unity3d",
"url": null
} |
c#, unity3d
This significantly cuts down on the amount of logic and reading complexity in your snippet.
Move decision logic
Secondly, the other meaty bit of logic in your code is your if evaluations. Just by reading it, I don't know what it is that each if is trying to verify. It requires a lot of deep thought to understand it. Again, we must improve the readability.
I'm also going to slightly change your approach. Rather than have them execute the move, I'm going to have them decide what the move is. The execution of the chosen move is not something that needs to be repeated in every individual if, it can be done afterwards based on the move that has been decided.
I suspect that what led you to using your flag boolean is the fact that you "forget" which direction you were traveling in between subsequent calls of the Update method. This flag logic is very contrived. While it's possible to get it working, it's not easy (nor necessary) to do so. The better approach here is to remember which direction you were moving in, so you don't have to repeatedly figure it out. This is achieved by storing the "current direction" in a class field (or property), so that its value it retained inbetween subsequent calls to the Update method.
I'm also going to change the style of your evaluations. Right now, you're evaluating if you should continue moving. But it makes more sense to (by default) intend to move in the same direction as before; but check if you reach a certain boundary, in which case you change your desired direction. In other words, the if blocks will evaluate if you should change your direction, not if you should continue it.
Think of your square as a bounding box. Each side of the box represents a "stop" when you're moving in the direction that would cross the boundaries.
stop IF moving up
┌───────────────────────┐
│ │
stop IF moving left │ │ stop IF moving right | {
"domain": "codereview.stackexchange",
"id": 43138,
"lm_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#, unity3d",
"url": null
} |
c#, unity3d
stop IF moving left │ │ stop IF moving right
│ │
└───────────────────────┘
stop IF moving down | {
"domain": "codereview.stackexchange",
"id": 43138,
"lm_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#, unity3d",
"url": null
} |
c#, unity3d
If you use this approach, it simplifies the evaluations you have to do. I'm assuming a clockwise movement. For counter-clockwise, you'll have to change what the next direction is when you hit a boundary.
Vector3 currentDirection = this.MoveRight; // default movement
public void Update()
{
// stop IF moving right
if(currentDirection == this.MoveRight && transform.position.x >= 4)
{
// start moving down
currentDirection = this.MoveDown;
}
// stop IF moving down
else if(currentDirection == this.MoveDown && transform.position.y >= 4)
{
// start moving left
currentDirection = this.MoveLeft;
}
// stop IF moving left
else if(currentDirection == this.MoveLeft && transform.position.x <= -4)
{
// start moving up
currentDirection = this.MoveUp;
}
// stop IF moving up
else if(currentDirection == this.MoveUp && transform.position.y <= -4)
{
// start moving right
currentDirection = this.MoveRight;
}
// Whatever the chosen move is, execute it
transform.position += currentDirection;
}
Some remarks: | {
"domain": "codereview.stackexchange",
"id": 43138,
"lm_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#, unity3d",
"url": null
} |
c#, unity3d
Some remarks:
The comments really help a new reader with finding your way through the ifs very quickly. I actually made a mistake in the original snippet, but I was able to quickly fix it because the comments made it clear which block did what.
In most cases, none of the if blocks will be entered - these are all the cases where the character can keep moving in the direction that they were already moving. The if blocks will only be entered when you need to change your direction.
Make sure to define currentDirection outside of the Update method, as you need it to be remembered inbetween subsequent calls to the Update method
Note the use of Vector3 equality checks. I opted for == as it is less strict than .Equals and more likely to yield the desired behavior.
Because I'm using <= and >=, this will also work for a character who is currently outside of the intended boundary. After doing a full loop (4 direction changes), they will have encountered the boundary and from then on stay inside the boundary you've defined.
Avoiding hardcoded values
Now that we've reworked the logic, we can remove the hardcoded 4 and -4 magic numbers. Just like we did for the movements, we're going to define private fields:
private int TopBoundary = -4;
private int RightBoundary = 4;
private int BottomBoundary = 4;
private int LeftBoundary = -4;
How you set/change these values is up to you. Either they're hardcoded (which is what I did here), but you could also have these be set via a constructor or public method, or make them into publically settable properties in their own right.
In any case, just replace the original hardcoded value with the field/property that represents the boundary:
// stop IF moving right
if(currentDirection == this.MoveRight && transform.position.x >= this.RightBoundary)
{
// start moving down
currentDirection = this.MoveDown;
} | {
"domain": "codereview.stackexchange",
"id": 43138,
"lm_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#, unity3d",
"url": null
} |
c#, unity3d
I hope you agree that the final result is much more readable for anyone who doesn't have hands on knowledge of how it was written, whether they are other developers or you in the future when it's not as fresh in your memory anymore.
Comment
For your everyday business development practices, I would argue that transform.position.x >= this.RightBoundary is a bit too meaty to put in a chain of if blocks, and would be better abstracted into a clearly labeled variable or method.
However, your context is one of game development; where coordinate-based operations are so very common that abstracting them all into their own methods can lead to a massive explosion of "use once" methods.
The assumption here is that a game developer will learn to innately read and understand simple coordinate operations without needing to further abstract them for readability's sake. | {
"domain": "codereview.stackexchange",
"id": 43138,
"lm_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#, unity3d",
"url": null
} |
performance, vba, excel, outlook
Title: Excel VBA to Fetch email addresses from inbox and sent items folders
Question: I am using the following VBA to fetch multiple specified Email addresses from inbox and sent items folder also including cc and bcc
for eg(gmail.com;yahoo.com) must return all mails having that domain name.
the problem is it takes a whole lot of time and I mean if a person has 2k emails (overall) he might have to wait for approx. 2 hours.
The internet speed isn't an issue and it gives desired output of specified email addresses.
Checked some sources how to make code faster i got to know about restrict function when applied through DASL filter and limit number of items in a loop. I applied the same but the result is still the same and fetching is still slow.
As new into VBA I don't know all about optimization and still learning.
Any other sources or ways to make the fetching and execution faster ?
code given for reference
Option Explicit | {
"domain": "codereview.stackexchange",
"id": 43139,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel, outlook",
"url": null
} |
performance, vba, excel, outlook
Sub GetInboxItems()
'all vars declared
Dim ol As Outlook.Application
Dim ns As Outlook.Namespace
Dim fol As Outlook.Folder
Dim i As Object
Dim mi As Outlook.MailItem
Dim n As Long
Dim seemail As String
Dim seAddress As String
Dim varSenders As Variant
'for sent mails
Dim a As Integer
Dim b As Integer
Dim objitem As Object
Dim take As Outlook.Folder
Dim xi As Outlook.MailItem
Dim asd As String
Dim arr As Variant
Dim K As Long
Dim j As Long
Dim vcc As Variant
Dim seemail2 As String
Dim seAddress2 As String
Dim varSenders2 As Variant
Dim strFilter As String
Dim strFilter2 As String
'screen wont refresh untill this is turned true
Application.ScreenUpdating = False
'now assigning the variables and objects of outlook into this
Set ol = New Outlook.Application
Set ns = ol.GetNamespace("MAPI")
Set fol = ns.GetDefaultFolder(olFolderInbox)
Set take = ns.GetDefaultFolder(olFolderSentMail)
Range("A3", Range("A3").End(xlDown).End(xlToRight)).Clear
n = 2
strFilter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:fromemail" & Chr(34) & " like '%" & seemail & "'"
strFilter2 = "@SQL=" & Chr(34) & "urn:schemas:httpmail:sentitems" & Chr(34) & " like '%" & seemail2 & "'"
'this one is for sent items folder where it fetches the emails from particular people
For Each objitem In take.Items.Restrict(strFilter2)
If objitem.Class = olMail Then
Set xi = objitem
n = n + 1
seemail2 = Worksheets("Inbox").Range("D1")
varSenders2 = Split(seemail2, ";")
For K = 0 To UBound(varSenders2)
'this is the same logic as the inbox one where if mail is found and if the mail is of similar kind then and only it will return the same | {
"domain": "codereview.stackexchange",
"id": 43139,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel, outlook",
"url": null
} |
performance, vba, excel, outlook
If xi.SenderEmailType = "EX" Then
seAddress2 = xi.Sender.GetExchangeUser.PrimarySmtpAddress
If InStr(1, seAddress2, varSenders2(K), vbTextCompare) Then
Cells(n, 1).Value = xi.Sender.GetExchangeUser().PrimarySmtpAddress
Cells(n, 2).Value = xi.SenderName
ActiveSheet.UsedRange.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
On Error Resume Next
Range("A3:A9999").Select
Selection.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End If
'this is the smpt address (regular address)
ElseIf xi.SenderEmailType = "SMTP" Then
seAddress2 = xi.SenderEmailAddress
If InStr(1, seAddress2, varSenders2(K), vbTextCompare) Then
Cells(n, 1).Value = xi.SenderEmailAddress
Cells(n, 2).Value = xi.SenderName
ActiveSheet.UsedRange.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
On Error Resume Next
Range("A3:A9999").Select
Selection.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End If
'this one fetches the cc part recipient denotes cc
For j = xi.Recipients.Count To 1 Step -1
If (xi.Recipients.Item(j).AddressEntry.Type = "EX") Then
vcc = xi.Recipients.Item(j).Address
If InStr(1, vcc, varSenders2(K), vbTextCompare) Then
Cells(n, 1).Value = xi.Recipients.Item(j).AddressEntry.GetExchangeUser.PrimarySmtpAddress
Cells(n, 2).Value = xi.Recipients.Item(j).Name | {
"domain": "codereview.stackexchange",
"id": 43139,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel, outlook",
"url": null
} |
performance, vba, excel, outlook
Cells(n, 2).Value = xi.Recipients.Item(j).Name
ActiveSheet.UsedRange.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
On Error Resume Next
Range("A3:A9999").Select
Selection.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End If
Else
vcc = xi.Recipients.Item(j).Address
If InStr(1, vcc, varSenders2(K), vbTextCompare) Then
Cells(n, 1).Value = xi.Recipients.Item(j).Address
Cells(n, 2).Value = xi.Recipients.Item(j).Name
ActiveSheet.UsedRange.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
On Error Resume Next
Range("A3:A9999").Select
Selection.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End If
End If
Next j
Else: seAddress2 = ""
End If
For a = 1 To take.Items.Count
n = 3
'this also fetches the recipient emails
If TypeName(take.Items(a)) = "MailItem" Then
For b = 1 To take.Items.Item(a).Recipients.Count
asd = take.Items.Item(a).Recipients(b).Address
If InStr(1, asd, varSenders2(K), vbTextCompare) Then
Cells(n, 1).Value = asd
Cells(n, 2).Value = take.Items.Item(a).Recipients(b).Name | {
"domain": "codereview.stackexchange",
"id": 43139,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel, outlook",
"url": null
} |
performance, vba, excel, outlook
Cells(n, 2).Value = take.Items.Item(a).Recipients(b).Name
n = n + 1
End If
Next b
End If
Next a
Next K
End If
Next objitem
For Each i In fol.Items.Restrict(strFilter)
If i.Class = olMail Then
Set mi = i
'objects have been assigned and can be used to fetch emails
seemail = Worksheets("Inbox").Range("D1")
varSenders = Split(seemail, ";")
n = n + 1
For K = 0 To UBound(varSenders) | {
"domain": "codereview.stackexchange",
"id": 43139,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel, outlook",
"url": null
} |
performance, vba, excel, outlook
'similar logic as above
If mi.SenderEmailType = "EX" Then
seAddress = mi.Sender.GetExchangeUser().PrimarySmtpAddress
If InStr(1, seAddress, varSenders(K), vbTextCompare) Then
Cells(n, 1).Value = mi.Sender.GetExchangeUser().PrimarySmtpAddress
Cells(n, 2).Value = mi.SenderName
ActiveSheet.UsedRange.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
On Error Resume Next
Range("A3:A9999").Select
Selection.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End If
ElseIf mi.SenderEmailType = "SMTP" Then
seAddress = mi.SenderEmailAddress
If InStr(1, seAddress, varSenders(K), vbTextCompare) Then
Cells(n, 1).Value = mi.SenderEmailAddress
Cells(n, 2).Value = mi.SenderName
ActiveSheet.UsedRange.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
On Error Resume Next
Range("A3:A9999").Select
Selection.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End If
For j = mi.Recipients.Count To 1 Step -1
If (mi.Recipients.Item(j).AddressEntry.Type = "EX") Then
vcc = mi.Recipients.Item(j).Address
If InStr(1, vcc, varSenders(K), vbTextCompare) Then
Cells(n, 1).Value = mi.Recipients.Item(j).AddressEntry.GetExchangeUser.PrimarySmtpAddress
Cells(n, 2).Value = mi.Recipients.Item(j).Name | {
"domain": "codereview.stackexchange",
"id": 43139,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel, outlook",
"url": null
} |
performance, vba, excel, outlook
Cells(n, 2).Value = mi.Recipients.Item(j).Name
ActiveSheet.UsedRange.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
On Error Resume Next
Range("A3:A9999").Select
Selection.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End If
Else
vcc = mi.Recipients.Item(j).Address
If InStr(1, vcc, varSenders(K), vbTextCompare) Then
Cells(n, 1).Value = mi.Recipients.Item(j).Address
Cells(n, 2).Value = mi.Recipients.Item(j).Name
ActiveSheet.UsedRange.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
On Error Resume Next
Range("A3:A9999").Select
Selection.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End If
End If
Next j
Else: seAddress = ""
End If
Next K
End If
Next i
ActiveSheet.UsedRange.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
On Error Resume Next
Range("A3:A9999").Select
Selection.SpecialCells(xlCellTypeBlanks).EntireRow.Delete | {
"domain": "codereview.stackexchange",
"id": 43139,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel, outlook",
"url": null
} |
performance, vba, excel, outlook
Set take = Nothing
Set mi = Nothing
Application.ScreenUpdating = True
End Sub
Answer: Performance
Each statement that references ActiveSheet is affecting the performance/speed. Rather than using the ActiveSheet repeatedly create a named sheet and assign that sheet to a sheet variable. Also create Range variables, all of the Select statements are affecting the performance. Any Select statements should be outside loops if possible.
Use With statements to speed up internal operations.
DRY Code
There is a programming principle called the Don't Repeat Yourself Principle sometimes referred to as DRY code. If you find yourself repeating the same code mutiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.
Complexity
There is only one subroutine, and when I copied the subroutine it was 241 lines long. The general rule in programming is that no function or subroutine should be larger than a single screen in an editor because it is too difficult to understand large subroutines or functions. Break the subroutine up into smaller subroutines or functions that do exactly one thing. Localize the variables to the subroutines they are needed in. There should probably be one subroutine for the Inbox and one subroutine for the Sent mails.
Another reason to break up the function is that it is very difficult to identify where any bottlenecks are (things that slow down the code) in a large subroutine.
There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:
that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function. | {
"domain": "codereview.stackexchange",
"id": 43139,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel, outlook",
"url": null
} |
performance, vba, excel, outlook
The art or science of programming is to break problems into smaller and smaller pieces until each piece is very simple to code. | {
"domain": "codereview.stackexchange",
"id": 43139,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel, outlook",
"url": null
} |
python, numpy, physics
Title: Solving a 3D heat diffusion PDE
Question: I am trying to solve a heat diffusion type PDE using a finite difference method.
I would like to preface that I have seriously simplified the code. Just so that anyone who tries to help me, doesn't get caught up in the coefficients of the PDE.
I am trying to move away from using the 4x nested for loops, and instead would like to use a slicing or shifting approach, where I simultaneously calculate as many points in the 3D grid ijk at each value for n with as few possible steps. The execution time of the stacked for loops can get quite long if I, J, K, N are set in the 100's or 1000's.
Also, I'm only using 1 timestep for illustration purpose. If I were to use more than 1, then I would have to set the new boundary values, which isn't important for the purpose of optimising the code.
The code that I need help optimising is as follows:
import numpy as np
T = 1
I = 10
J = 10
K = 10
N = 1
T0 = 0
dt = (T - T0) / N
f_u = np.zeros((I + 1, J + 1, K + 1, N + 1)) | {
"domain": "codereview.stackexchange",
"id": 43140,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, physics",
"url": null
} |
python, numpy, physics
T0 = 0
dt = (T - T0) / N
f_u = np.zeros((I + 1, J + 1, K + 1, N + 1))
f_u[:, :, :, N] = 1
for n in range(N, 0, -1):
for i in range(1, I):
for j in range(1, J):
for k in range(1, K):
f_u[i, j, k, n - 1] = f_u[i, j, k, n] + dt * ((i + 1) * f_u[i + 1, j + 1, k, n]\
+ 0.5 * f_u[i + 1, j, k, n]\
+ (i + 1) * 0.5 * f_u[i + 1, j - 1, k, n]\
+ f_u[i, j, k, n]\
+ (k + 1) * f_u[i, j, k + 1, n]\
+ (k - 1) * f_u[i, j, k - 1, n]\
+ (i - 1) * f_u[i - 1, j + 1, k, n]\
+ 0.5 * f_u[i - 1, j, k, n]\
+ (i - 1) * 0.5 * f_u[i - 1, j - 1, k, n]\
+ f_u[i, j + 1, k, n]\
+ f_u[i, j - 1, k, n])
print(f_u[:,:,:,0].sum())
>> 21870.0
Answer: For your kind of data it's very important that you use dtype=int.
All of your dimensions that aren't n should be de-looped. Any time that you write an index, it turns into a slice:
i - 1 -> :-2
i -> 1:-1
i + 1 -> 2:
Same for j and k.
PEP8 needs to be sacrificed for clarity. Attempt to align your terms.
Avoid using \; instead enclose your expression in parens ().
Expand your regression test from a single sum(), and add asserts.
Suggested
import numpy as np
T = 1
T0 = 0
N = 1
dt = (T - T0) / N | {
"domain": "codereview.stackexchange",
"id": 43140,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, physics",
"url": null
} |
python, numpy, physics
T = 1
T0 = 0
N = 1
dt = (T - T0) / N
I = 10
J = 10
K = 10
i = np.arange(1, I)
j = np.arange(1, J)
k = np.arange(1, K)
f_u = np.zeros((I + 1, J + 1, K + 1, N + 1), dtype=int)
f_u[:, :, :, N] = 1
for n in range(N, 0, -1):
f_u[1:-1, 1:-1, 1:-1, n - 1] = (
f_u[1:-1, 1:-1, 1:-1, n]
+ dt * (
+ (i + 1) * f_u[2: , 1:-1, 1:-1, n]
+ 0.5 * f_u[2: , 1:-1, 1:-1, n]
+ (i + 1) * 0.5 * f_u[2: , :-2, 1:-1, n]
+ f_u[1:-1, 1:-1, 1:-1, n]
+ (k + 1) * f_u[1:-1, 1:-1, 2: , n]
+ (k - 1) * f_u[1:-1, 1:-1, :-2, n]
+ (i - 1) * f_u[ :-2, 1:-1, 1:-1, n]
+ 0.5 * f_u[ :-2, 1:-1, 1:-1, n]
+ (i - 1) * 0.5 * f_u[ :-2, :-2, 1:-1, n]
+ f_u[1:-1, 2: , 1:-1, n]
+ f_u[1:-1, :-2, 1:-1, n]
)
)
assert f_u.shape == (11, 11, 11, 2)
assert f_u.sum() == 23201
assert np.isclose(f_u.mean(), 8.715627347858753, rtol=0, atol=1e-12)
assert f_u.min() == 0
assert f_u.max() == 50 | {
"domain": "codereview.stackexchange",
"id": 43140,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, physics",
"url": null
} |
c++, algorithm, c++11, timer
Title: Leaky Bucket Algorithm with no Queue
Question: Basic implementation of a leaky bucket, the idea is you call it by saying I will allow e.g. 5 login attempts per 60 seconds.
//Leaky Bucket algorithm with chrono
class RateController {
int n;
std::chrono::steady_clock::duration interval;
int cnt;
std::chrono::time_point<std::chrono::steady_clock> last;
public:
RateController(int limit, int seconds) :
n(limit), interval(std::chrono::seconds(seconds/limit)), cnt(0) {}
bool ok() {
auto t = std::chrono::steady_clock::now();
if (cnt) {
cnt -= (t - last) / interval;
if (cnt < 0) cnt = 0;
if (cnt >= n) return false;
}
++cnt;
last = t;
return true;
}
};
Answer: Create a type alias for the clock you want to use
Things become more maintainable and easier to write if you create a type alias for the clock, like so:
using clock = std::chrono::steady_clock;
That way, you can write:
clock::duration interval;
clock::time_point last;
...
auto t = clock::now();
Use an unsigned type for the counters
I recommend using unsigned types for the counters, as they should never be negative. In order to leak without the counter going negative, write:
cnt -= std::min(cnt, (t - last) / interval); | {
"domain": "codereview.stackexchange",
"id": 43141,
"lm_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++, algorithm, c++11, timer",
"url": null
} |
c++, algorithm, c++11, timer
Let the caller pass the interval as a std::chrono::duration
Instead of forcing the caller to pass the duration as an integer describing seconds, and then having to convert this to a std::chrono::duration type yourself, consider changing the parameter seconds of the constructor to be of type clock::duration. The caller can then pass in any std::chrono::duration it likes.
Be aware of integer division
The expression seconds / limit will evaluate to 0 if limit > seconds. This is problematic as it will cause a division by zero later in ok(). I would avoid the division entirely, and have interval mean the interval in which at most limit calls to ok() will return true. Then to leak you just write:
cnt -= std::min(cnt, (t - last) * n / interval);
Naming things
Some things are abbreviated unnecessarily. Instead of cnt, write count. Instead of n, write max_count or limit like you do in the constructor. Instead of t, write now or current_time. It's just a few more characters to type, but it will make the code much clearer to anyone reading it, including yourself in a few months when you've forgotten the details of your implementation. | {
"domain": "codereview.stackexchange",
"id": 43141,
"lm_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++, algorithm, c++11, timer",
"url": null
} |
javascript, angular-2+, rxjs
Title: If condition in combineLatest observables
Question: I have many observables so I use combineLatest in RxJS. After get all results I need to check one of value by using if condition. If the condition meets then call another HTTP service so I use another observable. Finally I render the data into UI.
const a$ = this.http.get('url_a'); // observable
const b$ = this.http.get('url_b'); // observable
const c$ = this.http.get('url_c'); // observable
const d$ = this.http.get('url_d'); // observable
const e$ = this.http.get('url_e'); // observable
const f$ = this.http.get('url_f'); // observable
combineLatest([a$, b$, c$, d$, e$, f$])
.pipe(
take(1),
mergeMap(([ra, rb, rc, rd, re, rf]) => {
this.resp1 = ra;
this.resp2 = rb;
this.resp3 = rc;
this.resp4 = rd;
this.resp5 = re;
this.resp6 = rf;
// below is the condition, if it meets I call another http
if (this.resp3.id < a_constant) {
this.resp3.step = constant;
return this.http.put('url_another'); // observable
}
// then I use a trick below
return of(1); // trick observable
}))
.subscribe(() => {
this.step = this.resp3.step - 1;
// other rendering ui work by returning results such as resp1, resp2, etc.
});
The issue is that if if (this.resp3.id < a_constant) I want to update something. So the this.resp3.id maybe changes. I want this value finally.
I use return of(1) the trick. Although it works but it is ugly.
EDIT:
Per feedback, I added additional info.
The issue is I want to listen an observable. Usually it is this.http.put('url_another') so I can subscribe it. But there is a if condition so this observable is not always created. But I have to subscribe something. Then I use an unrelated observable of(1) to listen.
of(1) is a fake observable. | {
"domain": "codereview.stackexchange",
"id": 43142,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, angular-2+, rxjs",
"url": null
} |
javascript, angular-2+, rxjs
Answer: First, a few questions:
What is the return of(1) trick doing? The combineLatest isn't being stored in a variable and the subscribe takes no parameter, so what is the of(1) doing?
What is the purpose of combining these observables? You don't seem to be doing anything with the result of the combination. Why not just work with the a$, b$, etc variables instead of copying the result to this.respx variables? Then you could use an async pipe in the template to display each of the a$, b$ data.
One a minor thing in the code, you don't need a take(1) because each of your Observables only emit once and complete. So the combineLatest will only emit one time.
Also, you could do something like this:
const c$ = this.http.get('url_c').pipe(
map(data => {
if (this.resp3.id < a_constant) {
this.resp3.step = constant;
return this.http.put('url_another');
}
}
)
Does that help? | {
"domain": "codereview.stackexchange",
"id": 43142,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, angular-2+, rxjs",
"url": null
} |
java, algorithm, graph, genetic-algorithm, traveling-salesman
Title: Genetic TSP in Java with graph expansion
Question: This post presents my take on TSP (travelling salesman problem). The idea is to:
Take an input node i,
Compute the entire graph G reachable from i
Compute the all-pairs shortest paths for G
Shuffle the current tour specified number of times and choose the shortest one
GeneticTSPSolver.java:
package com.github.coderodde.tsp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* This class implements the genetic TSP solver.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Mar 29, 2022)
* @since 1.6 (Mar 29, 2022)
*/
public final class GeneticTSPSolver { | {
"domain": "codereview.stackexchange",
"id": 43143,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman",
"url": null
} |
java, algorithm, graph, genetic-algorithm, traveling-salesman
public static List<Node> findTSPSolution(Node seedNode, int iterations) {
Random random = new Random();
List<Node> tspGraph = GraphExpander.expandGraph(seedNode);
AllPairsShortestPathData allPairsData =
AllPairsShortestPathSolver.solve(tspGraph);
List<Node> bestTour = new ArrayList<>();
double bestTourCost = Double.POSITIVE_INFINITY;
for (int i = 0; i < iterations; ++i) {
Collections.shuffle(tspGraph, random);
double currentTourCost = computeTourCost(tspGraph, allPairsData);
if (bestTourCost > currentTourCost) {
bestTourCost = currentTourCost;
bestTour.clear();
bestTour.addAll(tspGraph);
}
}
return bestTour;
}
private static double
computeTourCost(List<Node> tour, AllPairsShortestPathData data) {
double tourCost = 0.0;
for (int i = 0; i < tour.size(); ++i) {
int index1 = i;
int index2 = (i + 1) % tour.size();
Node node1 = tour.get(index1);
Node node2 = tour.get(index2);
tourCost += data.getEdgeCost(node1, node2);
}
return tourCost;
}
}
GraphExpander.java:
package com.github.coderodde.tsp;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* This class provides the method for computing graphs reachable from a seed
* node.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Mar 29, 2022)
* @since 1.6 (Mar 29, 2022)
*/
public final class GraphExpander { | {
"domain": "codereview.stackexchange",
"id": 43143,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman",
"url": null
} |
java, algorithm, graph, genetic-algorithm, traveling-salesman
public static List<Node> expandGraph(Node seedNode) {
List<Node> graph = new ArrayList<>();
Deque<Node> queue = new ArrayDeque<>();
Set<Node> visitedSet = new HashSet<>();
queue.addLast(seedNode);
visitedSet.add(seedNode);
while (!queue.isEmpty()) {
Node currentNode = queue.removeFirst();
visitedSet.add(currentNode);
graph.add(currentNode);
for (Node childNode : currentNode.getNeighbors()) {
if (!visitedSet.contains(childNode)) {
visitedSet.add(childNode);
queue.addLast(childNode);
}
}
}
return graph;
}
}
AllPairsShortestPathData.java:
package com.github.coderodde.tsp;
import java.util.HashMap;
import java.util.Map;
public final class AllPairsShortestPathData {
private Map<Node, Map<Node, Double>> matrix = new HashMap<>();
public AllPairsShortestPathData(Map<Node, Map<Node, Double>> matrix) {
this.matrix = matrix;
}
public double getEdgeCost(Node tail, Node head) {
return matrix.get(tail).get(head);
}
}
AllPairsShortestPathSolver.java:
package com.github.coderodde.tsp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class provides the method for computing the all-pairs shortest paths via
* Floyd-Warshall algorithm.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Mar 29, 2022)
* @since 1.6 (Mar 29, 2022)
*/
public final class AllPairsShortestPathSolver { | {
"domain": "codereview.stackexchange",
"id": 43143,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman",
"url": null
} |
java, algorithm, graph, genetic-algorithm, traveling-salesman
public static AllPairsShortestPathData solve(List<Node> graph) {
Map<Node, Map<Node, Double>> data = new HashMap<>(graph.size());
for (Node node : graph) {
Map<Node, Double> row = new HashMap<>();
for (Node node2 : graph) {
row.put(node2, Double.POSITIVE_INFINITY);
}
data.put(node, row);
}
for (Node tailNode : graph) {
for (Node headNode : tailNode.getNeighbors()) {
data.get(tailNode)
.put(headNode, tailNode.getWeightTo(headNode));
data.get(headNode)
.put(tailNode, tailNode.getWeightTo(headNode));
}
}
for (Node node : graph) {
data.get(node).put(node, 0.0);
}
for (Node node1 : graph) {
for (Node node2 : graph) {
for (Node node3 : graph) {
double tentativeCost = data.get(node2).get(node1) +
data.get(node1).get(node3);
if (data.get(node2).get(node3) > tentativeCost) {
data.get(node2).put(node3, tentativeCost);
node2.addNeighbor(node3, tentativeCost);
}
}
}
}
return new AllPairsShortestPathData(data);
}
}
Node.java:
package com.github.coderodde.tsp;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* This class defines the graph node type for the traveling salesman problem.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Mar 29, 2022)
* @since 1.6 (Mar 29, 2022)
*/
public final class Node { | {
"domain": "codereview.stackexchange",
"id": 43143,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman",
"url": null
} |
java, algorithm, graph, genetic-algorithm, traveling-salesman
private final String name;
private final Map<Node, Double> neighborMap = new HashMap<>();
public Node(String name) {
this.name = Objects.requireNonNull(name, "The node name is null.");
}
public void addNeighbor(Node node, double weight) {
neighborMap.put(node, weight);
node.neighborMap.put(this, weight);
}
public double getWeightTo(Node node) {
return neighborMap.get(node);
}
public Collection<Node> getNeighbors() {
return neighborMap.keySet();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Node)) {
return false;
}
Node other = (Node) o;
return name.equals(other.name);
}
@Override
public int hashCode() {
int hash = 5;
hash = 59 * hash + Objects.hashCode(this.name);
return hash;
}
@Override
public String toString() {
return name;
}
}
Demo.java:
package com.github.coderodde.tsp;
import java.util.List;
public final class Demo { | {
"domain": "codereview.stackexchange",
"id": 43143,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman",
"url": null
} |
java, algorithm, graph, genetic-algorithm, traveling-salesman
Demo.java:
package com.github.coderodde.tsp;
import java.util.List;
public final class Demo {
public static void main(String[] args) {
Node n1 = new Node("1");
Node n2 = new Node("2");
Node n3 = new Node("3");
Node n4 = new Node("4");
Node n5 = new Node("5");
Node n6 = new Node("6");
n1.addNeighbor(n3, 1.0);
n2.addNeighbor(n3, 2.0);
n3.addNeighbor(n4, 3.0);
n3.addNeighbor(n5, 4.0);
n6.addNeighbor(n4, 1.0);
n6.addNeighbor(n5, 5.0);
List<Node> tour = GeneticTSPSolver.findTSPSolution(n3, 3);
System.out.println("Tour:");
for (Node node : tour) {
System.out.println(node);
}
System.out.println("\nCost: " + computeCost(tour));
}
private static double computeCost(List<Node> tour) {
double cost = 0.0;
for (int i = 0; i < tour.size(); ++i) {
int index1 = i;
int index2 = (i + 1) % tour.size();
Node node1 = tour.get(index1);
Node node2 = tour.get(index2);
cost += node1.getWeightTo(node2);
}
return cost;
}
}
```
**Critique request**
As always, please tell me anything that comes to mind.
Answer: Naming
You chose some confusing names.
tspGraph is not a graph, but a path/tour through the graph, and the "tsp" prefix is not helpful, as in your program everything is about the Travelling Salesman Problem. I'd call the variable candidateTour.
List<Node> graph = new ArrayList<>(); in GraphExpander. Again, this isn't a graph. This time it's just a collection of nodes, the ones reachable from a given start node. So, I'd call it reachableNodes. | {
"domain": "codereview.stackexchange",
"id": 43143,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman",
"url": null
} |
java, algorithm, graph, genetic-algorithm, traveling-salesman
AllPairsShortestPathData.getEdgeCost() If I understand correctly, this can be a multi-edge accumulated cost, if the two nodes aren't adjacent. Your class name reflects that it isn't about edges, but paths. But the access method is misleading. So, the name should be getShortestPathCost(Node start, Node end).
Javadoc
You placed a few Javadoc comments, but not enough to understand your code, and the naming isn't self-explanatory. My understanding of e.g. the AllPairsShortestPathData class would give Javadoc like:
/**
* The "matrix" of shortest-path (multi-step) costs when travelling
* from one node to another.
*/
public final class AllPairsShortestPathData {
// ...
}
And in
/**
* This class provides the method for computing graphs reachable from a seed
* node.
* ...
*/
public final class GraphExpander {
// ...
}
it should be "nodes" instead of "graphs".
Unit Tests
There are no unit tests.
Although the exact outcome of a random-based algorithm is unpredictable, you should create tests whether the resulting path is indeed a valid solution (visits each city, only connects neighbor cities, and so on).
For the lower-level classes, where no randomness is involved, test cases with specific result expectations can easily be created.
Algorithm
I wouldn't call your algorithm "genetic" (see Wikipedia). It's pure Monte-Carlo. A genetic algorithm incrementally modifies and/or combines good candidates to reach even better ones. The key concepts of
a population,
crossover and
mutation | {
"domain": "codereview.stackexchange",
"id": 43143,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman",
"url": null
} |
java, algorithm, graph, genetic-algorithm, traveling-salesman
a population,
crossover and
mutation
all aren't present in your program.
You use Collections.shuffle() to create the next candidate from a given one, which gives a completely random result, independent of the previous candidate. That's a very "poor man's" version of mutation, so much that it doesn't deserve that label.
Your algorithm just calculates N random tours and returns the shortest one.
Finally, I'm not convinced that your program gives valid solutions for the classic Travelling Salesman Problem, where each city has to be visited exactly once. Your usage of the AllPairsShortestPathData class seems to imply that you also allow connections with intermediate city visits, but I might be wrong here.
You should state clearly which variant of the TSP you solve. | {
"domain": "codereview.stackexchange",
"id": 43143,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman",
"url": null
} |
javascript, react.js, redux, state
Title: Doubling of state to speed up UI performance in React with Redux
Question: I have a settings section to my UI which keeps track of a myriad of user settings. The settings are requested from an API when the app loads, and then used in the section to populate what the user's current settings are. I am using redux for this. For example:
const Settings () => {
const dispatch = useDispatch();
const userSettings = useSelector(state => state.user.settings);
const { getNotifications } = userSettings;
return (
<form>
<label>Receive Notifications?</label>
<input
type="checkbox"
checked={getNotifications}
onClick={() => {
dispatch(
putNewUserSettings({ getNotifications: !getNotifications })
)
}}
/>
</form>
)
}
The putNewUserSettings function registers a new action in redux, which makes an api call to update the settings from the back end. When that api call returns, redux captures that, and updates state.user.settings, and the checkbox changes from being checked to unchecked, or vice versa. Great.
This, however, causes a delay in the UI. The user clicks the checkbox, but it doesn't actually change until the api call returns and updates the redux store. This makes for a sluggish-feeling UI. Not good!
My solution to this is to actually maintain the state of the checkbox (or whatever other form field) in local state, and when that changes, create an effect to make the api call:
const Settings () => {
const dispatch = useDispatch();
const userSettings = useSelector(state => state.user.settings);
const { getNotifications } = userSettings;
// Doubling of state, use redux value as initial value
const [getNotificationsLocal, setGetNotificationsLocal] = useState(getNotifications); | {
"domain": "codereview.stackexchange",
"id": 43144,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, react.js, redux, state",
"url": null
} |
javascript, react.js, redux, state
/**
* What local state changes, make call to api so that db is updated with
* new user settings
*/
useEffect(() => {
dispatch(
putNewUserSettings({ getNotifications: getNotificationsLocal })
)
}, [getNotificationsLocal])
return (
<form>
<label>Receive Notifications?</label>
<input
type="checkbox"
checked={getNotificationsLocal}
onClick={() => { setGetNotificationsLocal(!getNotificationsLocal) }}
/>
</form>
)
}
So in this second case, because the checkbox is reading from local state, when the user taps the checkbox, it immediately updates in the UI, and it has that performant feel. As a secondary effect, that change triggers a call to the API to 'officially' update the setting in a more global sense. (I do make use of a handy hook called useDidMountEffect to avoid running the API call on mount, as it would be unecessary to call the API to set the settings value to what it already is.)
Is this bad practice? I find myself doing this all over in an app because the api is a touch slow and causing for slow UI. Is this some kind of anti-pattern that will cause more problems I'm not foreseeing?
Answer: What you've done makes sense to me; I see this approach all the time for autosaving. I don't yet know of a library that eases this kind of manual pain.
However, here are some caveats with your current approach: | {
"domain": "codereview.stackexchange",
"id": 43144,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, react.js, redux, state",
"url": null
} |
javascript, react.js, redux, state
The user could toggle the checkbox in quick succession, perhaps from an accidental double click. This opens up a potential race condition with the API calls: the sending order may not equal the fulfillment order (from the BE). Due to this, the final state in Redux may become out of sync with your local state. And the user may feel distrust through this bad experience. My normal solution to this is to track the loading state of the API request inflight, and disable the checkbox until it's done. This prevents the opportunity of multiple inflight requests, and ensures that the UI stays in sync.
What happens if the save request fails? You've optimistically updated your local state. But now there's a mismatch between the local and BE state. My normal solution for this, inconjunction with point 1, would be to show an error message nearby and revert the local state to what it was before.
Re. 1, and this is more subjective: Perhaps introduce a bit of loading UI near the checkbox, like a spinner, to indicate the save is in progress. As a user, that'll clearly indicate an autosave is happening, which is an immediate response to their interaction, meeting your perceived speed requirements, but also provides the confidence of the save being performed. | {
"domain": "codereview.stackexchange",
"id": 43144,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, react.js, redux, state",
"url": null
} |
javascript, performance, array, random, ecmascript-6
Title: Randomly set styles with JavaScript
Question: I have created a function which randomly sets styles using CSS selectors. Right now it returns a random item from an array. The program also works with shorthand properties (such as font).
Could my code be improved and run more efficiently?
const setRandomStyles = (obj) => {
console.time("Executed in ");
Object.entries(obj).forEach(([target, styles]) =>
document
.querySelectorAll(target)
.forEach((element) =>
Object.assign(
element.style,
Object.fromEntries(
Object.entries(styles).map(([key, values]) => [
key,
Array.isArray(values[0])
? values.map((e) => e[~~(Math.random() * e.length)]).join(" ")
: values[~~(Math.random() * values.length)],
])
)
)
)
);
console.timeEnd("Executed in ");
};
setRandomStyles({
"*": {
color: ["red", "orange", "yellow", "green", "blue", "violet"],
backgroundColor: ["yellow", "green", "blue", "violet"],
font: [["italic", "bold"], [...Array(40).keys()].map((i) => i + "px"), ["cursive", "sans-serif", "consolas"]],
},
});
You can also propose better code to set random styles in js.
Thanks!
Answer: Code Style
This code looks very identical to the code in your recent question Download entire localStorage as file. Like I mentioned in my answer there it does look a bit "pyramid shaped". I see this basic pattern
function
Object.entries().forEach
Object.assign
Object.fromEntries
Object.entries().map
map || item
That is 6+ levels of indentation! It is a good thing you are only using two spaces instead of four (or even worse- tabs) - otherwise the line lengths would be quite a bit longer.
Still it doesn't seem totally unreadable.
Could my code be improved and run more efficiently? | {
"domain": "codereview.stackexchange",
"id": 43145,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, performance, array, random, ecmascript-6",
"url": null
} |
javascript, performance, array, random, ecmascript-6
Could my code be improved and run more efficiently?
Efficiency
One could perhaps improve efficiency by switching to basic for loops. While it strays from the functional programming techniques, the example snippet below uses for...of loops, which still uses an iterator so it isn't as fast as a regular for loop but that will likely not be noticeable for small DOM trees. It also eliminates the need to call Object.assign() and Object.fromEntries() as it assigns to the style directly in each iteration. While it contains the same complexity (i.e. two loops nested within a loop) the indentation levels are fewer and there are fewer functions executed per iteration.
const setRandomStyles = obj => {
console.time("Executed in ");
for (const [target, styles] of Object.entries(obj)) {
for (const element of document.querySelectorAll(target)) {
for (const [key, values] of Object.entries(styles)) {
element.style[key] = Array.isArray(values[0])
? values.map((e) => e[~~(Math.random() * e.length)]).join(" ")
: values[~~(Math.random() * values.length)];
}
}
}
console.timeEnd("Executed in ");
};
setRandomStyles({
"*": {
color: ["red", "orange", "yellow", "green", "blue", "violet"],
backgroundColor: ["yellow", "green", "blue", "violet"],
font: [["italic", "bold"], [...Array(40).keys()].map((i) => i + "px"), ["cursive", "sans-serif", "consolas"]],
},
});
Arrow function syntax simplification
While it may not be a big difference, "Multiple params require parentheses"1 but if an arrow function has just one parameter then the parentheses can be omitted (as was done in the snippet above).
For Example:
const setRandomStyles = (obj) => {
can be simplified to:
const setRandomStyles = obj => {
And
(e) => e[~~(Math.random() * e.length)]
can be simplified to:
e => e[~~(Math.random() * e.length)] | {
"domain": "codereview.stackexchange",
"id": 43145,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, performance, array, random, ecmascript-6",
"url": null
} |
javascript, performance, array, random, ecmascript-6
(e) => e[~~(Math.random() * e.length)]
can be simplified to:
e => e[~~(Math.random() * e.length)]
Simplify selectors
While style is a global attribute it may just be for demonstration purposes, the selector * applies to all elements within the HTML page - including tags that likely don't need to have style attributes - e.g. <html>, <head>, <link>, <meta>, etc..
For example, I ran the code on a sample HTML page on jsbin.com and it showed this HTML (simplified and formatted for brevity):
<html style="color: red; background-color: violet; font: bold 6px sans-serif;">
<head style="color: green; background-color: blue; font: italic 3px sans-serif;">
<script style="color: orange; background-color: violet; font: italic 21px consolas;"> /* script source */</script>
<meta charset="utf-8" style="color: violet; background-color: violet; font: bold 29px sans-serif;">
<meta name="viewport" content="width=device-width" style="color: violet; background-color: violet; font: bold 26px consolas;">
<title style="color: orange; background-color: yellow; font: bold 6px cursive;">JS Bin</title>
<style id="jsbin-css" style="color: violet; background-color: blue; font: bold 20px cursive;">
</style>
</head>
<body style="color: blue; background-color: yellow; font: italic 14px consolas;">
sample text
<div style="color: violet; background-color: yellow; font: bold 22px sans-serif;">Hey there dude</div>
<script style="color: green; background-color: violet; font: italic 8px cursive;">/* script source */ </script>
</body>
</html> | {
"domain": "codereview.stackexchange",
"id": 43145,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, performance, array, random, ecmascript-6",
"url": null
} |
c++, floating-point
Title: C++ compare floats
Question: I have designed a class to perform float compare. I used Knuth's strong compare to do it. Float compare is really really tricky, I'm sure there's something wrong :) Any comments?
#include <limits>
#include <cmath>
#include <assert.h>
class FloatUtils {
private:
FloatUtils();
template<typename T>
static T safeDivision( const T& f1, const T& f2 );
public:
template<typename T>
static bool almostEqual( const T& a, const T& b, const T& relEpsilon = std::numeric_limits<T>::epsilon(),const T& absEpsilon = std::numeric_limits<T>::epsilon()) noexcept;
template<typename T>
static bool almostZero( const T& a, const T& absEpsilon = std::numeric_limits<T>::epsilon() ) noexcept;
};
template<typename T>
inline T FloatUtils::safeDivision( const T& f1, const T& f2 ) {
// Avoid overflow.
if ( (f2 < static_cast<T>(1)) && (f1 > f2 * std::numeric_limits<T>::max()) )
return std::numeric_limits<T>::max();
// Avoid underflow.
if ( (f1 == static_cast<T>(0)) || ((f2 > static_cast<T>(1)) && (f1 < f2 * std::numeric_limits<T>::min())) )
return static_cast<T>(0);
return f1 / f2;
}
template<typename T>
inline bool FloatUtils::almostEqual( const T& a, const T& b, const T& relEpsilon, const T& absEpsilon ) noexcept {
static_assert(!std::is_integral<T>::value, "T can be only no integral type");
static_assert(std::numeric_limits<T>::is_iec559, "IEEE754 supported only");
if ( !std::isfinite(a) || !std::isfinite(b) ) {
return false;
}
/**
* avoid division by zero checking exactly 0 value
*/
if ( a == 0 ) {
return almostZero(b, absEpsilon);
}
/**
* avoid division by zero checking exactly 0 value
*/
if ( b == 0 ) {
return almostZero(a, absEpsilon);
} | {
"domain": "codereview.stackexchange",
"id": 43146,
"lm_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++, floating-point",
"url": null
} |
c++, floating-point
/**
* We use Knuth's formula modified, i.e. the right side of inequations may cause underflow,
* to prevent this, the formula scales the difference rather than epsilon.
* We don't nanage 0 or Inf here so we need to add the special cases above.
*/
T diff = std::abs(a - b);
T d1 = safeDivision<T>(diff, std::abs(a));
T d2 = safeDivision<T>(diff, std::abs(b));
return d1 <= relEpsilon && d2 <= relEpsilon;
}
template<typename T>
inline bool FloatUtils::almostZero( const T& a, const T& absEpsilon ) noexcept {
if ( std::abs(a) <= absEpsilon )
return true;
return false;
}
Test cases:
int main() {
assert(FloatUtils::almostEqual(3.145646, 3.145646) == true);
assert(FloatUtils::almostEqual(145697.78965, 145553.09186, 0.001) == true);
assert(FloatUtils::almostEqual(145697.78965, 145552.09186, 0.001) == false);
assert(FloatUtils::almostEqual(0.00001, 0.0, 0.1, 0.001) == true);
assert(FloatUtils::almostEqual(1.0, 1.0, 0.0) == true);
assert(FloatUtils::almostEqual(0.0, 1E-20, 1E-5) == true);
assert(FloatUtils::almostEqual(0.0, 1E-30, 1E-5) == true);
assert(FloatUtils::almostEqual(0.0, -1E-10, 0.1, 1E-9) == true);
assert(FloatUtils::almostEqual(0.0, -1E-10, 0.1, 1E-11) == false);
assert(FloatUtils::almostEqual(0.123456, 0.123457, 1E-6) == false);
assert(FloatUtils::almostEqual(0.123456, 0.123457, 1E-3) == true);
assert(FloatUtils::almostEqual(0.123456, -0.123457, 1E-3) == false);
assert(FloatUtils::almostEqual(1.23456E28, 1.23457E28, 1E-3) == true);
assert(FloatUtils::almostEqual(1.23456E-10, 1.23457E-10, 1E-3) == true);
assert(FloatUtils::almostEqual(1.111E-10, 1.112E-10, 0.000899) == false);
assert(FloatUtils::almostEqual(1.111E-10, 1.112E-10, 0.1) == true);
assert(FloatUtils::almostEqual(1.0, 1.0001, 1.1E-2) == true);
assert(FloatUtils::almostEqual(1.0002, 1.0001, 1.1E-2) == true);
assert(FloatUtils::almostEqual(1.0, 1.0002, 1.1E-4) == false);
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 43146,
"lm_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++, floating-point",
"url": null
} |
c++, floating-point
Answer: First, note that anyone trying to "fuzzy compare" floating-point numbers for "approximate equality" is already in a state of sin. In real code, either you care about actual (bit-for-bit) equality, or else you have a specific error-bar in mind which you've carried through the whole calculation. There's pretty much no situation where the programmer ever wants "x is approximately equal to y, based on some fudge-factor epsilons I don't even care enough to specify." That's just not a thing people want to do.
class FloatUtils {
private:
FloatUtils();
You're using a struct instead of a namespace because you don't like namespaces, right? But then you're also giving it a private, non-defined constructor so that the user can't accidentally create an instance of the struct type itself? First of all, this is massive overkill and you should just write either
namespace FloatUtils {
or
struct FloatUtils {
But, if you really must prevent people from constructing instances of your type, the correct way to do that is not with a private constructor but instead with a deleted constructor:
struct FloatUtils {
FloatUtils() = delete;
I don't see why you need safeDivision to be private. Couldn't it profitably be made public?
template<typename T>
static bool almostEqual( const T& a, const T& b, const T& relEpsilon = std::numeric_limits<T>::epsilon(),const T& absEpsilon = std::numeric_limits<T>::epsilon()) noexcept;
This line is comically long, and also default function arguments are the devil. It would be strictly better to write one declaration per signature to which you intend the user to have access:
template<class T>
static bool almostEqual(const T& a, const T& b) {
auto eps = std::numeric_limits<T>::epsilon();
return almostEqual(a, b, eps, eps);
}
template<class T>
static bool almostEqual(const T& a, const T& b, const T& relEps) {
return almostEqual(a, b, relEps, std::numeric_limits<T>::epsilon());
} | {
"domain": "codereview.stackexchange",
"id": 43146,
"lm_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++, floating-point",
"url": null
} |
c++, floating-point
template<class T>
static bool almostEqual(const T& a, const T& b, const T& relEps, const T& absEps);
Marking these functions noexcept doesn't serve any purpose; nobody is going to be making compile-time decisions based on whether noexcept(almostEqual(a, b)).
It is mildly strange that you consider almostEqual(INFINITY, INFINITY) == false. They're bitwise the same value; shouldn't they be considered equal?
static_assert(!std::is_integral<T>::value, "T can be only no integral type");
I suspect you mean
static_assert(std::is_floating_point_v<T>, "T must be a floating-point type");
Why do you need safeDivision to protect against overflow? It might well be that abs(a - b) is INFINITY, and so diff / abs(a) is also INFINITY... but that's definitely going to be greater than absEpsilon, so who cares?
Vice versa, I suggest that if a > 0 && b < 0, the numbers are definitely not approximately equal... well, not for many applications, anyway. Depends if you're using them as operands to + or as operands to *, I guess. Again, anyone comparing floats for fuzzy equality is already in a state of sin.
T diff = std::abs(a - b);
T d1 = safeDivision<T>(diff, std::abs(a));
T d2 = safeDivision<T>(diff, std::abs(b));
return d1 <= relEpsilon && d2 <= relEpsilon;
It seems like you could save a division by doing
T diff = std::abs(a - b);
T denominator = std::min(std::abs(a), std::abs(b));
return safeDivision(diff, denominator) <= relEpsilon;
Notice that I've dropped the T from safeDivision. In general, you should call function templates as if they were ordinary functions, without any scary angle brackets. Let type deduction do its thing.
If you really want to force the programmer to specify the T argument to safeDivision, then you should make it non-deducible. In C++20 you can do this with type_identity_t:
template<class T>
static T safeDivision(const std::type_identity_t<T>& f1, const std::type_identity_t<T>& f2); | {
"domain": "codereview.stackexchange",
"id": 43146,
"lm_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++, floating-point",
"url": null
} |
c++, floating-point
safeDivision(1.0, 2.0); // error, can't deduce T
safeDivision<double>(1.0, 2.0); // OK
safeDivision<float>(1.0, 2.0); // also OK
By the way, since T must be a floating-point type, you're losing performance via unnecessary pass-by-reference. Prefer pass-by-value for trivial primitive types like float and long double:
template<class T>
static T safeDivision(T a, T b); | {
"domain": "codereview.stackexchange",
"id": 43146,
"lm_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++, floating-point",
"url": null
} |
c, strings
Title: C: Reverse individual words in a string
Question: I have been practicing C and I wanted to reverse each word in a string. I wrote this code and although it works, I am not happy with my solution. It requires twice the length of the original string to store the result and buffer respectively and there are too many if statements which makes the code hacky. I am wondering how can I do better?
#include <stdio.h>
#include <string.h>
int main()
{
char* str = "123 456 789";
int i, j = 0, k, l = 0;
int str_len = (int)strlen(str);
char buffer[str_len];
int buffer_size = 0;
char result[str_len + 1];
for (i = 0; i < str_len; i++)
{
char c = str[i];
if (c == ' ' || (i + 1) == str_len)
{
short is_end_of_string = 0;
if ((i + 1) == str_len)
{
buffer_size++;
buffer[l] = c;
is_end_of_string = 1;
}
for (k = 0; k < buffer_size / 2; k++)
{
char temp = buffer[k];
buffer[k] = buffer[buffer_size - k - 1];
buffer[buffer_size - k - 1] = temp;
}
for (k = 0; k < buffer_size; k++)
{
result[j++] = buffer[k];
}
if (!is_end_of_string)
{
result[j++] = c;
buffer_size = 0;
l = 0;
}
}
else
{
buffer_size++;
buffer[l++] = c;
}
}
result[j] = 0;
printf("%s\n", result);
return 0;
}
Try it online
Answer: Clarify "word"
OP's "word" seems to be characters separated by a space ' '. A more common definition would use any white-space (tabs, end-of-line, etc.) , not just ' ' as a separator.
Research isspace() in <ctype.h>.
Alternative
It requires twice the length of the original string | {
"domain": "codereview.stackexchange",
"id": 43147,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings",
"url": null
} |
c, strings
It requires twice the length of the original string
No need to find the string or word length anywhere. O(1) extra memory needed, unlike OP's O(length) for an in-place reversal.
Algorithm:
p = string start
forever
while is white-space: p++
if p[0] then
note beginning address
while p[0] and is non-white-space: p++
note one-past-end-of-word address
while one-past-end-of-word > beginning
swap (beginning[0], one-past-end-of-word[-1])
beginning++;
one-past-end-of-word--;
else we are done
For general use: String length may exceed INT_MAX
Use size_t to handle all possible string lengths. Cast not needed. Note that size_t is an unsigned type, so other parts of code made need changing too.
// int str_len = (int)strlen(str);
size_t str_len = strlen(str);
For boolean objects, use _Bool or bool
#include <stdbool.h>
// short is_end_of_string = 0;
bool is_end_of_string = false;
// is_end_of_string = 1;
is_end_of_string = true;
There are times to use maybe unsigned char for a boolean if we had a large array of booleans, yet this is not the case here.
Testing
Try more challenging strings too.
"123 456 789"
" 123 456 789"
"123 456 789 "
" 123 456 789 "
"123\t 456\n 789"
" "
""
"1 2 3\n"
Advanced
Access characters of a string via unsigned char * instead of char * for more proper use of is...() functions in <ctype.h> which can fail with negative values.
Pedantic: unsigned char * access also handles rare non-2's complement with signed char to properly distinguish between +0 and -0.
Print with sentinels
Easier to detect proper handling of leading/trailing white-space.
// printf("%s\n", result);
printf("<%s>\n", result); | {
"domain": "codereview.stackexchange",
"id": 43147,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings",
"url": null
} |
performance, algorithm, c, cryptography, hashcode
Title: Encryption and Decryption in C
Question: I have written a program in C, which encrypts and decrypts a c-styled string (const char *) and print the result to stdout. It requires key (const char *) and it's hash is calculated using Polynomial Rolling Hash.
My program makes sure that the hash of key must be in-between 0...128, using statement like size_t hash = get_hash(key) % 128;. My code works well if I provide a good key, but if the key is bad (plain[i] ± hash < 0), then it exits saying could not encrypt.
I have implemented all suggestion I got from my previous questions (not related this one).
Here's my code: TRY GOOD_KEY | TRY BAD_KEY
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
// gets hash of a string using Polynomial Rolling Hash
// https://en.wikipedia.org/wiki/Rolling_hash#Polynomial_rolling_hash
static size_t get_hash(const char *a)
{
if (a && *a != 0)
{
size_t p = 53;
size_t m = 1e9 + 9;
long long power_of_p = 1;
long long hash_val = 0;
for (size_t i = 0; a[i] != '\0'; i++)
{
hash_val = (hash_val + (a[i] - 97 + 1) * power_of_p) % m;
power_of_p = (power_of_p * p) % m;
}
return (hash_val % m + m) % m;
}
return (size_t)-1;
}
// encrypts `plain` using `key` and stores the output on heap allocated memory `out`
static bool encrypt(const char *plain, char **out, const char *key)
{
if (!plain || !out || !key)
return false;
size_t hash = get_hash(key) % 128;
size_t len = strlen(plain);
bool add = true;
*out = calloc(len + 1, sizeof(char));
if (!(*out))
return false; | {
"domain": "codereview.stackexchange",
"id": 43148,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, c, cryptography, hashcode",
"url": null
} |
performance, algorithm, c, cryptography, hashcode
*out = calloc(len + 1, sizeof(char));
if (!(*out))
return false;
for (size_t i = 0; plain[i] != '\0'; i++)
{
if (add == true && plain[i] + hash > '\0')
{
(*out)[i] = plain[i] + hash;
add = false;
}
else if (add == false && plain[i] - hash > '\0')// should not be less than zero
{
(*out)[i] = plain[i] - hash;
add = true;
}
else
{
free(*out);
return false;
}
}
return true;
}
// decrypts `enc` using `key` and stores the output on heap allocated memory `out`
static bool decrypt(const char *enc, char **out, const char *key)
{
if (!enc || !out || !key)
return false;
size_t hash = get_hash(key) % 128;
size_t len = strlen(enc);
bool add_inrv = true;
*out = calloc(len + 1, sizeof(char));
if (!(*out))
return false;
for (size_t i = 0; enc[i] != '\0'; i++)
{
if (add_inrv == true && enc[i] - hash > '\0')
{
(*out)[i] = enc[i] - hash;
add_inrv = false;
}
else if (add_inrv == false && enc[i] + hash > '\0')
{
(*out)[i] = enc[i] + hash;
add_inrv = true;
}
else
{
free(*out);
return false;
}
}
return true;
}
int main(int argc, char const **argv)
{
if (argc < 3)
{
perror("not enough input\nUsage: <MESSAGE> <KEY>");
return EXIT_FAILURE;
}
printf("Your text: `%s`\n", argv[1]);
char *enc, *after_dnc;
if(!encrypt(argv[1], &enc, argv[2])){
perror("could not encrypt");
return EXIT_FAILURE;
}
printf("Encrypted: `%s`\n", enc);
if(!decrypt(enc, &after_dnc, argv[2])){
perror("could not decrypt");
return EXIT_FAILURE;
}
printf("Decrypted: `%s`\n", after_dnc);
free(enc);
free(after_dnc);
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 43148,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, c, cryptography, hashcode",
"url": null
} |
performance, algorithm, c, cryptography, hashcode
free(enc);
free(after_dnc);
return EXIT_SUCCESS;
}
For output please use online compiler given above.
I'm using GCC v11.2.0 on Arch Linux x86_64 using C17 standard.
Answer: If in the following I keep mentioning problems I see, that doesn't mean there isn't good:
there are comments telling what each function is good for
(but for main())
even where most are static (Not to be used outside compilation unit - why?)
I find the code fairly readable:
naming and code formatting are inconspicious
(hm. _inrv?)
you strive for const correctness
In all functions but get_hash(), you don't nest if (<can proceed>)s, but use early out. (I'd rather use 'a' than 97)
encrypt() seems to be to alternately add and subtract hash:
use a signed type and keep adding & inverting instead of conditional execution.
encrypt() and decrypt() are basically the same function - let's give using a common implementation a try:
static bool
crypt(const char *message, char ** const pout, const char *const key, bool add);
// encrypts `plain` using `key` and stores the output on heap allocated memory `out`
bool encrypt(const char *plain, char **out, const char *key)
{
return crypt(plain, out, key, true);
}
// decrypts `enc` using `key` and stores the output on heap allocated memory `out`
bool decrypt(const char *enc, char **out, const char *key)
{
return crypt(enc, out, key, false);
}
#define MAGIC (128-1-1)
// crypts `message` using `key` and stores the output on heap allocated memory `pout`
static bool
crypt(const char *message, char ** const pout, const char *const key, bool add)
{
if (!message || !pout || !key)
return false;
size_t len = strlen(message);
char *out = *pout = malloc(len + 1);
if (NULL == out)
return false;
out[len] = '\0';
if (0 == len)
return true;
long hash = 1 + (get_hash(key) % (long)MAGIC);
if (!add)
hash = -hash; | {
"domain": "codereview.stackexchange",
"id": 43148,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, c, cryptography, hashcode",
"url": null
} |
performance, algorithm, c, cryptography, hashcode
for (int i = 0 ; i < len ; i++)
{
out[i] = message[i] + hash;
hash = -hash;
}
return true;
} | {
"domain": "codereview.stackexchange",
"id": 43148,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, c, cryptography, hashcode",
"url": null
} |
c++, recursion, c++20, boost, constrained-templates
Title: An Add/Minus Operator For Boost.MultiArray in C++
Question: This is a follow-up question for An element_wise_add Function For Boost.MultiArray in C++. The following code is the improved version based on G. Sliepen's answer. On the other hand, the built-in function .num_dimensions() I used here for the part of array dimension mismatch detection.
template<typename T>
concept is_multi_array = requires(T x)
{
x.num_dimensions();
x.shape();
boost::multi_array(x);
};
// Add operator
template<class T1, class T2> requires (is_multi_array<T1>&& is_multi_array<T2>)
auto operator+(const T1& input1, const T2& input2)
{
if (input1.num_dimensions() != input2.num_dimensions()) // Dimensions are different, unable to perform element-wise add operation
{
throw std::logic_error("Array dimensions are different");
}
if (*input1.shape() != *input2.shape()) // Shapes are different, unable to perform element-wise add operation
{
throw std::logic_error("Array shapes are different");
}
boost::multi_array output(input1); // [ToDo] drawback to be improved: avoiding copying whole input1 array into output, but with appropriate memory allocation
for (decltype(+input1.shape()[0]) i = 0; i < input1.shape()[0]; i++)
{
output[i] = input1[i] + input2[i];
}
return output;
} | {
"domain": "codereview.stackexchange",
"id": 43149,
"lm_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++, recursion, c++20, boost, constrained-templates",
"url": null
} |
c++, recursion, c++20, boost, constrained-templates
// Minus operator
template<class T1, class T2> requires (is_multi_array<T1>&& is_multi_array<T2>)
auto operator-(const T1& input1, const T2& input2)
{
if (input1.num_dimensions() != input2.num_dimensions()) // Dimensions are different, unable to perform element-wise add operation
{
throw std::logic_error("Array dimensions are different");
}
if (*input1.shape() != *input2.shape()) // Shapes are different, unable to perform element-wise add operation
{
throw std::logic_error("Array shapes are different");
}
boost::multi_array output(input1); // [ToDo] drawback to be improved: avoiding copying whole input1 array into output, but with appropriate memory allocation
for (decltype(+input1.shape()[0]) i = 0; i < input1.shape()[0]; i++)
{
output[i] = input1[i] - input2[i];
}
return output;
}
The test of the add/minus operator:
int main()
{
// Create a 3D array that is 3 x 4 x 2
typedef boost::multi_array<double, 3> array_type;
typedef array_type::index index;
array_type A(boost::extents[3][4][2]);
// Assign values to the elements
int values = 0;
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
A[i][j][k] = values++;
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
std::cout << A[i][j][k] << std::endl;
auto sum_result = A;
for (size_t i = 0; i < 3; i++)
{
sum_result = sum_result + A;
}
sum_result = sum_result - A;
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
std::cout << sum_result[i][j][k] << std::endl;
return 0;
}
All suggestions are welcome.
Which question it is a follow-up to?
An element_wise_add Function For Boost.MultiArray in C++ | {
"domain": "codereview.stackexchange",
"id": 43149,
"lm_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++, recursion, c++20, boost, constrained-templates",
"url": null
} |
c++, recursion, c++20, boost, constrained-templates
Which question it is a follow-up to?
An element_wise_add Function For Boost.MultiArray in C++
What changes has been made in the code since last question?
The previous question is the implementation of element_wise_add function for Boost.MultiArray. Based on G. Sliepen's suggestion, this kind of element-wise operations could be implemented with C++ operator overloading. As the result, here comes the operator+ and operator- overload functions for Boost.MultiArray.
Why a new review is being asked for?
The operator+ and operator- overload functions here include the exception handling for the situation of different dimensions and shapes. Please check if this usage is appropriate. Moreover, I am still seeking another smarter method to improve the construction of output object. If there is any better idea for deducing the output structure from input without copying process, please let me know.
Answer:
if (input1.num_dimensions() != input2.num_dimensions())
{
throw std::logic_error("Array dimensions are different");
}
If I'm not mistaken, the dimensions are static, and can be accessed through the array class's dimensionality constant, so I think this check could be part of the function requiresments, rather than a run-time error.
if (*input1.shape() != *input2.shape())
{
throw std::logic_error("Array shapes are different");
}
Is it possible to create an array with num_dimensions() == 0? I think we could use a (probably static_) assertion to prove to ourselves and later maintainers that dereferencing the pointer returned by shape() is safe.
I believe *input1.shape() could be written as input1.size(), which is simpler.
for (decltype(+input1.shape()[0]) i = 0; i < input1.shape()[0]; i++)
Isn't input1.shape()[0] simply *input1.shape()? i.e. input1.size() again.
boost::multi_array output(input1); | {
"domain": "codereview.stackexchange",
"id": 43149,
"lm_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++, recursion, c++20, boost, constrained-templates",
"url": null
} |
c++, recursion, c++20, boost, constrained-templates
boost::multi_array output(input1);
So... the type of the output array is always the same as the type of input1? This seems very arbitrary, and could lead to unexpected type differences when simply changing a + b to b + a.
Perhaps we could use decltype(input1[0] + input2[0]) to get a more appropriate "common" element type for the output?
It might be neater to implement operator+= instead, and then implement operator+ using operator+=.
(And similarly for operator-= and operator-). | {
"domain": "codereview.stackexchange",
"id": 43149,
"lm_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++, recursion, c++20, boost, constrained-templates",
"url": null
} |
c++, embedded, arm
Title: Abstraction for embedded C++ register operations
Question: I just started with embeddeded C++ since I only coded in C for the last year and I wanted to do/learn something while I'm in university.
First of the there is the Register manipulation class. I won't include the .cpp file since stuff done there is trivial.
register.hpp:
class Reg {
public:
Reg(uint32_t *reg, uint32_t reset_value);
Reg();
uint32_t read();
bool bit_set(int n);
void reset();
void set_bit(int n);
void write(uint32_t n);
void clear_bit(int n);
private:
uint32_t *reg;
uint32_t reset_value;
};
gpio_port.hpp:
class gpio_port {
public:
gpio_port(GPIO_TypeDef *port);
gpio_port();
Reg moder;
Reg otyper;
Reg ospeedr;
Reg pupdr;
Reg idr;
Reg odr;
Reg bsrr;
Reg lckr;
Reg afrl;
Reg afrh;
private:
GPIO_TypeDef *port;
};
gpio_port.cpp:
gpio_port::gpio_port(GPIO_TypeDef* port) {
this->port = port;
this->moder = Reg((uint32_t *) &this->port->MODER, 0x0000);
this->otyper = Reg((uint32_t *) &this->port->OTYPER, 0x0000);
this->ospeedr = Reg((uint32_t *) &this->port->OSPEEDR, 0x0000);
this->pupdr = Reg((uint32_t *) &this->port->PUPDR, 0x0000);
this->idr = Reg((uint32_t *) &this->port->IDR, 0x0000);
this->odr = Reg((uint32_t *) &this->port->ODR, 0x0000);
this->bsrr = Reg((uint32_t *) &this->port->BSRR, 0x0000);
this->lckr = Reg((uint32_t *) &this->port->LCKR, 0x0000);
this->afrl = Reg((uint32_t *) &this->port->AFR[0], 0x0000);
this->afrh = Reg((uint32_t *) &this->port->AFR[1], 0x0000);
}
gpio_port::gpio_port() {
this->port = nullptr;
} | {
"domain": "codereview.stackexchange",
"id": 43150,
"lm_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++, embedded, arm",
"url": null
} |
c++, embedded, arm
gpio_port::gpio_port() {
this->port = nullptr;
}
cosmic.hpp
namespace csmc {
namespace peripherals {
static gpio_port gpioa = gpio_port(GPIOA);
static gpio_port gpiob = gpio_port(GPIOB);
static gpio_port gpioc = gpio_port(GPIOC);
static gpio_port gpiod = gpio_port(GPIOD);
static gpio_port gpioe = gpio_port(GPIOE);
static gpio_port gpioh = gpio_port(GPIOH);
}
};
So here you see the Reg class is the abstraction for each Register. It can be applied to any u32 value.
gpio_port was a simple struct first. But initializing it in the cosmic.hpp for each GPIO port looked really messy so I moved it into a class.
The namespaces are the actual libray I want to write.
Here is some example usage:
#include "cosmic/cosmic.hpp"
using namespace csmc;
int main() {
gpio_port gpioa = peripherals::gpioa;
gpio_port gpiob = peripherals::gpiob;
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOBEN;
gpioa.moder.set_bit(16);
gpiob.moder.set_bit(16);
while (1) {
gpioa.odr.set_bit(8);
gpiob.odr.set_bit(8);
delay();
gpioa.odr.clear_bit(8);
gpiob.odr.clear_bit(8);
delay();
}
}
My naming conventions are not that standard for embeddeded Development as far as I know. I'm open for all suggestions and better code structure. :D
Answer: Before you read my comments I did something similar, but just used #defines, what you have done is a good step forwards :)
In Register.hpp | {
"domain": "codereview.stackexchange",
"id": 43150,
"lm_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++, embedded, arm",
"url": null
} |
c++, embedded, arm
If a parameter to a function can't be changed make it const. It
helps document the code.
If a function doesn't change member data then make the function const.
Make the class a template ad you could use it for 8/16/32/64 bit processors without having to change things. (Although templates might not work too well with all embedded compilers)
Use an enum for the bit number. You will get compile time checking that the bit is in range. You could make this a template parameter too.
e.g.:
enum class ExampleBits
{
bit0, bit1, bit2, bit3, bit4, bit5
};
template <class Storage, class Bits>
class Reg
{
public:
Reg(const Storage* reg, const Storage reset_value);
Reg();
Storage read() const;
bool is_bit_set(const Bits n) const; // Changed name
void reset();
void set_bit(const int n);
void write(const Storage n);
void clear_bit(const int n);
private:
Storage* reg;
Storage reset_value;
};
gpio_port
I think public members are almost always a mistake. I can't think of a reason why thats not true here, but I can see why you have done it with the code as it is.
If you add a public enum to the class with the list of register names and then store the reg items in an "array".
Provide a function that has a parameter of the above enum and it returns a reference to the reg object.
You don't need this-> in the constructor.
You do need to check that port is not null before you use it, otherwise you get a segmentation error.
Use a static_cast rather than a C style cast.
You have used a 16 bit reset value in your call to the Reg constructor.
Naming the parameter and the member variable the same thing is a recipe for confusion, add m_ to all member variables.
Not setting the Reg values in teh second constructor, means the Reg() constructor must make the Reg::reg value safe, i.e. null it and all the functions in Reg must protect against dereferencing that pointer when its null. | {
"domain": "codereview.stackexchange",
"id": 43150,
"lm_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++, embedded, arm",
"url": null
} |
c++, embedded, arm
It depends on how you are going to use the code and if all the gpio_ports are always available, but I would be tempted to make a Peripherals class. That way you know they are all available and initialised all at the same time.
Using a using namespace csmc; statement means you don't need the csmc namespace. peripherals is quite a common name and I suggest that you do need csmc so stop being lazy and write it on both of the times you need it. Its actually less characters than the using statement, it means there is no doubt over which peripherals namespace you are using and it makes the code MUCH easier to read. Summary 'There is almost never any reason to write a using namespace xxx; statement, almost.'
Now stop your crying for a minute and go back to the top of this answer, what you have done is much better than my attempt. Its always easier to critic code than write it, and I am going to 'borrow' some ideas from your post to improve mine (when I get round to it:) ) | {
"domain": "codereview.stackexchange",
"id": 43150,
"lm_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++, embedded, arm",
"url": null
} |
javascript
Title: Efficient text scroller
Question: I wrote this small test. I would love to know if it's possible to achieve the same result in a more "efficient" way. Before any moderator closes this question, it's not subjective because my definition of efficient here means less lines of code and less memory usage.
Here is a demo: http://jsfiddle.net/YsjLp/
And here is the JavaScript code:
var position = 0;
var divToEdit = document.getElementById('here');
function executeIt(){
setInterval(function(){moveIt()},300);
}
function moveIt(){
var textToInsert = '';
var textLength = 10;
for (var i = 0; i <= textLength; i++) {
if(i == position){
textToInsert += '[-]';
}else{
textToInsert += '-';
}
};
if(position == textLength){
position = 0;
}else{
position += 1;
}
divToEdit.innerHTML = textToInsert;
}
executeIt();
Answer: As you define efficient to be "less lines of code", here it is:
function moveIt(){
var textToInsert = '';
var textLength = 10;
for (var i = 0; i <= textLength; i++)
textToInsert+= (i==position)?'[-]':'-';
(position==textLength)?position=0:position++;
divToEdit.innerHTML = textToInsert;
}
Demo: http://jsfiddle.net/YsjLp/3/ | {
"domain": "codereview.stackexchange",
"id": 43151,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
python, performance, breadth-first-search
Title: performance - Word ladder leetcode
Question: I am working on Word Ladder - LeetCode
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
Example 1:
Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
Example 2:
Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Output: 0
Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
My Approach:
Create a graph with word distances
Calculate the distance to the endWord using BFS
Code:
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList:
return 0
graph = {}
wordList = [beginWord] + wordList if beginWord not in wordList else wordList
for i in range(len(wordList)):
wordU = wordList[i]
# Compute distances and prepare a graph when the distance is equal to one
for j in range(i+1, len(wordList)):
wordV = wordList[j]
if wordU not in graph.keys():
graph[wordU] = []
if wordV not in graph.keys():
graph[wordV] = [] | {
"domain": "codereview.stackexchange",
"id": 43152,
"lm_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, breadth-first-search",
"url": null
} |
python, performance, breadth-first-search
if self.word_difference(wordU, wordV) == 1:
graph[wordU].append(wordV)
graph[wordV].append(wordU)
visited = set()
queue = [beginWord]
distances = {w:1 for w in queue} # since the first word is 1 we are putting 2 here for the root
return self.BFS(graph, endWord, visited, queue, distances)
def word_difference(self, word1, word2):
# Compute the difference in words
distance = 0
for c1, c2 in zip(word1, word2):
if c1 != c2:
distance += 1
return distance
def BFS(self, graph, endNode, visited, queue, distances):
while queue:
node = queue.pop(0)
if node not in visited:
visited.add(node)
if node == endNode:
return distances[node]
for neighbour in graph[node]:
if neighbour not in visited:
visited.add(neighbour)
distances[neighbour] = distances[node] + 1
queue.append(neighbour)
return 0
The problem is that the above code is failing on a test case with large word list.
The discussions forum had a solution which took a similar approach but is clearing all the test cases. How can I optimize my solution?
Answer: Measure first. If you have a performance problem, make sure you know where
it is. A simple, low-tech way to do this is to start throwing time markers into
the code and printing the elapsed time for different phases of the work. In
your case, the graph-building is the costly part of the process, so there's no
need to waste time thinking about how to optimize the BFS code.
from time import time
t1 = time()
... # Do some work.
t2 = time()
... # Do some other work
t3 = time()
print('Phase 1', t2 - t1)
print('Phase 2', t3 - t2) | {
"domain": "codereview.stackexchange",
"id": 43152,
"lm_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, breadth-first-search",
"url": null
} |
python, performance, breadth-first-search
print('Phase 1', t2 - t1)
print('Phase 2', t3 - t2)
Your algorithm and the one from the discussion forum are quite different.
Yes, they both build a graph and then use BFS on it. But, as noted, the
performance problem lies in the graph building. Your algorithm is O(N*N):
nested loops over wordList. But the other solution is effectively O(N)
because the inner loop is over the positions in the current word, not the
entire word list.
# Your approach: O(N*N).
for i in range(len(wordList)):
...
for j in range(i+1, len(wordList)):
...
# Discussion forum: O(N*m), where m is tiny, effectively a constant.
for word in word_list:
for i in range(len(word)):
...
Too much computation: word difference is not relevant. A clue that your
algorithm is inefficient comes from realizing that we don't actually care about
word distances. Our goal is to build a graph linking immediate neighbors (those
having a difference of exactly 1), but your algorithm does the work of actually
computing all pairwise differences.
Invert the strategy: create linking keys. Suppose you realize that you
don't need the word differences. The problem becomes, how do we find immediate
neighbors (those having a difference of exactly 1) without actually computing
any differences? That's not an easy question to answer, of course, and to some
extent it requires a leap of insight. Nonetheless, there is still a general
lesson to be learned. The wildcard-based strategy in the discussion forum
achieves that goal by figuring out a way to map each word to some linking-keys,
such that immediate neighbors will share a common key. The way to do that is to
convert each word (a sequence of characters) into other sequences of
characters where each character gets replaced by a generic value.
# The word
dog
# Its linking keys
_og
d_g
do_ | {
"domain": "codereview.stackexchange",
"id": 43152,
"lm_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, breadth-first-search",
"url": null
} |
python-3.x, classes
Title: Comparing custom Geometry classes (Lines and Planes): How to increase the accuracy of the __eq__ method
Question: I'm creating custom classes to represent Planes and Lines on a 3d graph. To help improve the performance of my process I've started implementing __eq__ so that I can eliminate duplicate objects in a list using objList = set(objList).
I'm wondering how to efficiently expand the __eq__ methods so that it can compare if the objects represent the same "geometry" on a graph? ie: Plane 0=ax+by+cz+d should be marked as equal to 0=2ax+2by+2cz+2d
For the planes class I've added two version but I'm worried that my second version isn't proper since the hashes of both objects won't be same and or that precision issues might reject objects that are equal.
ie: [conceptual not actual example] 6/3 = 2.0000000001 instead of 2/1 = 2
Note: I include both classes (Plane and Line) in this post because even if the algebra is different between the two classes, I assume that the main idea of how to approach this problem will be the same between both classes.
class Plane_v1:
'''
0 = ax + by + cz + d
'''
a = None
b = None
c = None
d = None
def __str__(self):
return f"Plane\n\ta :{self.a}\tb :{self.b}\tc :{self.c} \n\td: {self.d}"
def __hash__(self):
return hash((self.a, self.b, self.c, self.d))
def __eq__(self, value):
if value is None: return False
return self.a == value.a and self.b == value.b and self.c == value.c and self.d == value.d
class Plane_v2:
'''
0 = ax + by + cz + d
'''
a = None
b = None
c = None
d = None
def __str__(self):
return f"Plane\n\ta :{self.a}\tb :{self.b}\tc :{self.c} \n\td: {self.d}"
def __hash__(self):
return hash((self.a, self.b, self.c, self.d)) | {
"domain": "codereview.stackexchange",
"id": 43153,
"lm_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-3.x, classes",
"url": null
} |
python-3.x, classes
def __hash__(self):
return hash((self.a, self.b, self.c, self.d))
def __eq__(self, value):
if value is None: return False
if self.d == 0 or value.d == 0:
return self.a == value.a and self.b == value.b and self.c == value.c and self.d == value.d
return self.a/self.d == value.a/value.d and self.b/self.d == value.b/value.d and self.c/self.d == value.c/value.d
class Line:
'''
x = x0 + ta
y = y0 + tb
z = z0 + tc
'''
x0 = None
y0 = None
z0 = None
a = None
b = None
c = None
def __str__(self):
return f"Line\n\tx0:{self.x0}\ty0:{self.y0}\tz0:{self.z0} \n \ta :{self.a}\tb :{self.b}\tc :{self.c}"
return super().__str__()
def __hash__(self):
return hash((self.a, self.b, self.c, self.x0, self.y0, self.z0))
def __eq__(self, value):
if value is None: return False
return self.a == value.a and self.b == value.b and self.c == value.c and self.x0 == value.x0 and self.y0 == value.y0 and self.z0 == value.z0
Answer: Here's a couple of things you can do: | {
"domain": "codereview.stackexchange",
"id": 43153,
"lm_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-3.x, classes",
"url": null
} |
python-3.x, classes
Answer: Here's a couple of things you can do:
Include an __init__ function. Since the Plane class isn't very complex or dynamic, this is best acheived using a dataclass (Note: dataclasses where introduced in python3.7).
Make the class immutable, which provides stronger hash guarantees (otherwise it would be possible for an object in a set to be mutated, resulting in an incorrect state for the set). We can make the class immutable by passing the frozen=True parameter to the dataclass decorator.
The __eq__ method works as intended, but the __hash__ function does not. For example, 0 = 1x + 2y + 3z + 10 and 0 = 2x + 4y + 6z - 123 would be equal but would not have the same hash (we want them to have the same hash). To achieve this, we can use the unit vectors [a, b, c] since the unit vectors for both equations will be the same if the two planes have the same geometry. The unit vectors can be used for both __eq__ and __hash__.
To avoid float point precision errors, we can make use of python's fractions or decimal libraries.
Here's the full code which implements the above changes:
from dataclasses import dataclass
from fractions import Fraction
def compute_unit_vector(vector: tuple) -> tuple:
total = sum(map(abs, vector))
# if total = 0, that means the vector is a zero vector, which will cause
# a division by zero error when calculating the unit vector, so we explicitly
# check this case here
if total == 0:
return vector
# we use Fraction here to prevent float point precision errors
return tuple(Fraction(x, total) for x in vector)
@dataclass(frozen=True)
class Plane:
"""0 = ax + by + cz + d"""
a: float
b: float
c: float
d: float
@property
def unit_vector(self):
return compute_unit_vector((self.a, self.b, self.c))
def __hash__(self) -> int:
return hash(self.unit_vector)
def __eq__(self, other: object) -> bool:
return self.unit_vector == other.unit_vector | {
"domain": "codereview.stackexchange",
"id": 43153,
"lm_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-3.x, classes",
"url": null
} |
python-3.x, classes
def __eq__(self, other: object) -> bool:
return self.unit_vector == other.unit_vector
Here's an example using a set:
set([Plane(1, 2, 3, 4), Plane(2, 4, 6, 8), Plane(0, 0, 0, 0), Plane(-2, -4, -6, -8)])
Which results in the set:
{Plane(a=-2, b=-4, c=-6, d=-8),
Plane(a=0, b=0, c=0, d=0),
Plane(a=1, b=2, c=3, d=4)}
Edit: We can make things a bit faster if we initialize self.unit_vector in __post_init__ instead of as an @property method, since @property will recalculate every time it is called:
# replace the @property def unit_vector method with this instead
def __post_init__(self) -> None:
# this is a hack, we can't do self.unit_vector = unit_vector
# because the object is immutable via frozen=True
unit_vector = compute_unit_vector((self.a, self.b, self.c))
object.__setattr__(self, 'unit_vector', unit_vector) | {
"domain": "codereview.stackexchange",
"id": 43153,
"lm_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-3.x, classes",
"url": null
} |
python, pandas
Title: change object column to numeric above cardinality threshold pandas
Question: Is the following an acceptable way to change an object column to numeric if cardinality threshold (cardinality_threshold) is being breached? I think it would be good to check if column values are numeric though. Thanks!
data = {
'col1':['1', '2', '3'],
'col2':['1', '1', '2'],
}
df = pd.DataFrame(data)
df
cardinality_threshold = 2
cols = [i for i in df.columns]
for i in cols:
if(len(df[i].value_counts()) > cardinality_threshold) :
df[i] = pd.to_numeric(df[i]) # , errors = 'coerce'
print(df.info())
Answer:
Use DataFrame.nunique to vectorize the cardinality check
Use DataFrame.apply to convert to_numeric (not vectorized, but more idiomatic than loops)
Use uppercase for CARDINALITY_THRESHOLD per PEP8 style for constants
CARDINALITY_THRESHOLD = 2
breached = df.columns[df.nunique() > CARDINALITY_THRESHOLD]
df[breached] = df[breached].apply(pd.to_numeric, errors='coerce')
>>> df.dtypes
# col1 int64
# col2 object
# dtype: object
I think it would be good to check if column values are numeric though.
Note that to_numeric already skips numeric columns, so it's simplest to just let pandas handle it.
If you still want to explicitly exclude numeric columns:
Use DataFrame.select_dtypes to get the non-numeric columns
Use Index.intersection to get the non-numeric breached columns
breached = df.columns[df.nunique() > CARDINALITY_THRESHOLD]
non_numeric = df.select_dtypes(exclude='number').columns
cols = non_numeric.intersection(breached)
df[cols] = df[cols].apply(pd.to_numeric, errors='coerce') | {
"domain": "codereview.stackexchange",
"id": 43154,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, pandas",
"url": null
} |
php, datetime
Title: Get Next Working Date, skip weekends and holidays
Question: The object is to be able to pass some dates (start date, holiday) and the number of days you want to skip. We only want to skip working days, not weekends and holidays.
Just let me know what you'd do different than what I have. The code works, but I was told there are issues with it, but not told what issues they are.
function getWDays($startDate,$holiday,$wDays){
$d = new DateTime( $startDate );
$t = $d->getTimestamp();
$h = strtotime($holiday);
// loop for $wDays days
for($i=0; $i<$wDays; $i++){
// 1 day = 86400 seconds
$addDay = 86400;
$nextDay = date('w', ($t+$addDay));
if($nextDay == 0 || $nextDay == 6) {
$i--;
}
$t = $t+$addDay;
if ($t == $h) {
// lets make sure the holiday isn't one of our weekends
if(!$nextDay == 0 || !$nextDay == 6) {
$t = $t+$addDay;
}
}
}
$d->setTimestamp($t);
return $d->format( 'Y-m-d' );
}
echo getWDays("2013-08-29","2013-09-02", 3)
Answer: Here is another way of doing the same thing
<?php
function getWDays($startDate,$holiday,$wDays) {
// using + weekdays excludes weekends
$new_date = date('Y-m-d', strtotime("{$startDate} +{$wDays} weekdays"));
$holiday_ts = strtotime($holiday);
// if holiday falls between start date and new date, then account for it
if ($holiday_ts >= strtotime($startDate) && $holiday_ts <= strtotime($new_date)) {
// check if the holiday falls on a working day
$h = date('w', $holiday_ts);
if ($h != 0 && $h != 6 ) {
// holiday falls on a working day, add an extra working day
$new_date = date('Y-m-d', strtotime("{$new_date} + 1 weekdays"));
}
}
return $new_date;
}
// here is an example
$start = "2013-08-29";
$holiday = "2013-09-02";
$wDays = 3; | {
"domain": "codereview.stackexchange",
"id": 43155,
"lm_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, datetime",
"url": null
} |
php, datetime
// here is an example
$start = "2013-08-29";
$holiday = "2013-09-02";
$wDays = 3;
echo "Start: ",date("Y-m-d D", strtotime($start)),"<br />";
echo "Holiday: ",date("Y-m-d D", strtotime($holiday)),"<br />";
echo "WDays: $wDays<br />";
echo getWDays($start, $holiday, $wDays); | {
"domain": "codereview.stackexchange",
"id": 43155,
"lm_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, datetime",
"url": null
} |
java, homework, swing, sqlite, jdbc
Title: Searchable database with Java and SQL
Question: What does the code do?
Albeit unfinished (it does work, it's just not complete yet), the code creates a database (members.db) where telephone numbers, IDs, and names are stored. After which, the user can input what they'd like to do, e.g. show every telephone number in the db, every surname etc. The plan further down the line is to implement a backup function as well.
The code works as it is now, but I think it could be refactored to shorten it, which is what I'd like.
import static javax.swing.JOptionPane.*;
import static java.lang.Integer.*;
import java.util.*;
import static java.lang.System.*;
import java.sql.*;
import java.io.*;
public class memberList {
private static File dBfile = new File("members.db");
public static void main(String[] args) throws Exception {
if (!dBfile.exists())
createNewTable();
int choice = 0;
do {
choice = showMenu();
if (choice != 0) {
switch (choice) {
case 1:
showAllSurname();
break;
case 2:
showAllTelephone();
break;
default:
break;
}
}
} while (choice != 0);
}
private static int showMenu() {
String menu = "[1] Show all surnames" + "\n"
+ "[2] Show all telephone numbers";
return parseInt(showInputDialog(menu + "\n" + "Please choose between 0 - 2:"));
}
private static void createNewTable() {
String url = "jdbc:sqlite:members.db";
Connection connect = null;
Scanner read = null;
Statement stat = null; | {
"domain": "codereview.stackexchange",
"id": 43156,
"lm_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, homework, swing, sqlite, jdbc",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.