text
stringlengths
1
2.12k
source
dict
python, sqlite, connection-pool async def release_resource(self, res): if self._is_hashable_resource: if res not in self._in_use: raise Exception('Releasing unknown object') # Could raise exception if two threads are releasing the same resource: self._in_use.remove(res) self._pool.append(res) # If someone is waiting for a resource: async with self._resource_returned: self._resource_returned.notify() @asynccontextmanager async def resource(self, timeout=None): res = await self.get_resource(timeout) try: yield res finally: await self.release_resource(res) import aiosqlite3 class ConnectionPool(ResourcePool): def __init__(self, max_connections, database): super().__init__(max_connections) self._database = database async def create_resource(self): return await aiosqlite3.connect(self._database, asyncio.get_running_loop()) def get_connection(self, timeout=None): return self.get_resource(timeout) async def release_resource(self, connection): await connection.rollback() # clean up return await super().release_resource(connection) def release_connection(self, connection): return self.release_resource(connection) def connection(self, timeout=None): return self.resource(timeout) if __name__ == "__main__": async def worker(pool, n): try: for i in range(10): async with pool.connection() as conn: cursor = await conn.cursor() await cursor.execute('SELECT COUNT(*) FROM braintree_transaction') row = await cursor.fetchone() await cursor.close() print(n, i, row[0]) await asyncio.sleep(.0001) except Exception as e: print(e)
{ "domain": "codereview.stackexchange", "id": 44850, "lm_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, sqlite, connection-pool", "url": null }
python, sqlite, connection-pool connection_pool = ConnectionPool(2, database='fncpl.db') tasks = [worker(connection_pool, n) for n in range(3)] loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.gather(*tasks)) loop.run_until_complete(connection_pool.close()) loop.close() A sample implementation that is based on threads (not suitable for a sqlite3 pool) would be: Sample Multi-threaded Implementation from abc import ABC, abstractmethod from collections import deque from threading import Lock, Condition from contextlib import contextmanager class ResourcePool(ABC): def __init__(self, max_resources): if max_resources < 1: raise ValueError(f'Invalid max_resources argument: {max_resources}') self._max_resources = max_resources self._request_lock = Lock() self._resource_returned = Condition() self._pool = deque() self._n_resources_created = 0 self._is_hashable_resource = self.is_hashable_resource() self._in_use = set() def close(self): """Close all resources.""" with self._request_lock: while self._pool: self.close_resource(self._pool.popleft()) while self._in_use: self.close_resource(self._in_use.pop()) def close_resource(self, res): """Subclasses should override this method if the resource does not implement a close method.""" res.close() def __del__(self): """Close all resources when the pool is garbage collected. Note that due to how close is implemented, it may be called multiple times.""" self.close() def is_hashable_resource(self): """Override this function and return False if the resource cannot be added to a set. Otherwise, we can do some additional error checking and ensure that all resources are closed when method close is called.""" return True @abstractmethod def create_resource(self): pass
{ "domain": "codereview.stackexchange", "id": 44850, "lm_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, sqlite, connection-pool", "url": null }
python, sqlite, connection-pool @abstractmethod def create_resource(self): pass def get_resource(self, timeout=None): if timeout is None: timeout = 10 with self._request_lock: while True: if self._pool: res = self._pool.popleft() if self._is_hashable_resource: self._in_use.add(res) return res # Can we create another resource? if self._n_resources_created < self._max_resources: self._n_resources_created += 1 res = self.create_resource() if self._is_hashable_resource: self._in_use.add(res) return res # We must wait for a resource to be returned with self._resource_returned: if not self._resource_returned.wait(timeout=timeout): raise RuntimeError("Timeout: No available resource in the pool.") # The pool now has at least one resource available and # we will succeed on next iteration. def release_resource(self, res): if self._is_hashable_resource: if res not in self._in_use: raise Exception('Releasing unknown object') # Could raise exception if two threads are releasing the same resource: self._in_use.remove(res) self._pool.append(res) # Notify the thread waiting for a resource, if any: with self._resource_returned: self._resource_returned.notify() @contextmanager def resource(self, timeout=None): res = self.get_resource(timeout) try: yield res finally: self.release_resource(res) import mysql.connector
{ "domain": "codereview.stackexchange", "id": 44850, "lm_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, sqlite, connection-pool", "url": null }
python, sqlite, connection-pool import mysql.connector class ConnectionPool(ResourcePool): def __init__(self, max_connections, database, user, password, time_zone='America/New_York'): super().__init__(max_connections) self._database = database self._user = user self._password = password self._time_zone = time_zone def create_resource(self): return mysql.connector.connect(database=self._database, user=self._user, password=self._password, charset='utf8mb4', use_unicode=True, init_command=f"set session time_zone='{self._time_zone}'" ) def get_connection(self, timeout=None): return self.get_resource(timeout) def release_resource(self, connection): connection.rollback() # clean up return super().release_resource(connection) def release_connection(self, connection): return self.release_resource(connection) def connection(self, timeout=None): return self.resource(timeout) if __name__ == '__main__': from multiprocessing.pool import ThreadPool def worker(pool, n): try: for i in range(10): with pool.connection() as conn: cursor = conn.cursor() cursor.execute('SELECT COUNT(*) FROM transaction') cnt = cursor.fetchone()[0] cursor.close() print(n, i, cnt) except Exception as e: print(e) connection_pool = ConnectionPool(2, database='test_db', user='***', password='***') thread_pool = ThreadPool(3) for n in range(3): thread_pool.apply_async(worker, args=(connection_pool, n)) thread_pool.close() thread_pool.join()
{ "domain": "codereview.stackexchange", "id": 44850, "lm_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, sqlite, connection-pool", "url": null }
python, sqlite, connection-pool Note that in both of these implementations if the resource being created can be hashed, then we can create a set to which we add resources that have been given out to clients. This allows us to provide an additional check to ensure that a client cannot return to the pool a resource that was never taken from the pool. It also allows the close method to close all resources including those that have not been returned back to the pool yet. There is no reason why this logic cannot be incorporated into the asyncio version.
{ "domain": "codereview.stackexchange", "id": 44850, "lm_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, sqlite, connection-pool", "url": null }
c, console, complex-numbers Title: A simple CLI arbitrary-precision Mandelbrot set calculator (for a single point) Question: I wrote the following C code that takes a couple of arguments on the command line and calculates a given number of iterations of the Mandelbrot set complex mapping using MPFR arbitrary precision arithmetic. Is it well-written? Does it have undefined behaviour or is unsafe? Here is the code: Makefile CC := gcc O := 1 CFLAGS := -Wall -Wpedantic -std=gnu17 -O$(O) $(XCFLAGS) XCFLAGS := mpfrtest: mpfrtest.o $(CC) $(CFLAGS) -lm -lmpfr $^ -o $@ mpfrtest.o: mpfrtest.c $(CC) $(CFLAGS) -c $^ -o $@ clean: rm -f *.o rm -f mpfrtest mpfrtest.c #include <complex.h> #include <errno.h> #include <inttypes.h> #include <math.h> #include <mpfr.h> #include <stdio.h> #include <stdlib.h> #define ESCAPE_NORM 4 #define ROUND MPFR_RNDN
{ "domain": "codereview.stackexchange", "id": 44851, "lm_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, console, complex-numbers", "url": null }
c, console, complex-numbers #define ESCAPE_NORM 4 #define ROUND MPFR_RNDN size_t orbit(const mpfr_t c_re, const mpfr_t c_im, size_t M, double complex *output, mpfr_prec_t prec, mpfr_rnd_t round, void (*callback)(size_t)) { mpfr_t z_re, z_im; mpfr_inits2(prec, z_re, z_im, NULL); mpfr_set_ui(z_re, 0, round); mpfr_set_ui(z_im, 0, round); mpfr_t re_tmp, im_tmp; mpfr_inits2(prec, re_tmp, im_tmp, NULL); double interval_d = ceil(sqrt((double)M)); size_t interval; if (interval_d < 1) { interval = 1; } else { interval = (size_t)interval_d; } output[0] = 0; size_t m = 0; for (; m < M && mpfr_cmp_ui(re_tmp, ESCAPE_NORM) <= 0; m++) { mpfr_sqr(re_tmp, z_re, round); mpfr_sqr(im_tmp, z_im, round); mpfr_sub(im_tmp, im_tmp, c_re, round); mpfr_sub(re_tmp, re_tmp, im_tmp, round); mpfr_mul(z_im, z_re, z_im, round); mpfr_mul_ui(z_im, z_im, 2, round); mpfr_add(z_im, z_im, c_im, round); mpfr_set(z_re, re_tmp, round); output[m] = mpfr_get_d(z_re, round) + mpfr_get_d(z_im, round) * I; mpfr_sqr(re_tmp, z_re, round); mpfr_sqr(im_tmp, z_im, round); mpfr_add(re_tmp, re_tmp, im_tmp, round); if (m % interval == 0) { (*callback)(m); } } mpfr_clears(re_tmp, im_tmp, z_re, z_im, NULL); return m; } int digitsiz(size_t value) { value++; int count = 0; while (value >= 10) { value /= 10; count++; } return count; } void progress(size_t m) { fprintf(stderr, "computed iteration %zu\n", m); }
{ "domain": "codereview.stackexchange", "id": 44851, "lm_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, console, complex-numbers", "url": null }
c, console, complex-numbers int main(int argc, char **argv) { if (argc != 5) { fprintf(stderr, "wrong argument count %d, should be 4\n", argc - 1); fprintf( stderr, "usage: %s <Re[c]> <Im[c]> <precision> <maximum iteration count>\n", argv[0]); exit(-5); } char *endptr; errno = 0; signed long prec_l = strtol(argv[3], &endptr, 10); if (argv[3][0] == '\0' || *endptr != '\0') { fprintf(stderr, "failed to parse argument precision as a number\n"); exit(-3); } if (errno == ERANGE) { fprintf(stderr, "argument precision is too large\n"); exit(-3); } if (prec_l <= 0) { fprintf(stderr, "argument precision must be positive\n"); exit(-3); } mpfr_prec_t prec = (mpfr_prec_t)prec_l; errno = 0; uintmax_t iter_umax = strtoumax(argv[4], &endptr, 10); if (argv[4][0] == '\0' || *endptr != '\0') { fprintf( stderr, "failed to parse argument maximum iteration count as a number\n"); exit(-4); } if (iter_umax > (uintmax_t)SIZE_MAX || errno == ERANGE) { fprintf(stderr, "argument maximum iteration count is too large\n"); exit(-4); } size_t iter = (size_t)iter_umax; mpfr_t c_re; mpfr_t c_im; mpfr_inits2(prec, c_re, c_im, NULL); if (mpfr_set_str(c_re, argv[1], 10, ROUND) != 0) { fprintf(stderr, "failed to parse argument Re[c] as a number\n"); mpfr_clears(c_re, c_im, NULL); exit(-4); }; if (mpfr_set_str(c_im, argv[2], 10, ROUND) != 0) { fprintf(stderr, "failed to parse argument Im[c] as a number\n"); mpfr_clears(c_re, c_im, NULL); exit(-5); } double complex *result = malloc(iter * sizeof(double complex)); if (result == NULL) { perror("orbit array allocation"); mpfr_clears(c_re, c_im, NULL); exit(-6); } size_t m = orbit(c_re, c_im, iter, result, prec, ROUND, progress);
{ "domain": "codereview.stackexchange", "id": 44851, "lm_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, console, complex-numbers", "url": null }
c, console, complex-numbers exit(-6); } size_t m = orbit(c_re, c_im, iter, result, prec, ROUND, progress); if (m == SIZE_MAX) { printf("iterations = max"); } else { printf("iterations = %zu\n", m); } int width = digitsiz(m); for (size_t i = 0; i < m; i++) { printf("orbit[%0*zu] = %13.6e + %13.6ei\n", width, i, creal(result[i]), cimag(result[i])); } mpfr_clears(c_re, c_im, NULL); free(result); }
{ "domain": "codereview.stackexchange", "id": 44851, "lm_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, console, complex-numbers", "url": null }
c, console, complex-numbers Answer: Only for the pedantic strtou...() functions have a quirk in that strtoumax("-1", &endptr, 10) is some large positive value without setting errno. If that is OK, 'nuff said. If code wants to detect negative strings, consider strtomax() and test the range. // Demonstrative unchecked code. // Like strtoumax()`, yet caps negative conversions rather than wrap. // This does allow "-0" to quietly return 0 with no setting of `errno`. uintmax_t strtoumax_alt(const char * restrict nptr, char ** restrict endptr, int base) { // Usually `errno = 0` set by calling code. intmax_t i = strtomax(nptr, endptr, base); if (i > INTMAX_MAX - 1) { if (errno == ERANGE) { errno = 0; } return strtoumax(nptr, endptr, base); } if (i < 0) { errno = ERANGE; return 0; } return (uintmax_t) i; } errno complicates things.*1 argc == 0 possible Following code is then UB. if (argc != 5) { ... fprintf(stderr, "usage: %s ...\n", argv[0]); *1 strto...() functions are most clearly used if the calling code first performs errno = 0; This strtoumax_alt(), with its two step of approach of strtointmax()/strtouintmax() like-wise works best if the caller first performs errno = 0; Yet if we want to better handle cases where strtoumax_alt() is called with a non-zero errno and regular strtoumax() does not set errno with the given parameters, then consider restoring errno before the 2nd strto...() function. So if the calling code is somehow accumulating errors in errno, this restoration will better support that. uintmax_t strtoumax_alt(const char * restrict nptr, char ** restrict endptr, int base) { int errno_original = errno; intmax_t i = strtomax(nptr, endptr, base); if (i > INTMAX_MAX - 1) { errno = errno_original; return strtoumax(nptr, endptr, base); } ...
{ "domain": "codereview.stackexchange", "id": 44851, "lm_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, console, complex-numbers", "url": null }
c, console, complex-numbers I suppose now there may be a race condition if 2 threads execute strtoumax_alt(), yet often such threads roll their own copy of errno. Messing with global objects for error indication is tricky. How I wish C afforded a direct return value and error flag feature (without a struct).
{ "domain": "codereview.stackexchange", "id": 44851, "lm_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, console, complex-numbers", "url": null }
python Title: Script that tells you the amount of base required to neutralise acidic nootropic Question: Function Gives the mass needed of specific basic (pH above 7) substance in order to neutralise the pH of a specific acidic substance. from decimal import Decimal as d # m = mass # n = moles # M = molar mass MkHCO3 = 100.11 MnaKHCO3 = 84.007 MphenHCl = 215.67 moles = lambda m,M: m/M nPhenHCl = moles(1.54, MphenHCl) mSubstance = lambda x,y: x*y mKHCO3 = mSubstance(MkHCO3, nPhenHCl) mNaHCO3 = mSubstance(MnaKHCO3, nPhenHCl) nl = '\n' print(f'{nl}KHCO3:') print(f'{d(mKHCO3):.2f}g{nl}') print(f'NaHCO3:') print(f'{d(mNaHCO3):.2f}g{nl}') Output KHCO3: 0.71g NaHCO3: 0.60g Background I know using a named lambda defeats the purpose but the function was so small I couldn't resist. This script is just for me which is why I hardcoded the value of the nootropic. I use single variables because I'm a chemist and that's how these equations are. If it was for others I wouldn't do these things. I usually write bash scripts to do things on the filesystem, I could do that with python but there's too much overhead, bash is better suited for that task. In doing so I write scripts (like the above) with a single use in mind. Which is why classes are hard for me to grasp. I've not yet come up with an idea big enough to use a class I think that's my problem, also because I don't practice much and online example are silly and don't apply to the real world. The above code is probably useless to use as a class, is that right? I need ideas on when a class would be required or how you'd even turn the above code into a class or if it's just a waste of time.
{ "domain": "codereview.stackexchange", "id": 44852, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python Class Idea, too much? If I compiled a bunch of acid bases and made a class for that? if you have a weak acid (vinegar) plus a strong base (sodium hydroxide) then you have to use logs and more complex equations, for a weak acid + weak base, (or strong acid + weak base and vice versa) you also have rate equations which will tell you how long these reactions will take. I could also add reaction feasibility stuff which will tell you if a reaction is possible. Other things like deriving the pressure and temp for a reaction to occur. Could I have a class for that or is it too much? For the curious because of the shambles that went on in the comments (now unavailable to see) All this info is really not needed that's why I said 'for the curious'. Neutralisation NaHCO3(aq) + phen-HCl(aq) -> phen(aq) + NaCl(aq) + H2O(l) + CO2(g) aq means aqueous (something dissolved in water) Aqueous bicarbonate salt + aqueous medicine salt -> aqueous medicine + water + gaseous carbon dioxide From the equation you can see that the reactants are 1:1. Simpler Neutralisation HCl(aq) + NaOH(aq) -> NaCl(aq) + H2O(l) You might notice most medicines are salts; med-hcl, med-phosphate etc, this is for long shelf life or because med might smell really bad besides other reasons. Moles (n) is just a ratio, The moles function, gives a decimal which you can multiply against the other compounds molar mass in order to find out how much equal mass it needs to react completely to make the products. Why you have to multiply n by molar mass Molar mass differs for each atoms/compounds (or say particles to group them all) this is because their weight varies; they have less or more protons, neutrons and electrons. Molar mass has the same number of particles for any atom/molecule/ compound per mol. molarMass = mass which has 6.023*10^23 particles. This is Avogadro's number or NA and is what 1 mol means, mol is different from moles. 1 mol = mass which contains NA particles. 1 moles = mass/molarMass = ratio
{ "domain": "codereview.stackexchange", "id": 44852, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python So you need to multiply n by NA to ensure equal numbers of particles react. Demystifying moles (n) Edited, I was sleepy and had nonsense before. x = £20 per 100g y = £12 per 50g z = what the price of y should be. Where x and y are the same products. You want to know the price per 1g. So you can know z. x[ratio] = 1 / 100 = 0.01 x[price per 1g] = x[ratio] * x[price] = £0.20 per 1g y[price per 1g] = x[ratio] * y[price] = £0.12 per 1g z[price per 50g] = y[price] * 50 = £6.00 per 50g That's all moles is and you probably do it to compare small vs large products prices to see which is cheaper/how much you save. Ionic and covalent bonding KHCO3 is an inorganic compound. K+ binds to bicarbonate or HCO3- creating a salt; potassium bicarbonate, this is an ionic bond (two opposite charges attracting). Salts have ionic bonds and break in water (excluding some crystals) giving ions; atoms/molecules with charges, this is why salt water is more conductive than water. More on ions Water exists in an equilibrium: H2O <-> H3O+ ~1 ~0
{ "domain": "codereview.stackexchange", "id": 44852, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python When electricity is passed through water, it ionises much more greatly, causing the position of equilibrium to greatly shift to the right. The bonding in KHCO3: K(+)(-O3-C-H) C is bonded covalently (the dashes -) to each of the oxygen atoms and hydrogen atom, this bond is strong, electrons are shared, and they are bound by the strong nuclear force and require high energy to ionise, they remain unchanged in water. This is the way salts work, and why they ionise in water. Take NaCl it's Na(+)Cl(-). You add water and it ionises to Na(+) + Cl(-). The free Na(+) is what allows you to taste salt. H2O2 represents Hydrogen Peroxide. When used as a variable name it doesn't have the same meaning as in chemistry. It is just a string and the underlying object is an integer. It doesn't have chemical properties. So the variables contain the molar mass of the compound. The only physical property I'm interested in is its molar mass which is an integer. You can calculate the mass for a reaction very easily, chemical properties have nothing to do with the calculation, only physical properties do like mass in this case. Example of 2:1 reaction H2O2(aq) -> 2H2O(l) + O2(g) If this is reversed, take the molar mass of both of the reactants then say for O2 you have has a mass of 10g: O2[n] = O2[mass] / O2[molarMass] H2O[mass required to completely react with O2] = O2[n] * (H2O[molarMass] * 2) That was all done without chemical properties, only physical properties. Might be obvious but to the fervent few well I hope this calms you, for the curious I hope you learned something. Conclusion I used to add about half a teaspoon of baking soda or potassium bicarbonate, this gave a salty or bitter taste respectively and was irritating to the throat. Using the calculated masses for the bases there is hardly a taste and no irritation.
{ "domain": "codereview.stackexchange", "id": 44852, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python Answer: I'll demonstrate two directions for your code. The first is a simplification and output addition - since the code is already so short, I believe that it could be made more legible with units baked into the variable names, so that you can follow along with unit arithmetic just by reading the names nearly as you would on paper. This changes the following: Remove decimal; you don't need it here. Add friendly names for compounds in comments. Consider using the Unicode point for subscript-2 and 3 in your output. Consider using milligrams instead, since they can show more accuracy with fewer characters in this case. Since clarity is of paramount importance in pharmacology, write out your two reactions in full. Don't bother making a constant for a newline. SI convention is to have a space between the quantity and the unit. More broadly: you're usually writing code on your own (which isn't the end of the world). Seeking a review is a great idea. Adding clear comments, variable names and output content is an important step to branching out so that you aren't the only person who understands your code. Having most of the context for your calculations in your head is fine until it isn't: when their complexity increases, when time passes and (like we all do) things are forgotten, or when you want to share this with someone else. Units without functions # Units g = 1 mg = 1e3 * g mol = 1 mmol = 1e3 * mol # Molar masses KHCO3_g_mol = 100.115 # Potassium bicarbonate NaHCO3_g_mol = 84.0066 # Sodium bicarbonate phenHCl_g_mol = 215.67 # Phenibut hydrochloride # Quantities for neutralization reactions phenHCl_g = 1.54 phenHCl_mol = phenHCl_g / phenHCl_g_mol KHCO3_mol = phenHCl_mol NaHCO3_mol = phenHCl_mol KHCO3_g = KHCO3_g_mol * KHCO3_mol NaHCO3_g = NaHCO3_g_mol * NaHCO3_mol
{ "domain": "codereview.stackexchange", "id": 44852, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python print(f' KHCO₃ + Phen-HCl → Phen + KCl + H₂O + CO₂') print(f'{KHCO3_mol * mmol/mol:6.3f} + {phenHCl_mol * mmol/mol:8.3f} (mmol)') print(f'{KHCO3_g * mg/g:6.1f} + {phenHCl_g * mg/g:8.0f} (mg)') print() print(f'NaHCO₃ + Phen-HCl → Phen + NaCl + H₂O + CO₂') print(f'{NaHCO3_mol * mmol/mol:6.3f} + {phenHCl_mol * mmol/mol:8.3f} (mmol)') print(f'{NaHCO3_g * mg/g:6.1f} + {phenHCl_g * mg/g:8.0f} (mg)') KHCO₃ + Phen-HCl → Phen + KCl + H₂O + CO₂ 7.141 + 7.141 (mmol) 714.9 + 1540 (mg) NaHCO₃ + Phen-HCl → Phen + NaCl + H₂O + CO₂ 7.141 + 7.141 (mmol) 599.9 + 1540 (mg) Units with functions # Units g = 1 mg = 1e3 * g mol = 1 mmol = 1e3 * mol # Molar masses KHCO3_g_mol = 100.115 # Potassium bicarbonate NaHCO3_g_mol = 84.0066 # Sodium bicarbonate phenHCl_g_mol = 215.67 # Phenibut hydrochloride # Quantities for neutralization reactions phenHCl_g = 1.54 phenHCl_mol = phenHCl_g / phenHCl_g_mol def show_neutralization(salt_name: str, salt_g_mol: float, chloride_name: str) -> None: salt_mol = phenHCl_mol salt_g = salt_mol * salt_g_mol print(f'{salt_name:>6} + Phen-HCl → Phen + {chloride_name} + H₂O + CO₂') print(f'{salt_mol * mmol/mol:6.3f} + {phenHCl_mol * mmol/mol:8.3f} (mmol)') print(f'{salt_g * mg/g:6.1f} + {phenHCl_g * mg/g:8.0f} (mg)') print() def main() -> None: show_neutralization(salt_name='KHCO₃', salt_g_mol=KHCO3_g_mol, chloride_name='KCl') show_neutralization(salt_name='NaHCO₃', salt_g_mol=NaHCO3_g_mol, chloride_name='NaCl') if __name__ == '__main__': main() KHCO₃ + Phen-HCl → Phen + KCl + H₂O + CO₂ 7.141 + 7.141 (mmol) 714.9 + 1540 (mg) NaHCO₃ + Phen-HCl → Phen + NaCl + H₂O + CO₂ 7.141 + 7.141 (mmol) 599.9 + 1540 (mg) Classes Make your classes immutable via NamedTuple. This demonstrates a simple two-class system for substance definitions and reactant instances. You could throw in a lot more complexity, such as Equation, but that's not really needed. from typing import NamedTuple
{ "domain": "codereview.stackexchange", "id": 44852, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python # Units g = 1 mg = 1e3 * g mol = 1 mmol = 1e3 * mol class Substance(NamedTuple): short_name: str long_name: str g_mol: float # molar mass def __str__(self) -> str: return self.short_name class Reactant(NamedTuple): substance: Substance mol: float @classmethod def from_mass(cls, substance: Substance, g: float) -> 'Reactant': return cls(substance, g/substance.g_mol) @property def g(self) -> float: # mass in grams return self.mol * self.substance.g_mol def __str__(self) -> str: return f'{self.substance}: {self.g * mg/g:.1f} mg' KHCO3 = Substance('KHCO₃', 'potassium bicarbonate', 100.115) NaHCO3 = Substance('NaHCO₃', 'sodium bicarbonate', 84.0066) PhenHCl = Substance('Phen-HCl', 'phenibut hydrochloride', 215.67) def main() -> None: phenhcl = Reactant.from_mass(PhenHCl, g=1.54) khco3 = Reactant(KHCO3, phenhcl.mol) nahco3 = Reactant(NaHCO3, phenhcl.mol) print('KHCO₃ + Phen-HCl → Phen + KCl + H₂O + CO₂') print(khco3) print(phenhcl) print() print('NaHCO₃ + Phen-HCl → Phen + NaCl + H₂O + CO₂') print(nahco3) print(phenhcl) if __name__ == '__main__': main() KHCO₃ + Phen-HCl → Phen + KCl + H₂O + CO₂ KHCO₃: 714.9 mg Phen-HCl: 1540.0 mg NaHCO₃ + Phen-HCl → Phen + NaCl + H₂O + CO₂ NaHCO₃: 599.9 mg Phen-HCl: 1540.0 mg
{ "domain": "codereview.stackexchange", "id": 44852, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
javascript, game, canvas Title: Snake game using Canvas API Question: Edit 2: For anyone interested, you can play the game at buggysnake.com Edit 1: I have typed up the code for making the body of the snake move. It's not perfect and there are small problems I need to fix. But I have updated the javascript code below to include that code. Background: I recently started learning Javascript about 3 weeks ago. About a week ago I learnt about the Canvas API. As for my first project, I decided to make a snake game using the Canvas API. As I am a beginner in both Javascript and the Canvas API, I am not sure if what I have typed up is good code. I would appreciate if someone could review it and provide some feedback regarding simplifying it and maybe generalising it to make the movements work with the entire body of the snake. As it is now, the only possible way I can think of moving the snake is by moving individual parts of it. There is still one piece missing in the code. That piece is the part where the body of the snake moves after the head has. I haven't been able to add that part in yet. There are a total of three files. The HTML, CSS and Javascript files. I have typed them up in that order. Just in case if anyone wants to run the game on their own computer. But the code in review is the Javascript code. index.html <!DOCTYPE html> <html lang="en-us"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Canvas</title> <script src="script.js" defer></script> <link href="style.css" rel="stylesheet"> </head> <body> <canvas class="myCanvas"> <p>Something for now</p> </canvas> </body> </html> style.css body { margin: 0; overflow: hidden; }
{ "domain": "codereview.stackexchange", "id": 44853, "lm_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, game, canvas", "url": null }
javascript, game, canvas style.css body { margin: 0; overflow: hidden; } script.js const canvas = document.querySelector(".myCanvas"); const html = document.querySelector("html"); const width = canvas.width = window.innerWidth; const height = canvas.height = window.innerHeight; const ctx = canvas.getContext("2d"); let scoreCounter = 0; let generalInstanceNumber = 0; let current_x; let current_y; //An array for our snake body. const snakes = []; //An array for the keys pressed. const keysPressed = [];
{ "domain": "codereview.stackexchange", "id": 44853, "lm_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, game, canvas", "url": null }
javascript, game, canvas //The constructor for our snake. function Snake(x, y,) { this.alreadyTurnedRight = true; this.alreadyTurnedLeft = true; this.alreadyTurnedUp = true; this.alreadyTurnedDown = true; this.x = x; this.y = y; this.velx = 0; this.vely = 0; this.position_x = 0; this.position_y = 0; this.instanceNumber; this.draw = function () { ctx.fillStyle = "green"; ctx.fillRect(this.x, this.y, 50, 50); } this.updateRight = function () { if (this.x >= width) { gameStarted = false; gameOver(); } else if (this.y === current_y) { this.velx = 0; this.velx += 10; this.x += this.velx; this.alreadyTurnedRight = false; this.alreadyTurnedLeft = true; this.alreadyTurnedUp = true; this.alreadyTurnedDown = true; } else { if (keysPressed[keysPressed.length - 2] === "ArrowUp" && this.alreadyTurnedRight === true) { this.y -= 10; } if (keysPressed[keysPressed.length -2] === "ArrowDown" && this.alreadyTurnedRight === true) { this.y += 10; } } } this.updateLeft = function () { if (this.x <= 0) { gameStarted = false; gameOver(); } else if (this.y === current_y) { this.velx = 0; this.velx -= 10; this.x += this.velx; this.alreadyTurnedRight = true; this.alreadyTurnedLeft = false; this.alreadyTurnedUp = true; this.alreadyTurnedDown = true; } else { if (keysPressed[keysPressed.length - 2] === "ArrowUp" && this.alreadyTurnedLeft === true) { this.y -= 10; } if (keysPressed[keysPressed.length - 2] === "ArrowDown" && this.alreadyTurnedLeft === true) { this.y += 10; } }
{ "domain": "codereview.stackexchange", "id": 44853, "lm_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, game, canvas", "url": null }
javascript, game, canvas this.y += 10; } } } this.updateUp = function () { if (this.y <= 0) { gameStarted = false; gameOver(); } else if (this.x === current_x) { this.vely = 0; this.vely -= 10; this.y += this.vely; this.alreadyTurnedRight = true; this.alreadyTurnedLeft = true; this.alreadyTurnedUp = false; this.alreadyTurnedDown = true; } else { if (keysPressed[keysPressed.length - 2] === "ArrowRight" && this.alreadyTurnedUp === true) { this.x += 10; } if (keysPressed[keysPressed.length - 2] === "ArrowLeft" && this.alreadyTurnedUp === true) { this.x -= 10; } } } this.updateDown = function () { if (this.y >= height) { gameStarted = false; gameOver(); } else if (this.x === current_x) { this.vely = 0; this.vely += 10; this.y += this.vely; this.alreadyTurnedRight = true; this.alreadyTurnedLeft = true; this.alreadyTurnedUp = true; this.alreadyTurnedDown = false; } else { if (keysPressed[keysPressed.length - 2] === "ArrowRight" && this.alreadyTurnedDown === true) { this.x += 10; } if (keysPressed[keysPressed.length - 2] === "ArrowLeft" && this.alreadyTurnedDown === true) { this.x -= 10; } } } }
{ "domain": "codereview.stackexchange", "id": 44853, "lm_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, game, canvas", "url": null }
javascript, game, canvas //Function for clearing the canvas for a new drawing. function updateCanvas() { ctx.fillStyle = "black"; ctx.fillRect(0, 0, width, height); } //Function for Game Over. function gameOver() { rPressed = true; updateCanvas(); ctx.fillStyle = "red"; ctx.font = "70px helvetica"; ctx.fillText("Game Over", width/2 - 200, height/2); ctx.fillStyle = "yellow"; ctx.font = "45px helvetica"; ctx.fillText("Press r to restart the game", width/2 - 280, height/2 + 100); } //Function for drawing the score. function score() { ctx.fillStyle = "blue"; ctx.font = "45px helvetica"; ctx.fillText(`Score: ${scoreCounter}`, 10, 50); } //Code for setting up the starting screen. ctx.fillStyle = "black"; ctx.fillRect(0, 0, width, height); ctx.fillStyle = "Green"; ctx.font = "70px helvetica"; ctx.fillText("Snake Game", width/2 - 220, height/2); ctx.fillStyle = "yellow"; ctx.font = "45px helvetica"; ctx.fillText("Press s to start the game", width/2 - 260, height/2 + 100); let x = width/2; let y = height/2; const snake = new Snake(x, y); snake.instanceNumber = 0; snakes.push(snake); let apple_x = randomNumber(0, width); let apple_y = randomNumber(0, height); const apple = new Apple(apple_x, apple_y); //Function for starting the game. let gameStarted = false; addEventListener("keydown", setUpScreen); function setUpScreen(event) { if (event.key === "s") { updateCanvas(); snake.draw(); apple.draw(); score(); gameStarted = true; removeEventListener("keydown", setUpScreen); } } //Code for restarting the game. let rPressed = false; addEventListener("keydown", restartGame); function restartGame(event) { if (event.key === "r" && rPressed === true) { location.reload(); } } //Code for performing animations based on user input. let rightKeyPressed = true; let leftKeyPressed = true; let upKeyPressed = true; let downKeyPressed = true;
{ "domain": "codereview.stackexchange", "id": 44853, "lm_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, game, canvas", "url": null }
javascript, game, canvas addEventListener("keydown", moveSnake); function moveSnake(event) { if (event.key === "ArrowRight" && gameStarted === true && rightKeyPressed === true) { keysPressed.push("ArrowRight"); current_x = snake.x; current_y = snake.y; rightKeyPressed = false; leftKeyPressed = true; upKeyPressed = true; downKeyPressed = true; cancelAnimationFrame(requestLoopLeft); cancelAnimationFrame(requestLoopUp); cancelAnimationFrame(requestLoopDown); loopRight(); } if (event.key === "ArrowLeft" && gameStarted === true && leftKeyPressed === true) { keysPressed.push("ArrowLeft"); current_x = snake.x; current_y = snake.y; rightKeyPressed = true; leftKeyPressed = false; upKeyPressed = true; downKeyPressed = true; cancelAnimationFrame(requestLoopRight); cancelAnimationFrame(requestLoopUp); cancelAnimationFrame(requestLoopDown); loopLeft(); } if (event.key === "ArrowUp" && gameStarted === true && upKeyPressed === true) { keysPressed.push("ArrowUp"); current_x = snake.x; current_y = snake.y; rightKeyPressed = true; leftKeyPressed = true; upKeyPressed = false; downKeyPressed = true; cancelAnimationFrame(requestLoopLeft); cancelAnimationFrame(requestLoopRight); cancelAnimationFrame(requestLoopDown); loopUp(); } if (event.key === "ArrowDown" && gameStarted === true && downKeyPressed === true) { keysPressed.push("ArrowDown"); current_x = snake.x; current_y = snake.y; rightKeyPressed = true; leftKeyPressed = true; upKeyPressed = true; downKeyPressed = false; cancelAnimationFrame(requestLoopLeft); cancelAnimationFrame(requestLoopRight); cancelAnimationFrame(requestLoopUp); loopDown(); } }
{ "domain": "codereview.stackexchange", "id": 44853, "lm_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, game, canvas", "url": null }
javascript, game, canvas //Functions for animating the direction of the snake. let requestLoopRight; function loopRight(number) { updateCanvas(); score(); apple.draw(); for (const element of snakes) { element.draw(); element.updateRight(); } apple.update(); //console.log(`from loopRight ${snake.x}`); requestLoopRight = requestAnimationFrame(loopRight); } let requestLoopLeft; function loopLeft() { updateCanvas(); score(); apple.draw(); for (const element of snakes) { element.draw(); element.updateLeft(); } apple.update(); //console.log(`From loopLeft ${snake.x}`); requestLoopLeft = requestAnimationFrame(loopLeft); } let requestLoopUp; function loopUp(name) { updateCanvas(); score(); apple.draw(); for (const element of snakes) { element.draw(); element.updateUp(); } apple.update(); //console.log(`From loopUp ${snake.y}`); requestLoopUp = requestAnimationFrame(loopUp); } let requestLoopDown; function loopDown() { updateCanvas(); score(); apple.draw(); for (const element of snakes) { element.draw(); element.updateDown(); } apple.update(); //console.log(`From loopDown ${snake.y}`); requestLoopDown = requestAnimationFrame(loopDown); } //Function for generating a random integer. function randomNumber(min, max) { return Math.floor(min + Math.random()*(max - min)); }
{ "domain": "codereview.stackexchange", "id": 44853, "lm_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, game, canvas", "url": null }
javascript, game, canvas //The constructor for our apple. function Apple(x, y) { this.x = x; this.y = y; this.draw = function () { ctx.fillStyle = "red"; ctx.beginPath(); ctx.arc(this.x, this.y, 28, 0, 2*Math.PI, false); ctx.fill(); } //This function includes the code for collision detection and adding a square to the snakes body. this.update = function () { let x = 0; let y = 0; if (Math.sqrt(((snake.x + 25) - this.x)*((snake.x + 25) - this.x) + ((snake.y + 25) - this.y)*((snake.y + 25) - this.y)) <= 28) { this.x = randomNumber(0, width); this.y = randomNumber(0, height); scoreCounter += 1; generalInstanceNumber += 1; if (rightKeyPressed === false) { let arrayLength = snakes.length - 1; x = snakes[arrayLength].x - 50; y = snakes[arrayLength].y; const newSnake = new Snake(x, y); newSnake.instanceNumber = generalInstanceNumber; snakes.push(newSnake); } if (leftKeyPressed === false) { let arrayLength = snakes.length - 1; x = snakes[arrayLength].x + 50; y = snakes[arrayLength].y; const newSnake = new Snake(x, y); newSnake.instanceNumber = generalInstanceNumber; snakes.push(newSnake); } if (upKeyPressed === false) { let arrayLength = snakes.length - 1; x = snakes[arrayLength].x; y = snakes[arrayLength].y + 50; const newSnake = new Snake(x, y); newSnake.instanceNumber = generalInstanceNumber; snakes.push(newSnake); } if (downKeyPressed === false) { let arrayLength = snakes.length - 1; x = snakes[arrayLength].x; y = snakes[arrayLength].y - 50;
{ "domain": "codereview.stackexchange", "id": 44853, "lm_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, game, canvas", "url": null }
javascript, game, canvas x = snakes[arrayLength].x; y = snakes[arrayLength].y - 50; const newSnake = new Snake(x, y); newSnake.instanceNumber = generalInstanceNumber; snakes.push(newSnake); } } } }
{ "domain": "codereview.stackexchange", "id": 44853, "lm_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, game, canvas", "url": null }
javascript, game, canvas Answer: Old school The code looks very old school. No use of modern JS syntax (could be 8 year old code). The comments in your code that contains pronoun "our" gives away the fact that you have copied an example, alway check the date of example code, and always use the most recent examples (within a year). Stay up to date, especially when you are learning. Writing a snake game A snake game is has deceptively simple code complexity, however as the length of the snakes body grows the amount of work needed to update each frame of the animation quickly becomes overwhelming for the CPU. Looking at your code the runtime complexity is \$O(n^2)\$ where \$n\$ is the number of snake body parts plus the number of apples. At worst, \$n\$ can be the number of playfield cells. The naïve design starts with the snakes head and an apple, adding moving searchable snake segments, and searchable apples as the game progresses. The better design considers a playfield (grid) of snake body parts and apples. Only the location of the snakes head and tail are tracked. The best time complexity for a snake game is \$O(1)\$ (generally all classic games are time \$O(1)\$ and space \$O(n)\$) Keep it D.R.Y. D.R.Y. (Don't Repeat Yourself) Your handling of directions is very repetitive. There is no need. Think of the 4 direction moves, as one move in a given direction. Now you have one function to move, rather than 4 functions to move up, left, right, down. Example const Vec2 = (x = 0, y = 0) => ({x, y}); const directions = { up: Vec2( 0, -1), right: Vec2( 1, 0), down: Vec2( 0, 1), left: Vec2(-1, 0) }; const keys = ((...keyNames) => { const keys = {}; for (const keyName of keyNames) { keys[keyName] = false } const keyEvents = e => { keys[e.key] !== undefined && (keys[e.key] = e.type === "keydown"); } addEventListener("keydown", keyEvents); addEventListener("keyup", keyEvents); return keys;
{ "domain": "codereview.stackexchange", "id": 44853, "lm_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, game, canvas", "url": null }
javascript, game, canvas addEventListener("keyup", keyEvents); return keys; })("ArrowUp", "ArrowRight", "ArrowDown", "ArrowLeft", "s", "r"); var gameOver = false; function Snake(x, y) { const dirs = directions; // local alias dirs const pos = Vec2(x, y); var currentDir = Vec2(); var velocity = 10; return Object.freeze({ draw() { ctx.rect(pos.x, pos.y, 50, 50); }, isGameOver() { if (pos.x >= width || pos.x < 0 || pos.y < 0 || pos.y >= height) { gameOver = true; } }, move() { if (keys.ArrowUp) { currentDir !== dirs.down && (currentDir = dirs.up); } else if (keys.ArrowRight) { currentDir !== dirs.left && (currentDir = dirs.right); } else if (keys.ArrowDown) { currentDir !== dirs.up && (currentDir = dirs.down); } else if (keys.ArrowLeft) { currentDir !== dirs.right && (currentDir = dirs.left); } pos.x += currentDir.x * velocity; pos.y += currentDir.y * velocity; isGameOver(); } }); }
{ "domain": "codereview.stackexchange", "id": 44853, "lm_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, game, canvas", "url": null }
javascript, game, canvas Poor event use Your use of events is way to complex for such a simple game. Imagine as the game gets more complex, following what is going on, testing and debugging would get very hard. Always aim to minimise the number of listeners waiting for events. The more events there are the more you obfuscate logic flow!!! I suspect you have already lost any idea of what is happening as it is evident that you are incorrectly requesting and canceling animation frames. Parts of your snake will simply stop moving. Generally animations and games use one game loop. eg function mainLoop(time) { if (gameOver) { showGameOver(); } else { playGame(); } requestAnimationFrame(mainLoop); } Too much this Avoid the token this.. JavaScripts' this was not thought out (it's like a with without a name). Reading only part of the source code you can not know for sure what this refers to. this makes code harder to read and much noisier. Use closure to create private variables. Use named objects and reference the name rather than this Comments can be evil Comments can give the reader (and you when you come back months or years later to read the code) the wrong idea of the author's intent. Example from your code // Function for generating a random integer. function randomNumber(min, max) { return Math.floor(min + Math.random()*(max - min)); } A number in javascript is not an integer, your intent is confused... Did you want an integer or a number? Is the function a bug and the comment a copy paste remnant What is your intent the function name or the comment? The only way to know is to find a use case within your code, thus the comment makes the code much harder to read and understand, the antithesis of what comment are there for. The better option is to avoid comments and write code that is easily understood. const randomInt = (min, max) => Math.floor(min + Math.random() * (max - min));
{ "domain": "codereview.stackexchange", "id": 44853, "lm_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, game, canvas", "url": null }
javascript, game, canvas What is goin on? I found some very strange bits of code, you assign value 0 and then add 10 velx = 0; velx += 10; Why not just assign 10 velx = 10;
{ "domain": "codereview.stackexchange", "id": 44853, "lm_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, game, canvas", "url": null }
c++, matrix, complexity, binary-search Title: Binary search of 2D matrix Question: I have written code as below: bool binary_search(const std::vector<int>& v, const int& target) { int left = 0, right = v.size() - 1; while (left <= right) { int mid = left + (right - left) / 2; if (v[mid] == target) return true; if (target > v[mid]) left = mid + 1; else right = mid - 1; } return false; } bool searchMatrix(std::vector<std::vector<int>>& matrix, int target) { const int n = matrix.size(); for (int i = 0; i < n; i++) { if (target <= matrix[i][matrix[i].size() - 1]) return binary_search(matrix[i], target); } return false; } It returns true if the target is found in matrix, and false when is not present. The matrix has following properties: Each row is sorted in non-decreasing order. The first integer of each row is greater than the last integer of the previous row. Due to these properties, the binary_search will be invoked only once. The task was to create O(log(mn)) algorithm. But I'm pretty sure that this is O(n + log m). So I'm looking to improve its computational complexity. Answer: You clearly need to enable more compiler warnings. For example, we want to know about the dangerous conversion in int right = v.size() - 1; Since v.size() returns a std::size_t, this is almost certainly a narrowing conversion, and may even give a negative value in right. Your binary_search() function could be completely eliminated by using std::binary_search() instead. Don't reinvent wheels! The linear search of rows (for (int i = 0; i < n; i++)) would be simpler using a range-based for. But we don't want that - we should be using binary search to find the required row. We should be passing a reference to const vector into searchMatrix(), since we don't intend to modify its values.
{ "domain": "codereview.stackexchange", "id": 44854, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, matrix, complexity, binary-search", "url": null }
python, performance Title: Goldbach's conjecture algorithm Question: I did a Goldbach's Conjecture exercise and got it to work. It's pretty slow though and I was wondering how I could optimize it. number = int(input("Enter your number >> ")) print("\nCalculating...") if number % 2 == 0: #Only even numbers primes = primenums(number) #returns all prime numbers <= input number addend1 = primes[0] addend2 = primes[0] while addend1 + addend2 != number: if primes[-1] == addend2: addend2 = primes[primes.index(addend1) + 1] addend1 = primes[primes.index(addend1) + 1] else: addend2 = primes[primes.index(addend2) + 1] Right now, up to 10,000 the algorithm is pretty fast, but at 100,000 it takes about 3 seconds to finish. Is that just how it is or could I make it faster? Answer: One thing that makes your code slow is your repeated calls to primes.index. Each of these calls needs to linearly scan primes until it finds the value you are looking for, making this \$\mathcal{O}(n)\$. This is especially bad in the first if case since you do this twice with exactly the same argument. Instead just keep the index around in addition to the number: def goldbach_keep_index(number): if number % 2 == 1: #Only even numbers raise ValueError("Goldbach conjecture is only defined for even numbers") primes = primenums(number) #returns all prime numbers <= input number i, j = 0, 0 addend1 = primes[i] addend2 = primes[j] while addend1 + addend2 != number: if addend2 == primes[-1]: i = j = i + 1 addend2 = primes[i] addend1 = primes[i] else: j += 1 addend2 = primes[j] return addend1, addend2
{ "domain": "codereview.stackexchange", "id": 44855, "lm_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", "url": null }
python, performance Note that I made this a function, so you can reuse it. Your main calling code could look like this: if __name__ == "__main__": number = int(input("Enter your number >> ")) p1, p2 = goldbach_keep_index(number) print(f"{p1} + {p2} = {number}") However, what you are really doing is taking all combinations of prime numbers, without repeating yourself. So just use itertools.combinations_with_replacement: from itertools import combinations_with_replacement def goldbach_combinations(number): if number % 2 == 0: raise ValueError("Goldbach conjecture is only defined for even numbers") primes = primenums(number) for addend1, addend2 in combinations_with_replacement(primes, 2): if addend1 + addend2 == number: return addend1, addend2 raise Exception(f"Found a counter-example to the Goldbach conjecture: {number}") In this case primes does not even need to be a list, it can just be a generator. If you instead make primes a set, you can easily implement the idea suggested by @Josiah in their answer by just checking if number - p is in primes: def goldbach_set(number): if number % 2 == 0: #Only even numbers raise ValueError("Goldbach conjecture is only defined for even numbers") primes = set(primenums(number)) #returns all prime numbers <= input number for p in primes: k = number - p if k in primes: return p, k raise Exception(f"Found a counter-example to the Goldbach conjecture: {number}") And now some timing comparisons, where goldbach is your code put into a function: def goldbach(number): if number % 2 == 0: #Only even numbers raise ValueError("Goldbach conjecture is only defined for even numbers") primes = primenums(number) #returns all prime numbers <= input number addend1 = primes[0] addend2 = primes[0]
{ "domain": "codereview.stackexchange", "id": 44855, "lm_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", "url": null }
python, performance while addend1 + addend2 != number: if primes[-1] == addend2: addend2 = primes[primes.index(addend1) + 1] addend1 = primes[primes.index(addend1) + 1] else: addend2 = primes[primes.index(addend2) + 1] return addend1, addend2 And primenums is a simple sieve: def prime_sieve(limit): prime = [True] * limit prime[0] = prime[1] = False for i, is_prime in enumerate(prime): if is_prime: yield i for n in range(i * i, limit, i): prime[n] = False def primenums(limit): return list(prime_sieve(limit)) And when pulling the generation of the primes outside of the function (and calculating them up to the largest number in the plot): Of course the first three functions are vastly slower than the set because they need to go through more combinations now. However, all functions are then constant time, so the increase in time comes solely from the fact that you have to consider more primes.
{ "domain": "codereview.stackexchange", "id": 44855, "lm_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", "url": null }
c++, object-oriented, game, design-patterns, event-handling Title: Event System using C++ Question: I am excited to share that I have developed an event system in C++. I have always been passionate about programming and have long aspired to create a low-level game engine solely using C++, OpenGL, and GLFW. This project has been a personal challenge and really fun too. To begin with, I created my own Event System. The functioning of this system involves pushing events to the event queue. The event manager then publishes the events from the queue to the listeners. Each listener checks if the event is of the type it is interested in, and if so, it handles the event. Once an event is handled, it is removed from the queue. I am open to any feedback or suggestions regarding the design or any other aspect of the system. Your input would be greatly appreciated. In addition to any general feedback, I have a few specific questions I'd like to address: 1. In the Event.h file, can you explain the justification for using macros? 2. Although I am aware that .cpp files should be used, there are several objects in this codebase that either are or contain templated methods. Can you elaborate on how this should be handled? 3. Considering the principles of Object-Oriented programming, could you evaluate whether this system is well-written? For those who are curious, I have also included the source code below: Event.h #include <string> #define EVENT_TYPE_FUNCTION(type) \ static const EventType getStaticType() { return EventType::##type; } \ virtual const EventType getType() const override { return EventType::##type; } \ virtual const std::string getTypeName() const override { return #type; }
{ "domain": "codereview.stackexchange", "id": 44856, "lm_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++, object-oriented, game, design-patterns, event-handling", "url": null }
c++, object-oriented, game, design-patterns, event-handling #define EVENT_CATEGORY_FUNCTION(category) \ virtual ~category##Event() override = default; \ virtual const EventCategory getCategory() const override { return EventCategory::##category; } \ virtual const EventType getType() const override{ return EventType::None; } enum class EventCategory { None, Input, Window, Mouse, Keyboard, Application, }; enum class EventType { None, WindowResize, WindowLostFocus, WindowGainedFocus, WindowClose, WindowCursorEnter, WindowCursorLeave, MouseMove, MousePress, MouseRelease, MouseScroll, KeyboardPress, KeyboardRepeat, KeyboardRelease, CharPress, }; class Event { public: virtual ~Event() = default; bool isHandeled() const { return handeled; } bool handle() { handeled = true; } virtual const EventCategory getCategory() const = 0; virtual const EventType getType() const = 0; virtual const std::string getTypeName() const = 0; private: bool handeled = false; }; class NoneEvent : public Event { const EventCategory getCategory() const override { return EventCategory::None; } EVENT_TYPE_FUNCTION(None) }; Keyboardevent.h #include "Event.h" #include <Stdint.h> class KeyboardEvent : public Event { protected: KeyboardEvent(int keyCode, int scancode, int mods) : keyCode(keyCode), scancode(scancode), mods(mods) { } public: int getKeyCode() const { return keyCode; } int getScanCode() const { return scancode; } int getMods() const { return mods; } EVENT_CATEGORY_FUNCTION(Keyboard) private: int keyCode; int scancode; int mods; }; class KeyboardPressEvent : public KeyboardEvent { public: KeyboardPressEvent(const int keyCode, const int scancode, const int mods) : KeyboardEvent(keyCode, scancode, mods) { }
{ "domain": "codereview.stackexchange", "id": 44856, "lm_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++, object-oriented, game, design-patterns, event-handling", "url": null }
c++, object-oriented, game, design-patterns, event-handling EVENT_TYPE_FUNCTION(KeyboardPress) }; class KeyboardRepeatEvent : public KeyboardEvent { KeyboardRepeatEvent(const int keyCode, const int scancode, const int mods) : KeyboardEvent(keyCode, scancode, mods) { } EVENT_TYPE_FUNCTION(KeyboardRepeat) }; class KeyboardReleaseEvent : public KeyboardEvent { public: KeyboardReleaseEvent(const int keyCode, const int scancode, const int mods) : KeyboardEvent(keyCode, scancode, mods) { } EVENT_TYPE_FUNCTION(KeyboardRelease) }; class CharPressEvent : public Event { public: CharPressEvent(const int codePoint) : codePoint(codePoint) { } const int getCodePoint() const { return codePoint; } const EventCategory getCategory() const override { return EventCategory::Keyboard; } EVENT_TYPE_FUNCTION(CharPress) private: const int codePoint; }; MouseEvent.h #pragma once #include "Event.h" class MouseEvent : public Event { public: EVENT_CATEGORY_FUNCTION(Mouse) }; // ===================== MOTION UPCOMING ============================== class MouseMotionEvent : public MouseEvent { protected: MouseMotionEvent(const double mouseX, const double mouseY) : mouseX(mouseX), mouseY(mouseY) { } public: const double getMouseX() const { return mouseX; } const double getMouseY() const { return mouseY; } private: const double mouseX, mouseY; }; class MouseMoveEvent : public MouseMotionEvent { public: MouseMoveEvent(const double mouseX, const double mouseY) : MouseMotionEvent(mouseX, mouseY) { } EVENT_TYPE_FUNCTION(MouseMove) }; class MouseScrollEvent : public MouseMotionEvent { public: MouseScrollEvent(const double mouseX, const double mouseY) : MouseMotionEvent(mouseX, mouseY) { } EVENT_TYPE_FUNCTION(MouseScroll) }; // ===================== BUTTON UPCOMING ==============================
{ "domain": "codereview.stackexchange", "id": 44856, "lm_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++, object-oriented, game, design-patterns, event-handling", "url": null }
c++, object-oriented, game, design-patterns, event-handling // ===================== BUTTON UPCOMING ============================== class MouseButtonEvent : public MouseEvent { protected: MouseButtonEvent(const int button, const int mods) : button(button), mods(mods) { } public: const int getButton() const { return button; } const int getMods() const { return mods; } private: const int button, mods; }; class MousePressEvent : public MouseButtonEvent { public: MousePressEvent(const int button, const int mods) : MouseButtonEvent(button, mods) { } EVENT_TYPE_FUNCTION(MousePress) }; class MouseReleaseEvent : public MouseButtonEvent { public: MouseReleaseEvent(const int button, const int mods) : MouseButtonEvent(button, mods) { } EVENT_TYPE_FUNCTION(MouseRelease) }; WindowEvent.h #pragma once #include "Event.h" class WindowEvent : public Event { public: EVENT_CATEGORY_FUNCTION(Window) }; class WindowResizeEvent : public WindowEvent { public: WindowResizeEvent(const int width, const int height) : width(width), height(height) { } const int getWidth() const { return width; } const int getHeight() const { return height; } EVENT_TYPE_FUNCTION(WindowResize) private: const int width, height; }; class WindowCloseEvent : public WindowEvent { public: EVENT_TYPE_FUNCTION(WindowClose) }; class WindowLostFocusEvent : public WindowEvent { public: EVENT_TYPE_FUNCTION(WindowLostFocus) }; class WindowGainedFocusEvent : public WindowEvent { public: EVENT_TYPE_FUNCTION(WindowGainedFocus) }; class WindowCursorEnterEvent : public WindowEvent { public: EVENT_TYPE_FUNCTION(WindowCursorEnter) }; class WindowCursorLeaveEvent : public WindowEvent { public: EVENT_TYPE_FUNCTION(WindowCursorLeave) }; EventListener.h #pragma once #include <functional> #include "MouseEvent.h" #include "KeyboardEvent.h" #include "WindowEvent.h"
{ "domain": "codereview.stackexchange", "id": 44856, "lm_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++, object-oriented, game, design-patterns, event-handling", "url": null }
c++, object-oriented, game, design-patterns, event-handling #include <functional> #include "MouseEvent.h" #include "KeyboardEvent.h" #include "WindowEvent.h" class BaseEventListener { public: virtual ~BaseEventListener() = default; virtual const void dispatchEvent(const std::shared_ptr<Event>&) const = 0; virtual bool isEventType(const std::shared_ptr<Event>& event) const = 0; virtual const int getID() const = 0; }; template<typename EventType> class EventListener : public BaseEventListener { public: using EventCallBackFn = std::function<void(const std::shared_ptr<EventType>&)>; explicit EventListener(const EventCallBackFn& callBack, const int id) : callBack(callBack), id(id) { } const void dispatchEvent(const std::shared_ptr<Event>& event) const override { callBack(std::static_pointer_cast<EventType>(event)); } bool isEventType(const std::shared_ptr<Event>& event) const override { return std::dynamic_pointer_cast<EventType>(event) != nullptr; } const int getID() const override { return id; } private: const EventCallBackFn callBack; const int id; }; EventListenerRegister.h #pragma once #include <vector> #include <memory> #include <algorithm> #include "EventListener.h" class EventListenerRegister { public: using ListenerList = std::vector<std::unique_ptr<BaseEventListener>>; template<typename EventType> int registerListenerFor(const typename EventListener<EventType>::EventCallBackFn& callBack) { static int listenerID = 0; std::unique_ptr<BaseEventListener> listener = std::make_unique<EventListener<EventType>>(callBack, listenerID); listeners.push_back(std::move(listener)); return listenerID++; }
{ "domain": "codereview.stackexchange", "id": 44856, "lm_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++, object-oriented, game, design-patterns, event-handling", "url": null }
c++, object-oriented, game, design-patterns, event-handling return listenerID++; } void unregisterListener(const int listenerID) { listeners.erase( std::remove_if(listeners.begin(), listeners.end(), [listenerID](const auto& listener) { return listenerID == listener->getID(); }), listeners.end() ); } ListenerList::iterator begin() { return listeners.begin(); } ListenerList::const_iterator begin() const { return listeners.begin(); } ListenerList::iterator end() { return listeners.end(); } ListenerList::const_iterator end() const { return listeners.end(); } private: ListenerList listeners; }; EventQueue.h #pragma once #include <queue> #include <memory> #include "MouseEvent.h" #include "KeyboardEvent.h" #include "WindowEvent.h" class EventQueue { public: void push(const std::shared_ptr<Event>& event) { eventQueue.push(event); } std::shared_ptr<Event> pop() { if (eventQueue.empty()) return nullptr; std::shared_ptr<Event> event = std::move(eventQueue.front()); eventQueue.pop(); return event; } bool isEmpty() const { return eventQueue.empty(); } private: std::queue<std::shared_ptr<Event>> eventQueue; }; EventBus.h #pragma once #include <memory> #include "EventListenerRegister.h" #include "EventQueue.h" class EventBus { public: template<typename EventType> int registerListenerFor(const typename EventListener<EventType>::EventCallBackFn& callBack) { return listeners.registerListenerFor<EventType>(callBack); } void unregisterListener(const int listenerID) { listeners.unregisterListener(listenerID); }
{ "domain": "codereview.stackexchange", "id": 44856, "lm_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++, object-oriented, game, design-patterns, event-handling", "url": null }
c++, object-oriented, game, design-patterns, event-handling void publishEvent(EventQueue& eventQueue) const { while(const auto& event = eventQueue.pop()) { for (const auto& listener : listeners) { if (listener->isEventType(event)) listener->dispatchEvent(event); if (event->isHandeled()) break; } } } private: EventListenerRegister listeners; }; EventManager.h #pragma once #include "EventBus.h" #include "EventQueue.h" class EventManager { public: template<typename EventType> int registerListenerFor(const typename EventListener<EventType>::EventCallBackFn& callBack) { return eventBus.registerListenerFor<EventType>(callBack); } void unregisterListener(const int listenerID) { eventBus.unregisterListener(listenerID); } void pushEvent(const std::shared_ptr<Event>& event) { eventQueue.push(event); } void publishEvents() { eventBus.publishEvent(eventQueue); } private: EventBus eventBus; EventQueue eventQueue; }; Answer: Avoid macros There are many issues with macros, the general advice is to avoid them where possible. Let's look at EVENT_TYPE_FUNCTION(): it's there to add a few member functions to query the event type. First, let's try to avoid adding three functions, and reduce it to one, that just returns the type. Then we can avoid a macro and just write: class NoneEvent: public Event { EventCategory getCategory() const override { return EventCategory::None; } EventType getType() const override { return EventType::None; } };
{ "domain": "codereview.stackexchange", "id": 44856, "lm_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++, object-oriented, game, design-patterns, event-handling", "url": null }
c++, object-oriented, game, design-patterns, event-handling Note how it is similar to the definition of getCategory(). So how do we get getStaticType() and getTypeName()? First, I would remove getStaticType() completely. It is unsafe and/or unnecessary: if you allow further inheritance from types that already have a getStaticType() member function, it will give the wrong results: class MouseDoubleClickEvent: public MousePressEvent { … EVENT_TYPE_FUNCTION(MouseDoubleClick); }; MousePressEvent* event = new MouseDoubleCLickEvent(…); EventType type = event.getStaticType(); // MousePress instead of MouseDoubleClick If you don't want to allow further inheritance (you should use the final keyword for that), then I see little reason to have a getStaticType() member function; only the most derived classes will have that member function, so you can only call it if you already have a pointer-to-most-derived-class, and then you already know the type. For getTypeName() you can have the base class Event get the derived class's type and convert it to a name, if you have some way to map EventTypes to strings: static std::map<EventType, sd::string> eventNames = { {EventType::None, "None"}, … }; class Event { … std::string getTypeName() const { return eventNames[getType()]; } }; There are other ways to handle this. Instead of a getType() you could have a getDescription() virtual member function that returns both an EventType and a std::string, and have non-virtual member functions getType() and getTypeName() in class Event that call getDescription() and return either the type enum or the string. Then in derived classes you'd write something like: struct EventDescription { EventType type; std::string name; }; class NoneEvent: public Event { EventDescription getDescription() const override { return {EventType::None, "None"}; } };
{ "domain": "codereview.stackexchange", "id": 44856, "lm_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++, object-oriented, game, design-patterns, event-handling", "url": null }
c++, object-oriented, game, design-patterns, event-handling Another possibility is to use a helper template class: template<EventType T> class NamedEvent: public Event { EventType getType() const override { return T; } std::string getTypeName() const override { return eventNames[T]; } }; class NoneEvent: public NamedEvent<EventType::None> { }; Prefer std::unique_ptr over std::shared_ptr You use std::shared_ptr in your code, but I don't think you actually need shared ownership semantics. Consider writing the event queue like so: class EventQueue { public: void push(std::unique_ptr<Event> event) { eventQueue.push(std::move(event)); } std::unique_ptr<Event> pop() { if (eventQueue.empty() return nullptr; std::unique_ptr<Event> event = std::move(eventQueue.front()); eventQueue.pop(); return event; } … private: std::queue<std::unique_ptr<Event> event; }; Note how the argument to push() is passed by value. The caller thus has to std::move() an existing std::unique_ptr<Event> as well, which makes the transfer of ownership explicit. Note that if you dispatch an event to multiple listeners, then you don't give the listeners a smart pointer to the event, but instead just give them a const reference to the Event itself. This means they don't get (shared) ownership, they just get to borrow the event for the duration of the callback: template<typename EventType> class EventListener : public BaseEventListener { public: using EventCallBackFn = std::function<void(const EventType&)>; … void dispatchEvent(const Event& event) const override { callBack(static_cast<const EventType&>(event)); } … }
{ "domain": "codereview.stackexchange", "id": 44856, "lm_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++, object-oriented, game, design-patterns, event-handling", "url": null }
c++, object-oriented, game, design-patterns, event-handling Listener IDs The system you have for listener IDs will probably work fine in practice if you have only a limited number of listeners subscribed. However, consider that if you regularly subscribe new listeners, listenerID might wrap around and cause problems. I would also avoid returning the listener ID as an int. Instead, create a class ListenerID with a private member variable holding the ID number, to which only EventListenerRegister has access. That makes it easier to change the ID type later, and also adds some type safety: consider that with implicit conversions, one might accidentily store the ID in a short or char. Make it easier to push events Currently you have to create a std::shared_ptr<Event> before you can pass it to pushEvent(). You could simplify it by writing something like: class EventManager { … template<typename T, typename... Args> requires std::derived_from<T, Event> // C++20 void pushEvent(Args&&... args) { eventQueue.push(std::make_unique<T>(std::forward<Args>(args)...)); } … } This allows you to push an event like so: EventManager eventManager; … eventManager.pushEvent<MouseMoveEvent>(1, 2); Unnecessary use of const You have lots of functions that return const values. That makes no sense; the caller can just copy the return value into a non-const variable. It only makes sense to return something const if it is a pointer or reference. I even see some const void, which makes no sense at all. You can use more auto You can avoid some repetition by creating type aliases, which you already did. But sometimes it is even better to not have to specify types at all, for example by using more auto: class EventListenerRegister { … auto begin() { return listeners.begin(); } auto begin() const { return listeners.begin(); } auto end() { return listeners.end(); } auto end() const { return listeners.end(); } … }; Templates and source files
{ "domain": "codereview.stackexchange", "id": 44856, "lm_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++, object-oriented, game, design-patterns, event-handling", "url": null }
c++, object-oriented, game, design-patterns, event-handling Templates and source files Although I am aware that .cpp files should be used, there are several objects in this codebase that either are or contain templated methods. Can you elaborate on how this should be handled? It's considered fine to have some code in header files. However, it depends on how it is going to be used. If everything is compiled together, there is no problem. If you want to create a shared library of your event system, then consider that someone can upgrade the shared library separately from the binary that links with it. If the new version of the shared library requires different code in the templates, then that will create a problem: the binary doesn't know this and will probably do the wrong thing, leading to crashes, or worse: unexpected behavior. You can in fact move the definition of templated functions into source files. However, you then have to tell the compiler to explicitly instantiate those templates. That also means you have to know all the types you need to instantiate up front, which sometimes is not possible.
{ "domain": "codereview.stackexchange", "id": 44856, "lm_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++, object-oriented, game, design-patterns, event-handling", "url": null }
c++, beginner, makefile Title: MakeFile for C++ small project Question: I decided to implement a Makefile for a personal project I'm working on (I've never created Makefile before) but I need to learn for an upcoming work assignment. The Makefile it's supposed to build the unit test binary(graphs_test/graphtest) for my graph API code. My directory structure for the project is as follows: . ├── README.md ├── graphs │ ├── DFS │ │ ├── a.out │ │ └── dfsDriver.cpp │ ├── include │ │ └── graph.h │ └── source │ └── graph.cpp └── graphs_test ├── Makefile ├── graphtest ├── include │ └── graphTest.h ├── obj │ └── graphTest.o └── source └── graphTest.cpp My Makefile is as follows: CXX=g++ LDFLAGS=-pthread LOCALIDIR=./include _LOCALDEPS=graphTest.h LOCALDEPS=$(patsubst %, $(LOCALIDIR)/%,$(_LOCALDEPS)) IDIR=../graphs/include _DEPS=graph.h DEPS=$(patsubst %, $(IDIR)/%,$(_DEPS)) ODIR=obj SOURCE=./source _OBJ=graphTest.o OBJ=$(patsubst %,$(ODIR)/%,$(_OBJ)) LIBS=/usr/local/lib/libgtest.a CFLAGS=-I$(IDIR) -I$(LOCALIDIR) -Wall -pedantic -Werror $(ODIR)/%.o: $(SOURCE)/%.cpp $(DEPS) $(LOCALDEPS) @mkdir -p $(ODIR) $(CXX) -c -o $@ $< $(CFLAGS) graphtest: $(OBJ) $(CXX) -o $@ $^ $(LIBS) $(LDFLAGS) info: @echo 'LOCALDEPS is: "$(LOCALDEPS)"' @echo 'DEPS is: "$(DEPS)"' @echo 'OBJ is: "$(OBJ)"' clean: rm -rf $(ODIR) This currently works. That is it builds my test binary. But I would appreciate any tips on how I can improve this Makefile or gotchas that can burn me later. Note that I haven't created the Makefile for my graph API code. So, I'm confused if I create rules to compile my graph API as well (I realize that the latter question might be out of scope for this site). I don't know if it should matter, but the graph.cpp file is empty since my API is parameterized.
{ "domain": "codereview.stackexchange", "id": 44857, "lm_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++, beginner, makefile", "url": null }
c++, beginner, makefile Answer: Traditionally. The first target is all. This should be the first rule so that if no arguments are provided to make it builds all. Also here you are building the tests so I would expect all to simply build test. all: test test: graphtest echo "Please run the tests now they have been built" I like that you are defining graphtest in terms of $(OBJ). But personally I would define $(OBJ) in terms of $(SRC). You can then use $(wildcard ...) to select the source files. This way you don't need to modify your Makefile when you add more source files. SDIR = source ODIR = obj SRC = $(wildcard $(SDIR)/*.cpp) OBJ = $(patsubst $(SDIR)/%.cpp, $(ODIR)/%.o, $(SRC)) This is the default definition: CXX=g++ I would not define it at all. By doing this you prevent the user of your makefile from overriding the default. Note: running make can look like this: CXX=clang make The user defined CXX will now not take effect because you explicitly overwrite it. This is fine for simple files: LDFLAGS=-pthread But as your files get more complex this can hide add libraries. So you should prefer to use += LDFLAGS += -pthread The builtin rule for compiling C++ is: n.o is made automatically from n.cc, n.cpp, or n.C with a recipe of the form ‘$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c’. We encourage you to use the suffix ‘.cc’ or ‘.cpp’ for C++ source files instead of ‘.C’ to better support case-insensitive file systems. ie. You can think of the default rule as: %.o: %.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $* $^ Even if you need to define your custom rule because of the source/object directory rules I would encourage you to use the same pattern: $(ODIR)/%.cpp: $(SDIR)/%.cpp $(DEPS) $(LOCALDEPS) $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $* $< Similarly for linking I would use: executable: $(OBJ) $(CXX) $(LDFLAGS) $(OBJ) $(LOADLIBES) $(LDLIBS)
{ "domain": "codereview.stackexchange", "id": 44857, "lm_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++, beginner, makefile", "url": null }
c++, beginner, makefile Personally I don't like you having a specific command in the build to build the object directory. I would make this a dependency: $(ODIR)/%.o: $(SDIR)/%.cpp $(DEPS) $(LOCALDEPS) @mkdir -p $(ODIR) # Don't like this line. $(CXX) -c -o $@ $< $(CFLAGS) I would have written it like this: DIR_%: mkdir -p $* $(ODIR)/%.o: DIR_$(ODIR) $(SDIR)/%.cpp $(DEPS) $(LOCALDEPS) $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $* $< But rather than do this for each file. I would do one other change and move this to the executable: DIR_%: mkdir -p $* graphtest: DIR_$(ODIR) $(OBJ) $(CXX) -o $@ $(LDFLAGS) $(OBJ) $(LOADLIBES) $(LDLIBS) $(ODIR)/%.o: $(SDIR)/%.cpp $(DEPS) $(LOCALDEPS) $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $* $< You are manually building your dependencies in the makefile. This is hard work and error prone. You can get g++ to build the make depedencies fo you. DDIR = depend DEPS = $(patsubst $(SDIR)/%.cpp, $(DDIR)/%.d, $(SRC)) deps: DIR_$(DDIR) $(DEPS) $(DDIR)/%.d: $(SDIR)/%.cpp # I may not have got this line exactly write. # I had to strip it out of my Makefile # Lookup documentation in g++ what -MF -MP -MM -MT do $(CXX) -MF "$@" -MM -MP -MT "$@" -MT"$(ODIR)/$(<:.cpp=.o)" $(CPPFLAGS) $(CXXFLAGS) $< This will create a Makefile that you can include into your make file. # Add this to the top of your make file: -include $(DDIR)/* You can now auto rebuild your dependencies with make dep. This is untested. But what I would have as my Makefile (If I wrote them by hand). LDFLAGS += -pthread CXXFLAGS += -I include -I ../graphs/include CXXFLAGS += -Wall -Wextra -pedantic -Werror SDIR = source ODIR = objs DDIR = deps SRC = $(wildcard $(SDIR)/*.cpp) OBJS = $(patsubst $(SDIR)/%.cpp, $(ODIR)/%.o, $(SRC)) DEPS = $(patsubst $(SDIR)/%.cpp, $(DDIR)/%.d, $(SRC)) -include $(DDIR)/* TARGET = graphtest
{ "domain": "codereview.stackexchange", "id": 44857, "lm_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++, beginner, makefile", "url": null }
c++, beginner, makefile -include $(DDIR)/* TARGET = graphtest all: test test: $(TARGET) @echo "Test exutable built. Please run it" deps: DIR_$(DDIR) $(DEPS) @echo "Dependencies updates" graphtest: DIR_$(ODIR) $(OBJS) $(CXX) -o $@ $(LDFLAGS) $(OBJS) $(LOADLIBES) $(LDLIBS) $(ODIR)/%.o: $(SDIR)/%.cpp $(DEPS) $(LOCALDEPS) $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $* $< $(DDIR)/%.d: $(SDIR)/%.cpp $(CXX) -MF "$@" -MM -MP -MT "$(ODIR)/$(<:.cpp=.o)" $(CPPFLAGS) $(CXXFLAGS) $< DIR_%: mkdir -p $* info: @echo 'LOCALDEPS is: "$(LOCALDEPS)"' @echo 'DEPS is: "$(DEPS)"' @echo 'OBJs is: "$(OBJS)"' clean: rm -rf $(ODIR) Though I personally put the object files in a separate directory (I do normally put the source and header files in the same directory as the Makefile. The make file becomes a lot simpler if you have the source, header and object files all in the same directory as the Makefile as all the default rules hold. Nowadays My makefile looks like this: TARGET = graphtest.app LDLIBS = -lpthread include <Directory Where Master Make Lives>/Makefile Then I have all the logic in the included Makefile. My master makefile will not work for you as it assumes things I do with my directory structure. But you can start putting common things into a master makefile so you don't need to type them out every time. For some hints you can look at the one I have build over the years: https://github.com/Loki-Astari/ThorMaker/blob/master/tools/Makefile
{ "domain": "codereview.stackexchange", "id": 44857, "lm_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++, beginner, makefile", "url": null }
python-3.x, programming-challenge, integer Title: Calculate the cost of Biryani lessons Question: Problem: According to a recent survey, Biryani is the most ordered food. Chef wants to learn how to make world-class Biryani from a MasterChef. The chef will be required to attend the MasterChef's classes for X weeks and the cost of classes per week is Y coins. What is the total amount of money that the Chef will have to pay? Input Format: The first line of input will contain an integer T — the number of test cases. The first and only line of each test case contains two space-separated integers. for _ in range(int(input())): x,y = map(int, input().split()) print(x*y) I tried to solve this simple calculation problem with fewer declared variables. Is there any way to optimize the above code? Answer: Your code is concise, readable, and idiomatic. It works as you intended. It's small but nice snippet of code. You could probably turn it into a one-liner, but it would get rather complex and readability would suffer, implying issues with maintainability, re-usability and reviewing. Regarding style, I have two minor remarks: The indentation is unusual, PEP 8 and recommends 4 spaces for indents, not 8. But this might as well be an issue with question formatting. The variable names you chose, x and y, are undescriptive. I would prefer weeks and cost_per_week, although your approach of using the names in the problem description is understandable.
{ "domain": "codereview.stackexchange", "id": 44858, "lm_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, programming-challenge, integer", "url": null }
python-3.x, programming-challenge, integer I have a bigger issue with your use of input for getting data. From what I understand from the input format description, I expect the format to be a text file. Expecting the user to copy, line by line, the input data fails to solve the problem in my book. Python makes it quite easy to work with files and iterating over lines. You should look into the open built-in function and work with that. In any case, when working with user input, you should validate that input and handle invalid input gracefully. Imagine mis-typing a line on the 99-th test case out of 100, your code would crash and the user would need to start over from the top. You can expect an input file to be properly formatted, but that assumption doesn't hold for data gotten through input. The use of print for output is also sub-optimal, as you would like to validate test cases programmatically. However, in this case, since the test data doesn't provide expected values, it is a decent approach, for lack of a better solution.
{ "domain": "codereview.stackexchange", "id": 44858, "lm_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, programming-challenge, integer", "url": null }
c, memory-management, memory-optimization Title: Simple stack allocator in C Question: My plan is to allocate a fixed amount of static memory at initialization (a few MBs), and use a stack allocator for quick temporary buffers. The idea is to avoid calls to malloc() for these kinds of temporary buffers (should be safer this way), but still being able to return it from a function (and then freed) if needed, which I otherwise wouldn't be able to with local arrays. An allocator based on a stack sounded great for this use case, and should also be quite fast since we're only incrementing a stack pointer and calling memset() to zero out the space. The data I'll be storing on the stack will always be of type uint8_t, so the allocator assumes that's what we want and returns a uint8_t* instead of a void* like malloc() does. #include <stdint.h> #include <string.h> // Convert megabytes to bytes. #define MB(x) (x * 1024 * 1024) // Default size: 2 MB. static uint8_t Stack[MB(2)]; // Points to the next available memory address. static uint8_t *StackPointer = Stack; int32_t GetStackUsage() { // Return the amount of memory used. return StackPointer - Stack; } int32_t GetStackFree() { // Return the amount of available memory. return sizeof(Stack) - GetStackUsage(); } uint8_t *Alloc(int32_t length) { // Return a null pointer, if memory requested is less than 1 byte. if (length < 1) return NULL; // Return a null pointer, if there is not enough memory left on the stack. if (StackPointer + length > Stack + sizeof(Stack)) return NULL; // Get a pointer to the next available address. uint8_t *memory = StackPointer; // Zero out the memory. memset(memory, 0, length); // Increment stack pointer. StackPointer += length; return memory; } void Dealloc(uint8_t *memory) { // Double free is not a good idea. if (memory == NULL) return; // Reset stack pointer. StackPointer = memory; }
{ "domain": "codereview.stackexchange", "id": 44859, "lm_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, memory-optimization", "url": null }
c, memory-management, memory-optimization // Reset stack pointer. StackPointer = memory; } Answer: Bug: Invalid address computation StackPointer + length > Stack + sizeof(Stack) for this to be true, StackPointer + length points past the end of Stack + sizeof(Stack). Yet that calculation is undefined behavior (UB) as address calculations are only allowed within the object (or 1 past). length > sizeof(Stack) - (StackPointer - Stack) works better. Why type int32_t? Allocation sizes are idiomatically size_t in C. int32_t is unfounded. I could see some rational for unsigned, uint_least32_t or even int, but not int32_t. size_t remains the best choice for sizing. Consider 0 allocation I would find such an allocator more useful where Alloc(0) did not return NULL. If needed, use if (length == 0) length++;. This way, a NULL return is unambiguously an out-of-memory failure. Alignment OP has "data I'll be storing on the stack will always be of type uint8_t", yet that is in the text and deserves to be in the code as a comment to indicate this restriction. Consider instead, making useful for all types. *alloc() and friends return a pointer suitable for all alignments. Research max_align_t to find the alignment needed. Consider quantizing the length: // Something like if (length % alignof(max_align_t)) { length += alignof(max_align_t) - length % alignof(max_align_t); } // or length = (length + alignof(max_align_t) - 1) & (alignof(max_align_t) - 1);
{ "domain": "codereview.stackexchange", "id": 44859, "lm_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, memory-optimization", "url": null }
c, memory-management, memory-optimization When length is an unsigned type and since sizeof(max_align_t) is certainly a power of 2, length % sizeof(max_align_t) results in a fast and operation. So this adjustment is not a costly general purpose %. Why return uint8_t *? C allocators far more often return void *. Speed If "should also be quite fast", skip the memset(memory, 0, length); part and let the caller zero memory if desired. Avoid precedence problems Consider the effect of MB(2 + 3) --> (2 + 3 * 1024 * 1024) Better as #define MB(x) ((x) * 1024 * 1024) Avoid overflow #define MB(x) (x * 1024 * 1024) is overflow with 16-bit int. Suggest: #define MB(x) ((size_t)1024 * 1024 * (x)) Naming Code has GetStackUsage, GetStackFree, Alloc, Dealloc which is scattered over that namespace and risks collisions. Suggest AllocStack_Usage, AllocStack_Free, AllocStack, AllocStack_Free or some other uniform naming. Header file As this is a set of helper routines, form a AllocStack.h to show what is exposed to the world and a AllocStack.c to show the implementation. Deallocating NULL Code nicely handles Dealloc(NULL). This is like free(NULL) is OK. Debugging idea Dealloc() should expect that the pointer (after the null check) only grows the stack. If a Dealloc() occurs that shrank the stack, that is certainly an error and could be caught and flagged - maybe with an assert().
{ "domain": "codereview.stackexchange", "id": 44859, "lm_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, memory-optimization", "url": null }
python, object-oriented, linked-list Title: Printing the elements of a linked list Question: An absolute beginner here who is practising linked list problems in hackerrank. Stumbled upon this question which is categorised as easy. Given a pointer to the head node of the linked list, print each node's data element. Link to question https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list/problem?isFullScreen=true class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def __init__(self): self.head = None self.tail = None def insert_node(self, node_data): node = SinglyLinkedListNode(node_data) if not self.head: self.head = node else: self.tail.next = node self.tail = node def printLinkedList(head): while head is not None: print(head.data, end="\n") head = head.next print() if __name__ == '__main__': llist_count = int(input()) llist = SinglyLinkedList() for _ in range(llist_count): llist_item = int(input()) llist.insert_node(llist_item) printLinkedList(llist.head) I have 2 questions about the code which I'm struggling to understand. In the printLinkedList function, why must it be print(head.data) and not just print(head) Referring to the same line print(head.data), the head is probably SinglyLinkedList().head I assume, but is there a data attribute in the class? Would appreciate if anyone could shed some light on my doubts.
{ "domain": "codereview.stackexchange", "id": 44860, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, object-oriented, linked-list", "url": null }
python, object-oriented, linked-list Would appreciate if anyone could shed some light on my doubts. Answer: To answer your first question: Each node in the list has a data and next attribute and we wish to print all the data attribute values by walking through the list. We have a choice in how we can design function printLinkedList to be called: (1) We pass it a SinglyLinkedList instance such as llist or the first node of llist, namely llist.head. The second option was chosen. If we printed head instead of head.data, it would be printing out a SinglyLinkedListNode instance and the output would look something like <__main__.SinglyLinkedListNode object at 0x000001D5FCB4F820. But since we wish to print out the data attribute values, we print head.data instead. I do think a better design would be to pass instead the linked list instance itself: def printLinkedList(linked_list): node = linked_list.head while node: print(node.data) # end='\n' is not required node = node.next print()
{ "domain": "codereview.stackexchange", "id": 44860, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, object-oriented, linked-list", "url": null }
python, object-oriented, linked-list You might even wish to make this a method of the SinglyLinkedList class replacing all references to linked_list with self since the client of this class should not be concerned with how it's implemented. To answer your second question: If you execute SinglyLinkedList().head you have created an empty list where the head attribute will have a value of None. But I would say that the head attribute is an instance attribute and not a class attribute. If it were a class attribute you would be able to say SinglyLinkedList.head without having created in actual instance of this class. The following may be a bit advanced for you, but I would prefer to redesign the classes to encapsulate their implementation and to expose to a client the bare minimum they need to use the classes. So the only thing that should be exposed is the class SinglyLinkedList because there is no need for a client to know that it iternally uses SinglyListNode instances to implement it. I would also provide a general method for iterating the elements of the list and then the user can implement any print logic using this capability: class SinglyLinkedList: class SinglyLinkedListNode: def __init__(self, node_data): self._data = node_data self._next = None def __init__(self): self._head = None self._tail = None def insert_node(self, node_data): node = SinglyLinkedList.SinglyLinkedListNode(node_data) if not self._head: self._head = node else: self._tail._next = node self._tail = node def __iter__(self): class SinglyLinkedListIterator: def __init__(self, linked_list): self._current_node = linked_list._head def __iter__(self): return self
{ "domain": "codereview.stackexchange", "id": 44860, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, object-oriented, linked-list", "url": null }
python, object-oriented, linked-list def __iter__(self): return self def __next__(self): if self._current_node: node_data = self._current_node._data self._current_node = self._current_node._next return node_data raise StopIteration return SinglyLinkedListIterator(self) def printLinkedList(linked_list): for node_data in linked_list: print(node_data) if __name__ == '__main__': node_count = int(input('Enter the number of nodes in the list: ')) #Booboo llist = SinglyLinkedList() for _ in range(node_count): node_data = int(input('Enter the next node value (an integer): ')) llist.insert_node(node_data) printLinkedList(llist) Note that the client is only needs to use the insert_node method and is given the ability to iterate all the data values that have been added. There is no need to know about any attributes used to implement the list and therefore the names of the attributes start with '_' to suggest to a client that these are private attributes not to be referenced by the client. Python Iterators When you have a class instance that is a collection of items, you would like to be able to iterate those elements, i.e. enumerate each element one by one. To accomplish this you implement an instance method named __iter__: class Foo: """A collection of items.""" ... def __iter__(self): """Return an iterator for this collection""". ... foo = Foo() ... # Add elements to foo # Iterate through all the items in the collection: iterator = foo.__iter__() # Or equivalently: iterator = iter(foo) try: while True: # Get next item: item = iterator.__next__() # Or equivalently: item = next(iterator) ... # Do something with item except StopExecption: pass # StopException is raised when there are no more items
{ "domain": "codereview.stackexchange", "id": 44860, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, object-oriented, linked-list", "url": null }
python, object-oriented, linked-list So the iterator instance that is returned must support method __next__, which is called repeatedly to get each item in the collection until there are no more items left to iterate. When this occurs a StopException exception is raised. But there is an easier syntax you can use to iterate such a collection, i.e. for/in: for item in foo: ... # Do something with item The above code is equivalent to the try/except blocks in the previous coding example. Quite often a collection's __iter__(self) method just returns self, i.e. the collection instance is the iterator: class Foo: def __init__(self): self._container = [] # for holding the items def add_item(self, item): self._container.append(item) def __iter__(self): # Initialize for iteration: self._current_index = 0 return self # Note the following: # Since self._container is a list instance, which already # supports iteration, we could have implemented this method # simply with: return iter(self._container) def __next__(self): # Any more items to iterate? if self._current_index < len(self._container): item = self._container[self._current_index] self._current_index += 1 return item # No more items to iterate: raise StopException def __iter__(self): return self Note that we did not really need to implement a __iter__ method in FooIterator since the only method that should be called on the iterator is __next__. But this allows a client to code: foo = Foo() for item in iter(foo): ... However, the problem with a container being its own iterator is that you cannot correctly perform multiple iterations on the container concurrently: # The following does not work! # Multiply every element in foo by every other element: for item1 in foo: for item2 in foo: print(item1 * item2)
{ "domain": "codereview.stackexchange", "id": 44860, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, object-oriented, linked-list", "url": null }
python, object-oriented, linked-list A problem arises since foo is the iterator instance for both loops and each loop iteration will be updating the same self._index variable. To support multiple, concurrent iterations, each call to __iter__ method needs to return a distinct iterator instance. So we define a new class, FooIterator, that can be used to iterate a Foo instance: class FooIterator: def __init__(self, foo_instance): self._container = foo_instance._container self._current_index = 0 def __next__(self): # Any more items to iterate? if self._current_index < len(self._container): item = self._container[self._current_index] self._current_index += 1 return item # No more items to iterate: raise StopException Now each for/in loop uses its own iterator instance modifying its own self._current_index attribute. And our Foo class is modified as follows: class Foo: def __init__(self): self._container = [] # for holding the items def add_item(self, item): self._container.append(item) def __iter__(self): return FooIterator(self)
{ "domain": "codereview.stackexchange", "id": 44860, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, object-oriented, linked-list", "url": null }
c, linked-list, memory-management Title: Implementation of K&R Malloc Question: This is a one file implementation of K&R Malloc. It's passed all test cases I've run on it, so I would like to request a code review. my_malloc.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> void insert_into_free_list(void* ptr); void* my_malloc(size_t size); void my_free(void* ptr); void coalesce_free_list(); void* free_list_begin(); void* free_list_next(void* node); void* malloc(size_t size); void free(void* ptr); /** * A single chunk in the free list that my_malloc uses to dole out memory. */ struct malloc_chunk { size_t size; /*!< The size of the chunk in bytes. This includes the bookkeeping bytes, the block presented to the user, and any necessary padding. Valid for both free and allocated chunks.*/ struct malloc_chunk* next_chunk; /*!< A pointer to the next chunk in the free list. Should always be NULL for the tail of the free list. Valid for free chunks only. */ }; /** * The head of the free list. */ static struct malloc_chunk* head_of_free_list = NULL; /** * A memory allocator which acts as a buffered interface to the sbrk system call. * Given a number of bytes, it returns a pointer to a block of memory whose size is greater than or equal to the number given aligned by eight bytes or NULL if the user requested 0 bytes. * It will also return NULL on failure of sbrk. The user is trusted to check for this failure condition. * It will include an additional eight bytes at the start of every block of memory allocated to be used for bookkeeping. * Those eight bytes should NOT be presented to the user. * * @param size The size in bytes of the memory block to be presented to the user. * @return The pointer to the beginning of the memory block that is presented to the user. */ void* my_malloc(size_t size) { size_t size_to_allocate; struct malloc_chunk* chunk; struct malloc_chunk** chunk_pointer; if(size == 0) { return NULL; }
{ "domain": "codereview.stackexchange", "id": 44861, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list, memory-management", "url": null }
c, linked-list, memory-management if(size == 0) { return NULL; } /* Round size up to the nearest multiple of eight */ size = (size + 7) & ~0x07; /* Add eight bytes for bookkeeping */ size += 8; /* If we can find a chunk in our free list that is large enough to accommodate the user's request, take it out of our free list and give it to the user. */ chunk = head_of_free_list; chunk_pointer = &head_of_free_list; while(chunk != NULL) { if(chunk->size >= size) { struct malloc_chunk* return_ptr = (struct malloc_chunk*) ((char*) chunk + chunk->size - size); /** * We either found an exact match or one that's close enough. * To avoid fragmentation, we simply give the user the entire chunk if it's close enough. */ if(chunk->size - size <= 16) { return_ptr = chunk; *chunk_pointer = chunk->next_chunk; /* In this case, the chunk is more than big enough for the requested amount of memory, so we just decrease the chunk's size. */ } else { chunk->size -= size; return_ptr->size = size; } return (char*) return_ptr + 8; } chunk_pointer = &chunk->next_chunk; chunk = chunk->next_chunk; } /* my_malloc should not call sbrk with a value lower than 8192. */ size_to_allocate = size > 8192 ? size : 8192; chunk = sbrk(size_to_allocate); if(chunk == (void*) -1) { perror("my_malloc"); return NULL; } /** * This covers the case that the user requested a large amount of memory. * Since they requested such a large amount, we don't attempt to add a buffer of extra memory to the free list and give them everything instead. */ if(size_to_allocate > 8192) { chunk->size = size; return (char*) chunk + 8; }
{ "domain": "codereview.stackexchange", "id": 44861, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list, memory-management", "url": null }
c, linked-list, memory-management chunk->size = size_to_allocate - size; struct malloc_chunk* ptr = (struct malloc_chunk*) ((char*) chunk + size_to_allocate - size); insert_into_free_list(chunk); ptr->size = size; return (char*) ptr + 8; } /** * A memory de-allocator which returns memory to the free list used by my_malloc. * Given a pointer which indicates a chunk of memory that was previously presented to the user by my_malloc, it uses information found in the eight bookkeeping bytes * found before the chunk specified by the pointer to add the chunk to the free list. * It can safely be called with NULL. * It will also coalesce the chunks in the free list to keep the number of chunks in the list to a minimum. * @param ptr A pointer to the beginning of a chunk of memory that was presented to the user by my_malloc. */ void my_free(void* ptr) { if(ptr == NULL) { coalesce_free_list(); return; } /* Back up by eight bytes, so that we can easily access the bookkeeping bytes. */ ptr = ((char*) ptr) - 8; insert_into_free_list(ptr); coalesce_free_list(); } /** * Returns the head of the free list or NULL if the free list is empty. * @return Head of the free list used by my_malloc. */ void* free_list_begin() { return head_of_free_list; } /** * Given a pointer to a node in the free list, it returns the next node in the list or NULL if node points to the tail of the list. * @param node A pointer to a node in the free list. * @return A pointer to the next node in the free list or NULL if @node points to the tail of the list. */ void* free_list_next(void* node) { return ((struct malloc_chunk*) node)->next_chunk; } /** * Used by my_free to coalesce the free list and keep the number of chunks present in the free list to a minimum. */ void coalesce_free_list() { struct malloc_chunk* node = head_of_free_list; if(node == NULL) { return; }
{ "domain": "codereview.stackexchange", "id": 44861, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list, memory-management", "url": null }
c, linked-list, memory-management if(node == NULL) { return; } while(node != NULL) { /* If two chunks are right next to each other in memory, then we can coalesce them. */ while((char*) node + node->size == (char*) node->next_chunk) { node->size += node->next_chunk->size; node->next_chunk = node->next_chunk->next_chunk; } node = node->next_chunk; } } void insert_into_free_list(void* ptr) { struct malloc_chunk* chunk_in_free_list; struct malloc_chunk* new_chunk; new_chunk = ptr; /** * The head of the free list being NULL means one of two things: * 1.) The user has called my_free without a corresponding call to my_malloc. We trust that they won't do this. * 2.) All chunks in the free list have been allocated. * * If the head isn't NULL, it could also be the case that ptr needs to be inserted before the head of the free list. * Either way, we make ptr the new head of the free list. */ if(head_of_free_list == NULL || head_of_free_list >= new_chunk) { new_chunk->next_chunk = head_of_free_list; head_of_free_list = new_chunk; } else { chunk_in_free_list = head_of_free_list; /** * We try to insert into our free list at the point where ptr->previous_chunk < ptr < ptr->next_chunk. * This will make coalescing the free list easier. */ while(chunk_in_free_list->next_chunk != NULL && chunk_in_free_list->next_chunk < new_chunk) { chunk_in_free_list = chunk_in_free_list->next_chunk; } new_chunk->next_chunk = chunk_in_free_list->next_chunk; chunk_in_free_list->next_chunk = new_chunk; } } /** * Alias of my_malloc, so it can be used with LD_PRELOAD */ void* malloc(size_t size) { return my_malloc(size); } /** * Alias of my_free, so it can be used with LD_PRELOAD */ void free(void* ptr) { my_free(ptr); }
{ "domain": "codereview.stackexchange", "id": 44861, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list, memory-management", "url": null }
c, linked-list, memory-management Answer: Some quick ideas: Masking with an int is not safe. Consider that size_t may be wider than unsigned/int, then the desired ~ mask will be insufficient. // size = (size + 7) & ~0x07; // Avoid size = (size + 7) & ~((size_t)0x07); // Better Pointer math treads on thin ice. It is assumed that aligning to 8 is sufficient. struct malloc_chunk* return_ptr = (struct malloc_chunk*) ((char*) chunk + chunk->size - size); // Iffy Better to use alignof(max_align_t) from <stddef.h> and proceed with: #define ALIGNMENT_N (alignof (max_align_t)) #define PRE_N (sizeof (union { size_t size; max_align_t dummy;})) size = (size + ALIGNMENT_N - 1) & ~(ALIGNMENT_N - 1); // Better Perhaps replace magic number 16 too. Also wrap 8192 in macro #define MY_MALLOC_BIG 8192 Consider pre-pending allocated data with a well aligned size. This aligns data and negates the need for the not-so-magical 8 coded in so many places. struct malloc_chunk { union { size_t size; max_align_t dummy; } u; union { struct malloc_chunk* next_chunk; max_align_t dummy; } v; }; Robust code would also check against large requests if (size > SIZE_MAX - ALIGNMENT_N - PRE_N) { return NULL; // Fail } ... // else the following code is problematic. size = (size + ALIGNMENT_N - 1) & ~(ALIGNMENT_N - 1); size += PRE_N; sbrk() is not from the standard C library. Use (void) when declaring functions to ensure parameter checking, else a call like free_list_begin(42) will not flag an error. // void* free_list_begin(); void* free_list_begin(void);
{ "domain": "codereview.stackexchange", "id": 44861, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list, memory-management", "url": null }
c++, object-oriented, design-patterns, event-handling Title: Improved Event System & InputManager Using C++ Question: I am new to C++, so please take me easy. I want to make a low-level game engine only using C++, OpenGL and GLFW. This is a continuation of Event System using C++ ; I added the suggestions from there. Here's a diagram of the improved event system: I also added an InputManager: I know I could implement a FSM for the InputManager, but for the moment, i do not need it -instead of the bool textInputMode. I would appreciate very much some feedback. Event.h: #pragma once #include <string> enum class EventCategory { None, Input, Window, Mouse, Keyboard, Application, }; enum class EventType { None, WindowResize, WindowLostFocus, WindowGainedFocus, WindowClose, WindowCursorEnter, WindowCursorLeave, MouseMove, MousePress, MouseRelease, MouseScroll, KeyboardPress, KeyboardRepeat, KeyboardRelease, CharPress, }; struct EventDescription { const EventCategory category; const EventType type; const std::string name; }; class Event { public: virtual ~Event() = default; bool handle() { handled = true; } bool isHandled() const { return handled; } EventCategory getCategory() const { return getDescription().category; } EventType getType() const { return getDescription().type; } std::string getTypeName() const { return getDescription().name; } virtual EventDescription getDescription() const = 0; private: bool handled = false; }; class NoneEvent : public Event { public: EventDescription getDescription() const override { return { EventCategory::None ,EventType::None, "None" }; } }; KeyboardEvent.h: #pragma once #include "Event.h" #include <Stdint.h> class KeyboardEvent : public Event { protected: KeyboardEvent(const int keyCode, const int scancode, const int mods) : keyCode(keyCode), scancode(scancode), mods(mods) { }
{ "domain": "codereview.stackexchange", "id": 44862, "lm_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++, object-oriented, design-patterns, event-handling", "url": null }
c++, object-oriented, design-patterns, event-handling public: virtual ~KeyboardEvent() = default; EventDescription getDescription() const override = 0; int getKeyCode() const { return keyCode; } int getScanCode() const { return scancode; } int getMods() const { return mods; } private: const int keyCode; const int scancode; const int mods; }; class KeyboardPressEvent : public KeyboardEvent { public: KeyboardPressEvent(const int keyCode, const int scancode, const int mods) : KeyboardEvent(keyCode, scancode, mods) { } EventDescription getDescription() const override { return { EventCategory::Keyboard, EventType::KeyboardPress, "KeyboardPress"}; } }; class KeyboardRepeatEvent : public KeyboardEvent { KeyboardRepeatEvent(const int keyCode, const int scancode, const int mods) : KeyboardEvent(keyCode, scancode, mods) { } EventDescription getDescription() const override { return { EventCategory::Keyboard, EventType::KeyboardRepeat, "KeyboardRepeat" }; } }; class KeyboardReleaseEvent : public KeyboardEvent { public: KeyboardReleaseEvent(const int keyCode, const int scancode, const int mods) : KeyboardEvent(keyCode, scancode, mods) { } EventDescription getDescription() const override { return { EventCategory::Keyboard, EventType::KeyboardRelease, "KeyboardRelease" }; } }; class CharPressEvent : public Event { public: CharPressEvent(const int codePoint) : codePoint(codePoint) { } int getCodePoint() const { return codePoint; } EventDescription getDescription() const override { return { EventCategory::Keyboard, EventType::CharPress, "CharPress" }; } private: const int codePoint; }; MouseEvent.h: #pragma once #include "Event.h" class MouseEvent : public Event { public: virtual ~MouseEvent() = default; EventDescription getDescription() const override = 0; }; // ===================== MOTION UPCOMING ==============================
{ "domain": "codereview.stackexchange", "id": 44862, "lm_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++, object-oriented, design-patterns, event-handling", "url": null }
c++, object-oriented, design-patterns, event-handling // ===================== MOTION UPCOMING ============================== class MouseMotionEvent : public MouseEvent { public: double getMouseX() const { return mouseX; } double getMouseY() const { return mouseY; } virtual ~MouseMotionEvent() = default; EventDescription getDescription() const override = 0; protected: MouseMotionEvent(const double mouseX, const double mouseY) : mouseX(mouseX), mouseY(mouseY) { } private: const double mouseX, mouseY; }; class MouseMoveEvent : public MouseMotionEvent { public: MouseMoveEvent(const double mouseX, const double mouseY) : MouseMotionEvent(mouseX, mouseY) { } virtual ~MouseMoveEvent() = default; EventDescription getDescription() const override { return { EventCategory::Mouse, EventType::MouseMove, "MouseMove" }; } }; class MouseScrollEvent : public MouseMotionEvent { public: MouseScrollEvent(const double mouseX, const double mouseY) : MouseMotionEvent(mouseX, mouseY) { } virtual ~MouseScrollEvent() = default; EventDescription getDescription() const override { return { EventCategory::Mouse, EventType::MouseScroll, "MouseScroll" }; } }; // ===================== BUTTON UPCOMING ============================== class MouseButtonEvent : public MouseEvent { protected: MouseButtonEvent(const int button, const int mods) : button(button), mods(mods) { } public: int getButton() const { return button; } int getMods() const { return mods; } virtual ~MouseButtonEvent() = default; EventDescription getDescription() const override = 0; private: const int button, mods; }; class MousePressEvent : public MouseButtonEvent { public: MousePressEvent(const int button, const int mods) : MouseButtonEvent(button, mods) { } virtual ~MousePressEvent() = default; EventDescription getDescription() const override { return { EventCategory::Mouse, EventType::MousePress, "MousePress" }; } };
{ "domain": "codereview.stackexchange", "id": 44862, "lm_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++, object-oriented, design-patterns, event-handling", "url": null }
c++, object-oriented, design-patterns, event-handling class MouseReleaseEvent : public MouseButtonEvent { public: MouseReleaseEvent(const int button, const int mods) : MouseButtonEvent(button, mods) { } virtual ~MouseReleaseEvent() = default; EventDescription getDescription() const override { return { EventCategory::Mouse, EventType::MouseRelease, "MouseRelease" }; } }; WindowEvent.h: #pragma once #include "Event.h" class WindowEvent : public Event { public: virtual ~WindowEvent() = default; EventDescription getDescription() const override = 0; }; class WindowResizeEvent : public WindowEvent { public: WindowResizeEvent(const int width, const int height) : width(width), height(height) { } virtual ~WindowResizeEvent() = default; EventDescription getDescription() const override { return { EventCategory::Window, EventType::WindowResize, "WindowResize" }; } int getWidth() const { return width; } int getHeight() const { return height; } private: const int width, height; }; class WindowCloseEvent : public WindowEvent { public: virtual ~WindowCloseEvent() = default; EventDescription getDescription() const override { return { EventCategory::Window, EventType::WindowClose, "WindowClose" }; } }; class WindowLostFocusEvent : public WindowEvent { public: virtual ~WindowLostFocusEvent() = default; EventDescription getDescription() const override { return { EventCategory::Window, EventType::WindowLostFocus, "WindowLostFocus" }; } }; class WindowGainedFocusEvent : public WindowEvent { public: virtual ~WindowGainedFocusEvent() = default; EventDescription getDescription() const override { return { EventCategory::Window, EventType::WindowGainedFocus, "WindowGainedFocus" }; } };
{ "domain": "codereview.stackexchange", "id": 44862, "lm_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++, object-oriented, design-patterns, event-handling", "url": null }
c++, object-oriented, design-patterns, event-handling class WindowCursorEnterEvent : public WindowEvent { public: virtual ~WindowCursorEnterEvent() = default; EventDescription getDescription() const override { return { EventCategory::Window, EventType::WindowCursorEnter, "WindowCursorEnter" }; } }; class WindowCursorLeaveEvent : public WindowEvent { public: virtual ~WindowCursorLeaveEvent() = default; EventDescription getDescription() const override { return { EventCategory::Window, EventType::WindowCursorLeave, "WindowCursorLeave" }; } }; EventQueue.h: #pragma once #include <queue> #include <memory> #include "MouseEvent.h" #include "KeyboardEvent.h" #include "WindowEvent.h" class EventQueue { public: using EventPtr = std::unique_ptr<Event>; void push(EventPtr event) { eventQueue.push(std::move(event)); } EventPtr pop() { if (eventQueue.empty()) return nullptr; EventPtr event = std::move(eventQueue.front()); eventQueue.pop(); return event; } bool isEmpty() const { return eventQueue.empty(); } private: std::queue<EventPtr> eventQueue; }; EventListenerID.h: #pragma once class EventListenerID { public: explicit EventListenerID(const size_t id) : id(id) { } size_t get() const { return id; } private: const size_t id; }; EventListener.h: #pragma once #include <functional> #include "MouseEvent.h" #include "KeyboardEvent.h" #include "WindowEvent.h" #include "EventListenerID.h" class BaseEventListener { public: virtual ~BaseEventListener() = default; virtual void dispatchEvent(const Event&) const = 0; virtual bool isEventType(const Event& event) const = 0; virtual EventListenerID getID() const = 0; }; template<typename EventType> class EventListener : public BaseEventListener { public: using EventCallBackFn = std::function<void(const EventType&)>;
{ "domain": "codereview.stackexchange", "id": 44862, "lm_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++, object-oriented, design-patterns, event-handling", "url": null }
c++, object-oriented, design-patterns, event-handling explicit EventListener(const EventCallBackFn& callBack, const EventListenerID& id) : callBack(callBack), id(id) { } void dispatchEvent(const Event& event) const override { callBack(static_cast<const EventType&>(event));} bool isEventType(const Event& event) const override { return dynamic_cast<const EventType*>(&event) != nullptr; } EventListenerID getID() const override { return id; } private: const EventCallBackFn callBack; const EventListenerID id; }; EventListenerRegister.h: #pragma once #include <vector> #include <memory> #include <algorithm> #include <stdexcept> #include "EventListener.h" class EventListenerRegister { public: using ListenerList = std::vector<std::unique_ptr<BaseEventListener>>; template<typename EventType> EventListenerID registerListenerFor(const typename EventListener<EventType>::EventCallBackFn& callBack) { static int currentID = 0; EventListenerID listenerID(currentID); ++currentID; std::unique_ptr<BaseEventListener> listener = std::make_unique<EventListener<EventType>>(callBack, listenerID); listeners.push_back(std::move(listener)); return listenerID; } void unregisterListener(EventListenerID& listenerID) { listeners.erase( std::remove_if(listeners.begin(), listeners.end(), [&listenerID](const auto& listener) { return listenerID.get() == listener->getID().get(); }), listeners.end() ); } auto begin() { return listeners.begin(); } auto begin() const { return listeners.begin(); } auto end() { return listeners.end(); } auto end() const { return listeners.end(); } private: ListenerList listeners; }; EventBus.h: #pragma once #include <memory> #include "EventListenerRegister.h" #include "EventQueue.h"
{ "domain": "codereview.stackexchange", "id": 44862, "lm_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++, object-oriented, design-patterns, event-handling", "url": null }
c++, object-oriented, design-patterns, event-handling #include <memory> #include "EventListenerRegister.h" #include "EventQueue.h" class EventBus { public: template<typename EventType> EventListenerID registerListenerFor(const typename EventListener<EventType>::EventCallBackFn& callBack) { return listeners.registerListenerFor<EventType>(callBack); } void unregisterListener(EventListenerID& listenerID) { listeners.unregisterListener(listenerID); } void publishEvent(EventQueue& eventQueue) const { while(const auto& event = eventQueue.pop()) { for (const auto& listener : listeners) { if (listener->isEventType(*event.get())) listener->dispatchEvent(*event.get()); if (event->isHandled()) break; } } } private: EventListenerRegister listeners; }; EventManager.h: #pragma once #include "EventBus.h" #include "EventQueue.h" class EventManager { public: template<typename EventType> requires std::derived_from<EventType, Event> EventListenerID registerListenerFor(const typename EventListener<EventType>::EventCallBackFn& callBack) { return eventBus.registerListenerFor<EventType>(callBack); } void unregisterListener(EventListenerID& listenerID) { eventBus.unregisterListener(listenerID); } template<typename EventType, typename... Args> requires std::derived_from<EventType, Event> void pushEvent(Args&&... args) { eventQueue.push(std::make_unique<EventType>(std::forward<Args>(args)...)); } void publishEvents() { eventBus.publishEvent(eventQueue); } private: EventBus eventBus; EventQueue eventQueue; }; MouseState.h: #pragma once #include <unordered_map> class MouseState { public: struct Position { double x, y; };
{ "domain": "codereview.stackexchange", "id": 44862, "lm_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++, object-oriented, design-patterns, event-handling", "url": null }
c++, object-oriented, design-patterns, event-handling class MouseState { public: struct Position { double x, y; }; void keyDown(const int buttonCode) { buttons[buttonCode] = true; } void keyRelease(const int buttonCode) { buttons[buttonCode] = false; } void setPosition(Position position) { this->position = position; } bool isButtonDown(const int buttonCode) const { return buttons[buttonCode]; } Position getPosition() const { return position; } private: mutable std::unordered_map<int, bool> buttons; Position position; }; KeyboardState.h: #pragma once #include <unordered_map> #include "Events/EventManager.h" class KeyboardState { public: enum class ButtonState { Pressed, Repeat, Released }; void keyPress(const int keyCode) { keyStates[keyCode] = ButtonState::Pressed; } void keyRepeat(const int keyCode) { keyStates[keyCode] = ButtonState::Repeat; } void keyRelease(const int keyCode) { keyStates[keyCode] = ButtonState::Released; } ButtonState getKeyState(const int keyCode) const { return keyStates[keyCode]; } bool isKeyPressed(const int keyCode) const { return keyStates[keyCode] == ButtonState::Pressed; } bool isKeyRepeated(const int keyCode) const { return keyStates[keyCode] == ButtonState::Repeat; } bool isKeyReleased(const int keyCode) const { return keyStates[keyCode] == ButtonState::Released; } private: mutable std::unordered_map<int, ButtonState> keyStates; }; CharState.h: #pragma once #include <string> class CharState { public: void charDown(const int codePoint) { charsDown += static_cast<char>(codePoint); } // TODO: make charsDown correlate to a codePoint void clear() { charsDown.clear(); } std::string getCharsDown() const { return charsDown; } private: std::string charsDown; }; InputManager.h: #pragma once #include "MouseState.h" #include "KeyboardState.h" #include "CharState.h" class InputManager { public: InputManager(EventManager& eventManager);
{ "domain": "codereview.stackexchange", "id": 44862, "lm_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++, object-oriented, design-patterns, event-handling", "url": null }
c++, object-oriented, design-patterns, event-handling class InputManager { public: InputManager(EventManager& eventManager); bool isKeyPressed(const int keyCode) const { return keyboardState.isKeyPressed(keyCode); } bool isKeyRepeated(const int keyCode) const { return keyboardState.isKeyRepeated(keyCode); } bool isKeyReleased(const int keyCode) const { return keyboardState.isKeyReleased(keyCode); } KeyboardState::ButtonState getButtonState(const int keyCode) const { return keyboardState.getKeyState(keyCode); } std::string getCharsDown() const { return charState.getCharsDown(); } void clearCharState() { charState.clear(); } bool isButtonPressed(const int keyCode) const { return mouseState.isButtonDown(keyCode); } MouseState::Position getMousePosition() const { return mouseState.getPosition(); } void setTextInputMode(const bool enabled) { textInputMode = enabled; } private: template<typename EventType> void registerListener(EventManager& eventManager, void (InputManager::* handler)(const EventType&)) { eventManager.registerListenerFor<EventType> ([this, handler](const EventType& event) { (this->*handler)(event); }); } void handleKeyboardPressEvent(const KeyboardPressEvent& event); void handleKeyboardRepeatEvent(const KeyboardRepeatEvent& event); void handleKeyboardReleaseEvent(const KeyboardReleaseEvent& event); void handleCharPressEvent(const CharPressEvent& event); void handleMouseButtonPressEvent(const MousePressEvent& event); void handleMouseButtonReleaseEvent(const MouseReleaseEvent& event); void handleMouseMoveEvent(const MouseMoveEvent& event); private: KeyboardState keyboardState; CharState charState; MouseState mouseState; bool textInputMode = false; }; InputManager.cpp: #include "InputManager.h" #include <iostream>
{ "domain": "codereview.stackexchange", "id": 44862, "lm_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++, object-oriented, design-patterns, event-handling", "url": null }
c++, object-oriented, design-patterns, event-handling bool textInputMode = false; }; InputManager.cpp: #include "InputManager.h" #include <iostream> InputManager::InputManager(EventManager& eventManager) { registerListener(eventManager, &InputManager::handleKeyboardPressEvent); registerListener(eventManager, &InputManager::handleKeyboardRepeatEvent); registerListener(eventManager, &InputManager::handleKeyboardReleaseEvent); registerListener(eventManager, &InputManager::handleCharPressEvent); registerListener(eventManager, &InputManager::handleMouseButtonPressEvent); registerListener(eventManager, &InputManager::handleMouseButtonReleaseEvent); registerListener(eventManager, &InputManager::handleMouseMoveEvent); } void InputManager::handleKeyboardPressEvent(const KeyboardPressEvent& event) { keyboardState.keyPress(event.getKeyCode()); } void InputManager::handleKeyboardRepeatEvent(const KeyboardRepeatEvent& event) { keyboardState.keyRepeat(event.getKeyCode()); } void InputManager::handleKeyboardReleaseEvent(const KeyboardReleaseEvent& event) { keyboardState.keyRelease(event.getKeyCode()); } void InputManager::handleCharPressEvent(const CharPressEvent& event) { if(textInputMode) charState.charDown(event.getCodePoint()); } void InputManager::handleMouseButtonPressEvent(const MousePressEvent& event) { mouseState.keyDown(event.getButton()); } void InputManager::handleMouseButtonReleaseEvent(const MouseReleaseEvent& event) { mouseState.keyRelease(event.getButton()); } void InputManager::handleMouseMoveEvent(const MouseMoveEvent& event) { mouseState.setPosition({ event.getMouseX(), event.getMouseY() }); }
{ "domain": "codereview.stackexchange", "id": 44862, "lm_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++, object-oriented, design-patterns, event-handling", "url": null }
c++, object-oriented, design-patterns, event-handling Answer: About diagrams While there was a time that UML diagrams were very popular, there are a lot of issues with them. The biggest issue with diagrams is that even if they start out to correctly describe the code, they will extremely quickly no longer represent the code. Unless you are meticulous in keeping the code and diagrams in sync, the diagrams are at best a suggestion of what the code actually does. Consider your second diagram: it says that KeyboardState listens to KeyEvent, however if I look at your code that is not the case. Instead, it is InputManager that listens to KeyEvents. Note that you could make it so KeyboardState registers callbacks, and make the callbacks member functions of KeyboardState. InputManager never unregisters its callbacks InputManager registers callbacks, but it never unregisters them. Consider this code: EventManager eventManager; { InputManager inputManager(eventManager); } eventManager.pushEvent<KeyboardPressEvent>(…); You should store the EventListenerIDs in InputManager, and add a destructor that calls unregisterListener() on the IDs. Ideally, this omission would have been caught at compilation time. There are various ways to make the code safer. First, you can annotate the return type of registerListenerFor() with [[nodiscard]]. Second, you could make EventListenerID itself have a destructor that unregisters the callback if the ID object is destroyed. About the use of const and mutable It's good to see you use const. This makes the code safer and more efficient. However, there are places where using const is not helpful and can even be detrimental. First, in these places it's very good to use const: const function annotations const reference/pointer parameters const reference/pointer return value const reference/pointer member variables Then there are some places where const isn't doing much:
{ "domain": "codereview.stackexchange", "id": 44862, "lm_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++, object-oriented, design-patterns, event-handling", "url": null }
c++, object-oriented, design-patterns, event-handling Then there are some places where const isn't doing much: const non-reference/pointer return values (it's good to see you've removed those) const non-reference/pointer parameters; these do nothing for the caller, and they very rarely prevent any bugs. I'm personally not sure it has enough benefits to warrant the extra noise it introduces. const auto non-reference/pointer range-for variables; auto can deduce const itself, so it's better to make sure the container you iterate over is const. const reference/pointers to temporaries (see below). Finally, there are some places where const can be harmful: const non-reference/pointer member variables. These prevent the assignment operator from working, which can be a problem. Instead of having a non-const object that contains a const member variable, it's often better to have a const object. Conversely, don't have a const object with a mutable member variable if you can just have a non-const object with a regular member variable. Normally, if I'd see a const KeyboardState keyboardState, I'd expect that nothing can modify the state it holds. I see you use this only for the std::unordered_maps, probably because you want to be able to use operator[] on it in const functions. But you should use [.find()][3] instead, that will work in const contexts without needing mutable. In publishEvent() you have this code: while(const auto& event = eventQueue.pop()) { … listener->dispatchEvent(*event.get()); … } While it works, it doesn't look very nice. eventQueue.pop() returns a std::unique_ptr by value, but event is a const reference. What luckily happens is that the lifetime of the temporary value returned by eventQueue.pop() is extended by storing reference to it. But this is completely unnecessary; you could just have written: while(auto event = eventQueue.pop())
{ "domain": "codereview.stackexchange", "id": 44862, "lm_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++, object-oriented, design-patterns, event-handling", "url": null }
c++, object-oriented, design-patterns, event-handling Getting access to objects stored in smart pointers *event.get() is equivalent to *(event.get()): you first ask for a pointer to the object stored in the std::unique_ptr, and then you dereference that pointer. However, you can get access to the object directly by just writing *event: listener->dispatchEvent(*event); Handling events There is a problem in your code. You expect listeners to call handle() on events to indicate they are handled and should not be passed to other listeners anymore. However, the callback functions get a const reference to the Events they handle. So they can never call handle() on the event. You could pass non-const references or make the member variable handled mutable, however there is a better way to solve this: make the callbacks return a bool or enum to indicate whether they have handled the event or not. This should then also be returned by dispatchEvent() of course. Then in publishEvent you can do something like: for (const auto& listener : listeners) { if (listener->isEventType(*event) { if (listener->dispatchEvent(*event)) break; } } Storing key and mouse button states Using std::unordered_map for storing the state of keys and mouse buttons is overkill, and not very efficient. Consider that for every entry in those maps, a separate memory allocation will be made to store the key/value pair. Instead, consider using statically sized arrays. GLFW defines GLFW_KEY_LAST for the highest possible keycode, and GLFW_MOUSE_BUTTON_LAST for the highest possible mouse button. Consider using const char* to store compile-time constant strings Your struct EventDescription stores name as a std::string. That works, but it has some unnecessary overhead. Since you only use it to assing strings known at compile time, consider using const char* instead: struct EventDescription { EventCategory category; EventType type; const char* name; }
{ "domain": "codereview.stackexchange", "id": 44862, "lm_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++, object-oriented, design-patterns, event-handling", "url": null }
c++, object-oriented, design-patterns, event-handling And of course let getTypeName() return a const char* as well. A caller can store the result in a std::string anyway if so desired.
{ "domain": "codereview.stackexchange", "id": 44862, "lm_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++, object-oriented, design-patterns, event-handling", "url": null }
python, python-3.x, unit-testing Title: Change unit-test structure to avoid try/except/finally clause Question: I have 10 or 20 tests with the same structure which I would like to improve. The test itself is nested within a try/except/finally clause to make sure that some of the variables are deleted at the end. def test_time_correction(): """Test time_correction method.""" sinfo = StreamInfo("test", "", 2, 0.0, "int8", uuid.uuid4().hex[:6]) try: outlet = StreamOutlet(sinfo, chunk_size=3) inlet = StreamInlet(sinfo) inlet.open_stream(timeout=5) tc = inlet.time_correction(timeout=3) assert isinstance(tc, float) except Exception as error: raise error finally: try: del inlet except Exception: pass try: del outlet except Exception: pass In the example above, I have 2 variables inlet and outlet, but in other tests, the finally clause might be: finally: try: del outlet1 except Exception: pass try: del outlet2 except Exception: pass try: del outlet3 except Exception: pass Open to suggestion on how this could be improved, maybe through fixture or other means. Answer: Python uses garbage collection. Objects will be deleted automatically when they are no longer referenced. The del statement doesn't force the object to be destroyed, it just removes the variable from the scope. What your code achieves is extremely niche: if del destroys the object immediately and the object's destructor raises an exception then this exception will be ignored, rather than failing or crashing the tests. This is extremely niche because since Python is garbage collected, it doesn't have any kind of deterministic destruction. I have never seen a __del__() method (destructor) in practice, even though Python supports this feature, and it might be useful when integrating native code. See also these SO questions:
{ "domain": "codereview.stackexchange", "id": 44863, "lm_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, unit-testing", "url": null }
python, python-3.x, unit-testing What is the __del__ method and how do I call it? How do I correctly clean up a Python object? The latter post explains that if you have to perform cleanup in your code, then you should use the with statement, for which objects have to provide __enter__() and __exit__() methods per the context manager protocol. All of this means that your test is likely equivalent to: def test_time_correction(): """Test time_correction method.""" sinfo = StreamInfo("test", "", 2, 0.0, "int8", uuid.uuid4().hex[:6]) outlet = StreamOutlet(sinfo, chunk_size=3) inlet = StreamInlet(sinfo) inlet.open_stream(timeout=5) tc = inlet.time_correction(timeout=3) assert isinstance(tc, float) But it could make sense to use with-statements. For example: def test_time_correction(): """Test time_correction method.""" sinfo = StreamInfo("test", "", 2, 0.0, "int8", uuid.uuid4().hex[:6]) with sinfo.outlet(chunk_size=3) as outlet, sinfo.inlet() as inlet: inlet.open_stream(timeout=5) tc = inlet.time_correction(timeout=3) assert isinstance(tc, float) Pytest also has a feature for setting up and tearing down resources for a test, called fixtures. This feature is documented here: https://docs.pytest.org/en/stable/explanation/fixtures.html A fixture is a separate function that creates and tears down a value that is needed by a test function. Fixtures are invoked by giving the test function a parameter with a corresponding name. This is mostly useful if the same kind of object is needed for multiple test cases. For example: @pytest.fixture def sinfo(): sinfo = StreamInfo("test", "", 2, 0.0, "int8", uuid.uuid4().hex[:6]) yield sinfo clean_up(sinfo) @pytest.fixture def inlet(sinfo): inlet = StreamInlet(sinfo) inlet.open_stream(timeout=5) yield inlet clean_up(inlet) @pytest.fixture def outlet(sinfo): outlet = StreamOutlet(sinfo, chunk_size=3) yield outlet clean_up(outlet)
{ "domain": "codereview.stackexchange", "id": 44863, "lm_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, unit-testing", "url": null }
python, python-3.x, unit-testing def test_time_correction(inlet, outlet): """Test time_correction method.""" tc = inlet.time_correction(timeout=3) assert isinstance(tc, float)
{ "domain": "codereview.stackexchange", "id": 44863, "lm_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, unit-testing", "url": null }
c++, recursion, template, c++20, constrained-templates Title: A recursive_reduce_all Template Function Implementation in C++ Question: This is a follow-up question for A recursive_sum Template Function Implementation with Unwrap Level in C++ and A recursive_unwrap_type_t Struct Implementation in C++. Considering the answer provided by G. Sliepen: Make it more generic Summing is a very specific operation. What if you want to calculate the product of all elements instead? Or get the minimum or maximum value? Instead of hardcoding the operation, create a recursive_reduce() that works like std::reduce(). You can still have it sum by default if you don't specify which operation to perform. I am trying to implement recursive_reduce_all() template function in C++ which performs operation on input container exhaustively. The test cases includes: Pure recursive_reduce_all function test with nested std::vectors recursive_reduce_all function test with execution policies recursive_reduce_all function test with initial value recursive_reduce_all function test with execution policies and initial value recursive_reduce_all function test with initial value and specified operation recursive_reduce_all function test with execution policies, initial value and specified operation (in generic lambda) The experimental implementation recursive_reduce_all() template function implementation /* recursive_reduce_all template function performs operation on input container exhaustively */ template<arithmetic T> constexpr auto recursive_reduce_all(const T& input) { return input; } template<std::ranges::input_range T> requires (arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> && recursive_depth<T>() == 1) constexpr auto recursive_reduce_all(const T& input) { return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input)); }
{ "domain": "codereview.stackexchange", "id": 44864, "lm_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, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // overload for std::array template<template<class, std::size_t> class Container, typename T, std::size_t N> requires (arithmetic<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> && recursive_depth<Container<T, N>>() == 1) constexpr auto recursive_reduce_all(const Container<T, N>& input) { return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input)); } template<std::ranges::input_range T> requires (arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::ranges::input_range<recursive_unwrap_type_t<1, T>>) constexpr auto recursive_reduce_all(const T& input) { auto result = recursive_reduce_all( UL::recursive_transform<recursive_depth<T>() - 1>(input, [](auto&& element){ return recursive_reduce_all(element); }) ); return result; } // recursive_reduce_all template function with execution policy template<class ExPo, arithmetic T> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input) { return input; } template<class ExPo, std::ranges::input_range T> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> && recursive_depth<T>() == 1) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input) { return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input)); }
{ "domain": "codereview.stackexchange", "id": 44864, "lm_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, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // recursive_reduce_all template function with execution policy, overload for std::array template<class ExPo, template<class, std::size_t> class Container, typename T, std::size_t N> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && arithmetic<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> && recursive_depth<Container<T, N>>() == 1) constexpr auto recursive_reduce_all(ExPo execution_policy, const Container<T, N>& input) { return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input)); } template<class ExPo, std::ranges::input_range T> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::ranges::input_range<recursive_unwrap_type_t<1, T>>) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input) { auto result = recursive_reduce_all( UL::recursive_transform<recursive_depth<T>() - 1>( execution_policy, input, [&](auto&& element){ return recursive_reduce_all(execution_policy, element); } ) ); return result; } // recursive_reduce_all template function with initial value template<arithmetic T> constexpr auto recursive_reduce_all(const T& input1, const T& input2) { return input1 + input2; } template<std::ranges::input_range T, class TI> requires (arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> && recursive_depth<T>() == 1) constexpr auto recursive_reduce_all(const T& input, TI init) { return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input), init); }
{ "domain": "codereview.stackexchange", "id": 44864, "lm_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, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // recursive_reduce_all template function with initial value, overload for std::array template<template<class, std::size_t> class Container, typename T, std::size_t N, class TI> requires (arithmetic<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> && std::same_as<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, TI> && recursive_depth<Container<T, N>>() == 1) constexpr auto recursive_reduce_all(const Container<T, N>& input, TI init) { return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input), init); } template<std::ranges::input_range T, class TI> requires (arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::ranges::input_range<recursive_unwrap_type_t<1, T>> && std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI>) constexpr auto recursive_reduce_all(const T& input, TI init) { auto result = init + recursive_reduce_all( UL::recursive_transform<recursive_depth<T>() - 1>( input, [&](auto&& element){ return recursive_reduce_all(element); }) ); return result; } // recursive_reduce_all template function with execution policy and initial value template<class ExPo, arithmetic T> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input1, const T& input2) { return input1 + input2; }
{ "domain": "codereview.stackexchange", "id": 44864, "lm_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, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<class ExPo, std::ranges::input_range T, class TI> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> && recursive_depth<T>() == 1) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input, TI init) { return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), init); } // recursive_reduce_all template function with execution policy and initial value, overload for std::array template<class ExPo, template<class, std::size_t> class Container, typename T, std::size_t N, class TI> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && arithmetic<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> && std::same_as<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, TI> && recursive_depth<Container<T, N>>() == 1) constexpr auto recursive_reduce_all(ExPo execution_policy, const Container<T, N>& input, TI init) { return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), init); }
{ "domain": "codereview.stackexchange", "id": 44864, "lm_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, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<class ExPo, std::ranges::input_range T, class TI> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::ranges::input_range<recursive_unwrap_type_t<1, T>> && std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI>) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input, TI init) { auto result = init + recursive_reduce_all( UL::recursive_transform<recursive_depth<T>() - 1>( execution_policy, input, [&](auto&& element){ return recursive_reduce_all(execution_policy, element); }) ); return result; } // recursive_reduce_all template function with initial value and specified operation template<arithmetic T, class BinaryOp> requires (std::regular_invocable<BinaryOp, T, T>) constexpr auto recursive_reduce_all(const T& input1, const T& input2, BinaryOp binary_op) { return std::invoke(binary_op, input1, input2); } template<std::ranges::input_range T, class TI, class BinaryOp> requires (arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> && recursive_depth<T>() == 1 && std::regular_invocable< BinaryOp, recursive_unwrap_type_t<recursive_depth<T>(),T>, recursive_unwrap_type_t<recursive_depth<T>(), T>> ) constexpr auto recursive_reduce_all(const T& input, TI init, BinaryOp binary_op) { return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input), init, binary_op); }
{ "domain": "codereview.stackexchange", "id": 44864, "lm_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, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // recursive_reduce_all template function with initial value and specified operation, overload for std::array template<template<class, std::size_t> class Container, typename T, std::size_t N, class TI, class BinaryOp> requires (arithmetic<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> && std::same_as<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, TI> && recursive_depth<Container<T, N>>() == 1 && std::regular_invocable< BinaryOp, recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> ) constexpr auto recursive_reduce_all(const Container<T, N>& input, TI init, BinaryOp binary_op) { return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input), init, binary_op); } template<std::ranges::input_range T, class TI, class BinaryOp> requires (arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::ranges::input_range<recursive_unwrap_type_t<1, T>> && std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> && std::regular_invocable< BinaryOp, recursive_unwrap_type_t<recursive_depth<T>(),T>, recursive_unwrap_type_t<recursive_depth<T>(), T>> ) constexpr auto recursive_reduce_all(const T& input, TI init, BinaryOp binary_op) { auto result = init + recursive_reduce_all( UL::recursive_transform<recursive_depth<T>() - 1>( input, [&](auto&& element){ return recursive_reduce_all(element, init, binary_op); }) ); return result; }
{ "domain": "codereview.stackexchange", "id": 44864, "lm_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, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // recursive_reduce_all template function with execution policy, initial value and specified operation template<class ExPo, arithmetic T, class BinaryOp> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && std::regular_invocable<BinaryOp, T, T>) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input1, const T& input2, BinaryOp binary_op) { return std::invoke(binary_op, input1, input2); } template<class ExPo, std::ranges::input_range T, class TI, class BinaryOp> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> && recursive_depth<T>() == 1 && std::regular_invocable< BinaryOp, recursive_unwrap_type_t<recursive_depth<T>(),T>, recursive_unwrap_type_t<recursive_depth<T>(), T>> ) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input, TI init, BinaryOp binary_op) { return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), init, binary_op); }
{ "domain": "codereview.stackexchange", "id": 44864, "lm_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, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // recursive_reduce_all template function with execution policy, initial value and specified operation, overload for std::array template<class ExPo, template<class, std::size_t> class Container, typename T, std::size_t N, class TI, class BinaryOp> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && arithmetic<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> && std::same_as<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, TI> && recursive_depth<Container<T, N>>() == 1 && std::regular_invocable< BinaryOp, recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> ) constexpr auto recursive_reduce_all(ExPo execution_policy, const Container<T, N>& input, TI init, BinaryOp binary_op) { return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), init, binary_op); }
{ "domain": "codereview.stackexchange", "id": 44864, "lm_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, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<class ExPo, std::ranges::input_range T, class TI, class BinaryOp> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::ranges::input_range<recursive_unwrap_type_t<1, T>> && std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> && std::regular_invocable< BinaryOp, recursive_unwrap_type_t<recursive_depth<T>(),T>, recursive_unwrap_type_t<recursive_depth<T>(), T>> ) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input, TI init, BinaryOp binary_op) { auto result = init + recursive_reduce_all( UL::recursive_transform<recursive_depth<T>() - 1>( execution_policy, input, [&](auto&& element){ return recursive_reduce_all(execution_policy, element, init, binary_op); }) ); return result; } Full Testing Code The full testing code: // A `recursive_reduce_all` Template Function Implementation in C++ #include <algorithm> #include <array> #include <cassert> #include <chrono> #include <complex> #include <concepts> #include <deque> #include <execution> #include <exception> #include <functional> #include <iomanip> #include <iostream> #include <iterator> #include <list> #include <map> #include <mutex> #include <numeric> #include <optional> #include <queue> #include <ranges> #include <stack> #include <stdexcept> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <variant> #include <vector> // is_reservable concept template<class T> concept is_reservable = requires(T input) { input.reserve(1); }; // is_sized concept, https://codereview.stackexchange.com/a/283581/231235 template<class T> concept is_sized = requires(T x) { std::size(x); }; // Reference: https://stackoverflow.com/a/58067611/6667035 template <typename T> concept arithmetic = std::is_arithmetic_v<T>;
{ "domain": "codereview.stackexchange", "id": 44864, "lm_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, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // recursive_depth function implementation template<typename T> constexpr std::size_t recursive_depth() { return 0; } template<std::ranges::input_range Range> constexpr std::size_t recursive_depth() { return recursive_depth<std::ranges::range_value_t<Range>>() + 1; } // recursive_variadic_invoke_result_t implementation template<std::size_t, typename, typename, typename...> struct recursive_variadic_invoke_result { }; template<typename F, class...Ts1, template<class...>class Container1, typename... Ts> struct recursive_variadic_invoke_result<1, F, Container1<Ts1...>, Ts...> { using type = Container1<std::invoke_result_t<F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>>; }; template<std::size_t unwrap_level, typename F, class...Ts1, template<class...>class Container1, typename... Ts> requires ( std::ranges::input_range<Container1<Ts1...>> && requires { typename recursive_variadic_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges struct recursive_variadic_invoke_result<unwrap_level, F, Container1<Ts1...>, Ts...> { using type = Container1< typename recursive_variadic_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>... >::type>; }; template<std::size_t unwrap_level, typename F, typename T1, typename... Ts> using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type; // recursive_unwrap_type_t struct implementation template<std::size_t, typename, typename...> struct recursive_unwrap_type { };
{ "domain": "codereview.stackexchange", "id": 44864, "lm_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, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<class...Ts1, template<class...>class Container1, typename... Ts> struct recursive_unwrap_type<1, Container1<Ts1...>, Ts...> { using type = std::ranges::range_value_t<Container1<Ts1...>>; }; template<std::size_t unwrap_level, class...Ts1, template<class...>class Container1, typename... Ts> requires ( std::ranges::input_range<Container1<Ts1...>> && requires { typename recursive_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges struct recursive_unwrap_type<unwrap_level, Container1<Ts1...>, Ts...> { using type = typename recursive_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container1<Ts1...>> >::type; }; template<std::size_t unwrap_level, typename T1, typename... Ts> using recursive_unwrap_type_t = typename recursive_unwrap_type<unwrap_level, T1, Ts...>::type; // recursive_array_unwrap_type struct implementation, https://stackoverflow.com/a/76347485/6667035 template<std::size_t, typename> struct recursive_array_unwrap_type { }; template<template<class, std::size_t> class Container, typename T, std::size_t N> struct recursive_array_unwrap_type<1, Container<T, N>> { using type = std::ranges::range_value_t<Container<T, N>>; };
{ "domain": "codereview.stackexchange", "id": 44864, "lm_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, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<std::size_t unwrap_level, template<class, std::size_t> class Container, typename T, std::size_t N> requires ( std::ranges::input_range<Container<T, N>> && requires { typename recursive_array_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges struct recursive_array_unwrap_type<unwrap_level, Container<T, N>> { using type = typename recursive_array_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container<T, N>> >::type; }; template<std::size_t unwrap_level, class Container> using recursive_array_unwrap_type_t = typename recursive_array_unwrap_type<unwrap_level, Container>::type; // https://codereview.stackexchange.com/a/253039/231235 template<template<class...> class Container = std::vector, std::size_t dim, class T> constexpr auto n_dim_container_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { return Container(times, n_dim_container_generator<Container, dim - 1, T>(input, times)); } } namespace UL // unwrap_level { template< std::ranges::input_range Container, std::copy_constructible F> requires (std::ranges::view<Container>&& std::is_object_v<F>) constexpr auto make_view(const Container& input, const F& f) noexcept { return std::ranges::transform_view( input, [&f](const auto&& element) constexpr { return recursive_transform(element, f ); } ); }
{ "domain": "codereview.stackexchange", "id": 44864, "lm_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, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates /* Override make_view to catch dangling references. A borrowed range is * safe from dangling.. */ template <std::ranges::input_range T> requires (!std::ranges::borrowed_range<T>) constexpr std::ranges::dangling make_view(T&&) noexcept { return std::ranges::dangling(); }
{ "domain": "codereview.stackexchange", "id": 44864, "lm_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, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // clone_empty_container template function implementation template< std::size_t unwrap_level = 1, std::ranges::input_range Container, std::copy_constructible F> requires (std::ranges::view<Container>&& std::is_object_v<F>) constexpr auto clone_empty_container(const Container& input, const F& f) noexcept { const auto view = make_view(input, f); recursive_variadic_invoke_result<unwrap_level, F, Container> output(std::span{input}); return output; } // recursive_transform template function implementation (the version with unwrap_level template parameter) template< std::size_t unwrap_level = 1, class T, std::copy_constructible F> requires (unwrap_level <= recursive_depth<T>() && // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235 std::ranges::view<T>&& std::is_object_v<F>) constexpr auto recursive_transform(const T& input, const F& f) { if constexpr (unwrap_level > 0) { auto output = clone_empty_container(input, f); if constexpr (is_reservable<decltype(output)>&& is_sized<decltype(input)>) { output.reserve(input.size()); std::ranges::transform( input, std::ranges::begin(output), [&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); } ); } else { std::ranges::transform( input, std::inserter(output, std::ranges::end(output)), [&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); } ); } return output; }
{ "domain": "codereview.stackexchange", "id": 44864, "lm_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, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates ); } return output; } else if constexpr(std::regular_invocable<F, T>) { return std::invoke(f, input); } else { static_assert(!std::regular_invocable<F, T>, "Uninvocable?"); } }
{ "domain": "codereview.stackexchange", "id": 44864, "lm_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, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates /* This overload of recursive_transform is to support std::array */ template< std::size_t unwrap_level = 1, template<class, std::size_t> class Container, typename T, std::size_t N, typename F > requires (std::ranges::input_range<Container<T, N>>) constexpr auto recursive_transform(const Container<T, N>& input, const F& f) { Container<recursive_variadic_invoke_result_t<unwrap_level, F, T>, N> output; std::ranges::transform( input, std::ranges::begin(output), [&f](auto&& element){ return recursive_transform<unwrap_level - 1>(element, f); } ); return output; } // recursive_transform function implementation (the version with unwrap_level, without using view) template<std::size_t unwrap_level = 1, class T, class F> requires (!std::ranges::view<T>) constexpr auto recursive_transform(const T& input, const F& f) { if constexpr (unwrap_level > 0) { static_assert(unwrap_level <= recursive_depth<T>(), "unwrap level higher than recursion depth of input"); // trying to handle incorrect unwrap levels more gracefully recursive_variadic_invoke_result_t<unwrap_level, F, T> output{}; std::ranges::transform( input, // passing a range to std::ranges::transform() std::inserter(output, std::ranges::end(output)), [&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); } ); return output; } else { return std::invoke(f, input); // use std::invoke() } }
{ "domain": "codereview.stackexchange", "id": 44864, "lm_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, template, c++20, constrained-templates", "url": null }