text stringlengths 1 2.12k | source dict |
|---|---|
performance, c, hash-map, c99
| | (6) following ‘true’ branch...
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 8
|
| 10 | (x < minl ? minl : (x > maxl ? maxl : x))
| | ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (8) following ‘true’ branch...
280098.c:129:17: note: in expansion of macro ‘CGL_utils_clamp’
| 129 | *key_size = CGL_utils_clamp(*key_size, 1, CGL_HASHTABLE_MAX_KEY_SIZE);
| | ^~~~~~~~~~~~~~~
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 9
|
| 129 | *key_size = CGL_utils_clamp(*key_size, 1, CGL_HASHTABLE_MAX_KEY_SIZE);
| | ^~~~~~~~~
| | |
| | (9) ...to here
280098.c:10:48: note: in definition of macro ‘CGL_utils_clamp’
| 10 | (x < minl ? minl : (x > maxl ? maxl : x))
| | ^
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 10
|
| 130 | uint32_t hash = table->hash_function(key, *key_size);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (10) calling ‘CGL_utils_super_fast_hash’ from ‘__CGL_hashtable_get_key_size_and_table_index’
|
+--> ‘CGL_utils_super_fast_hash’: events 11-14 | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
|
+--> ‘CGL_utils_super_fast_hash’: events 11-14
|
| 42 | uint32_t CGL_utils_super_fast_hash(const void* dat, size_t len)
| | ^~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (11) entry to ‘CGL_utils_super_fast_hash’
|......
| 49 | if (len <= 0 || data == NULL) return 0;
| | ~
| | |
| | (12) following ‘false’ branch...
| 50 |
| 51 | rem = len & 3;
| | ~~~~~~~
| | |
| | (13) ...to here
|......
| 55 | for (;len > 0; len--) {
| | ~~~~~~~
| | |
| | (14) following ‘true’ branch (when ‘len != 0’)...
|
‘CGL_utils_super_fast_hash’: event 15
|
| 38 | #define CGL_get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
| | ^
| | |
| | (15) ...to here
280098.c:56:22: note: in expansion of macro ‘CGL_get16bits’
| 56 | hash += CGL_get16bits (data); | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
| 56 | hash += CGL_get16bits (data);
| | ^~~~~~~~~~~~~
|
‘CGL_utils_super_fast_hash’: events 16-17
|
| 64 | switch (rem) {
| | ^~~~~~
| | |
| | (16) following ‘default:’ branch...
|......
| 80 | hash ^= hash << 3;
| | ~~~~~~~~~
| | |
| | (17) ...to here
|
<------+
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 18
|
| 130 | uint32_t hash = table->hash_function(key, *key_size);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (18) returning to ‘__CGL_hashtable_get_key_size_and_table_index’ from ‘CGL_utils_super_fast_hash’
|
<------+
|
‘CGL_hashtable_set’: events 19-20
|
| 173 | __CGL_hashtable_get_key_size_and_table_index(table, &key_size, &hash_table_index, key);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (19) returning to ‘CGL_hashtable_set’ from ‘__CGL_hashtable_get_key_size_and_table_index’
| 174 | CGL_hashtable_entry* entry_ptr = __CGL_hashtable_get_entry_ptr(table, key);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (20) calling ‘__CGL_hashtable_get_entry_ptr’ from ‘CGL_hashtable_set’
|
+--> ‘__CGL_hashtable_get_entry_ptr’: events 21-22
|
| 134 | static CGL_hashtable_entry* __CGL_hashtable_get_entry_ptr(CGL_hashtable* table, const void* key)
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (21) entry to ‘__CGL_hashtable_get_entry_ptr’
|......
| 137 | __CGL_hashtable_get_key_size_and_table_index(table, &key_size, &hash_table_index, key);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (22) calling ‘__CGL_hashtable_get_key_size_and_table_index’ from ‘__CGL_hashtable_get_entry_ptr’
|
+--> ‘__CGL_hashtable_get_key_size_and_table_index’: events 23-25
|
| 125 | static void __CGL_hashtable_get_key_size_and_table_index(CGL_hashtable* table, size_t* key_size, size_t* hash_table_index, const void* key)
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (23) entry to ‘__CGL_hashtable_get_key_size_and_table_index’
|......
| 128 | if(*key_size == 0) *key_size = strlen((const char*)key);
| | ~ ~~~~~~~~~~~~~~~~~~~~~~~~ | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
| | ~ ~~~~~~~~~~~~~~~~~~~~~~~~
| | | |
| | | (25) ...to here
| | (24) following ‘true’ branch...
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 26
|
| 10 | (x < minl ? minl : (x > maxl ? maxl : x))
| | ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (26) following ‘true’ branch...
280098.c:129:17: note: in expansion of macro ‘CGL_utils_clamp’
| 129 | *key_size = CGL_utils_clamp(*key_size, 1, CGL_HASHTABLE_MAX_KEY_SIZE);
| | ^~~~~~~~~~~~~~~
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 27
|
| 129 | *key_size = CGL_utils_clamp(*key_size, 1, CGL_HASHTABLE_MAX_KEY_SIZE);
| | ^~~~~~~~~
| | |
| | (27) ...to here
280098.c:10:48: note: in definition of macro ‘CGL_utils_clamp’
| 10 | (x < minl ? minl : (x > maxl ? maxl : x))
| | ^
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 28
| | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
|
| 130 | uint32_t hash = table->hash_function(key, *key_size);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (28) calling ‘CGL_utils_super_fast_hash’ from ‘__CGL_hashtable_get_key_size_and_table_index’
|
+--> ‘CGL_utils_super_fast_hash’: events 29-32
|
| 42 | uint32_t CGL_utils_super_fast_hash(const void* dat, size_t len)
| | ^~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (29) entry to ‘CGL_utils_super_fast_hash’
|......
| 49 | if (len <= 0 || data == NULL) return 0;
| | ~
| | |
| | (30) following ‘false’ branch...
| 50 |
| 51 | rem = len & 3;
| | ~~~~~~~
| | |
| | (31) ...to here
|......
| 55 | for (;len > 0; len--) {
| | ~~~~~~~
| | |
| | (32) following ‘true’ branch (when ‘len != 0’)...
|
‘CGL_utils_super_fast_hash’: event 33
| | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
|
| 38 | #define CGL_get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
| | ^
| | |
| | (33) ...to here
280098.c:56:22: note: in expansion of macro ‘CGL_get16bits’
| 56 | hash += CGL_get16bits (data);
| | ^~~~~~~~~~~~~
|
‘CGL_utils_super_fast_hash’: events 34-35
|
| 64 | switch (rem) {
| | ^~~~~~
| | |
| | (34) following ‘default:’ branch...
|......
| 80 | hash ^= hash << 3;
| | ~~~~~~~~~
| | |
| | (35) ...to here
|
<------+
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 36
|
| 130 | uint32_t hash = table->hash_function(key, *key_size);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | | | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
| | |
| | (36) returning to ‘__CGL_hashtable_get_key_size_and_table_index’ from ‘CGL_utils_super_fast_hash’
|
<------+
|
‘__CGL_hashtable_get_entry_ptr’: event 37
|
| 137 | __CGL_hashtable_get_key_size_and_table_index(table, &key_size, &hash_table_index, key);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (37) returning to ‘__CGL_hashtable_get_entry_ptr’ from ‘__CGL_hashtable_get_key_size_and_table_index’
|
<------+
|
‘CGL_hashtable_set’: events 38-39
|
| 174 | CGL_hashtable_entry* entry_ptr = __CGL_hashtable_get_entry_ptr(table, key);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (38) returning to ‘CGL_hashtable_set’ from ‘__CGL_hashtable_get_entry_ptr’
| 175 | if(entry_ptr)
| | ~
| | |
| | (39) following ‘false’ branch (when ‘entry_ptr’ is NULL)...
|
‘CGL_hashtable_set’: events 40-41
|
| 188 | entry.set = true;
| | ^
| | |
| | (40) ...to here
|......
| 194 | if(value_size > 0)
| | ~
| | |
| | (41) following ‘true’ branch (when ‘value_size != 0’)...
|
‘CGL_hashtable_set’: event 42 | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
|
‘CGL_hashtable_set’: event 42
|
| 12 | #define CGL_malloc(size) malloc(size)
| | ^~~~~~~~~~~~
| | |
| | (42) ...to here
280098.c:196:27: note: in expansion of macro ‘CGL_malloc’
| 196 | entry.value = CGL_malloc(value_size);
| | ^~~~~~~~~~
|
‘CGL_hashtable_set’: event 43
|
| 12 | #define CGL_malloc(size) malloc(size)
| | ^~~~~~~~~~~~
| | |
| | (43) this call could return NULL
280098.c:196:27: note: in expansion of macro ‘CGL_malloc’
| 196 | entry.value = CGL_malloc(value_size);
| | ^~~~~~~~~~
|
‘CGL_hashtable_set’: event 44
|
| 197 | memcpy(entry.value, value, value_size);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (44) argument 1 (‘entry.value’) from (43) could be NULL where non-null expected
|
/usr/include/string.h:43:14: note: argument 1 of ‘memcpy’ must be non-null
43 | extern void *memcpy (void *__restrict __dest, const void *__restrict __src,
| ^~~~~~
280098.c:205:34: warning: leak of ‘<unknown>’ [CWE-401] [-Wanalyzer-malloc-leak]
205 | memcpy(entry_to_place->next_entry, &entry, sizeof(CGL_hashtable_entry));
| ~~~~~~~~~~~~~~^~~~~~~~~~~~
‘main’: events 1-2
|
| 250 | int main (void) {
| | ^~~~
| | |
| | (1) entry to ‘main’
|......
| 255 | CGL_hashtable_set(table, "Name", "Jaysmito", 9); | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
|......
| 255 | CGL_hashtable_set(table, "Name", "Jaysmito", 9);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (2) calling ‘CGL_hashtable_set’ from ‘main’
|
+--> ‘CGL_hashtable_set’: events 3-4
|
| 170 | void CGL_hashtable_set(CGL_hashtable* table, const void* key, const void* value, size_t value_size)
| | ^~~~~~~~~~~~~~~~~
| | |
| | (3) entry to ‘CGL_hashtable_set’
|......
| 173 | __CGL_hashtable_get_key_size_and_table_index(table, &key_size, &hash_table_index, key);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (4) calling ‘__CGL_hashtable_get_key_size_and_table_index’ from ‘CGL_hashtable_set’
|
+--> ‘__CGL_hashtable_get_key_size_and_table_index’: events 5-7
|
| 125 | static void __CGL_hashtable_get_key_size_and_table_index(CGL_hashtable* table, size_t* key_size, size_t* hash_table_index, const void* key)
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (5) entry to ‘__CGL_hashtable_get_key_size_and_table_index’
|......
| 128 | if(*key_size == 0) *key_size = strlen((const char*)key);
| | ~ ~~~~~~~~~~~~~~~~~~~~~~~~
| | | |
| | | (7) ...to here
| | (6) following ‘true’ branch...
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 8
| | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
‘__CGL_hashtable_get_key_size_and_table_index’: event 8
|
| 10 | (x < minl ? minl : (x > maxl ? maxl : x))
| | ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (8) following ‘true’ branch...
280098.c:129:17: note: in expansion of macro ‘CGL_utils_clamp’
| 129 | *key_size = CGL_utils_clamp(*key_size, 1, CGL_HASHTABLE_MAX_KEY_SIZE);
| | ^~~~~~~~~~~~~~~
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 9
|
| 129 | *key_size = CGL_utils_clamp(*key_size, 1, CGL_HASHTABLE_MAX_KEY_SIZE);
| | ^~~~~~~~~
| | |
| | (9) ...to here
280098.c:10:48: note: in definition of macro ‘CGL_utils_clamp’
| 10 | (x < minl ? minl : (x > maxl ? maxl : x))
| | ^
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 10
|
| 130 | uint32_t hash = table->hash_function(key, *key_size);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (10) calling ‘CGL_utils_super_fast_hash’ from ‘__CGL_hashtable_get_key_size_and_table_index’
|
+--> ‘CGL_utils_super_fast_hash’: events 11-14
| | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
+--> ‘CGL_utils_super_fast_hash’: events 11-14
|
| 42 | uint32_t CGL_utils_super_fast_hash(const void* dat, size_t len)
| | ^~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (11) entry to ‘CGL_utils_super_fast_hash’
|......
| 49 | if (len <= 0 || data == NULL) return 0;
| | ~
| | |
| | (12) following ‘false’ branch...
| 50 |
| 51 | rem = len & 3;
| | ~~~~~~~
| | |
| | (13) ...to here
|......
| 55 | for (;len > 0; len--) {
| | ~~~~~~~
| | |
| | (14) following ‘true’ branch (when ‘len != 0’)...
|
‘CGL_utils_super_fast_hash’: event 15
|
| 38 | #define CGL_get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
| | ^
| | |
| | (15) ...to here
280098.c:56:22: note: in expansion of macro ‘CGL_get16bits’
| 56 | hash += CGL_get16bits (data); | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
| 56 | hash += CGL_get16bits (data);
| | ^~~~~~~~~~~~~
|
‘CGL_utils_super_fast_hash’: events 16-17
|
| 64 | switch (rem) {
| | ^~~~~~
| | |
| | (16) following ‘default:’ branch...
|......
| 80 | hash ^= hash << 3;
| | ~~~~~~~~~
| | |
| | (17) ...to here
|
<------+
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 18
|
| 130 | uint32_t hash = table->hash_function(key, *key_size);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (18) returning to ‘__CGL_hashtable_get_key_size_and_table_index’ from ‘CGL_utils_super_fast_hash’
|
<------+
|
‘CGL_hashtable_set’: events 19-20
|
| 173 | __CGL_hashtable_get_key_size_and_table_index(table, &key_size, &hash_table_index, key);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (19) returning to ‘CGL_hashtable_set’ from ‘__CGL_hashtable_get_key_size_and_table_index’
| 174 | CGL_hashtable_entry* entry_ptr = __CGL_hashtable_get_entry_ptr(table, key);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (20) calling ‘__CGL_hashtable_get_entry_ptr’ from ‘CGL_hashtable_set’
|
+--> ‘__CGL_hashtable_get_entry_ptr’: events 21-22
|
| 134 | static CGL_hashtable_entry* __CGL_hashtable_get_entry_ptr(CGL_hashtable* table, const void* key)
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (21) entry to ‘__CGL_hashtable_get_entry_ptr’
|......
| 137 | __CGL_hashtable_get_key_size_and_table_index(table, &key_size, &hash_table_index, key);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (22) calling ‘__CGL_hashtable_get_key_size_and_table_index’ from ‘__CGL_hashtable_get_entry_ptr’
|
+--> ‘__CGL_hashtable_get_key_size_and_table_index’: events 23-25
|
| 125 | static void __CGL_hashtable_get_key_size_and_table_index(CGL_hashtable* table, size_t* key_size, size_t* hash_table_index, const void* key)
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (23) entry to ‘__CGL_hashtable_get_key_size_and_table_index’
|......
| 128 | if(*key_size == 0) *key_size = strlen((const char*)key);
| | ~ ~~~~~~~~~~~~~~~~~~~~~~~~ | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
| | ~ ~~~~~~~~~~~~~~~~~~~~~~~~
| | | |
| | | (25) ...to here
| | (24) following ‘true’ branch...
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 26
|
| 10 | (x < minl ? minl : (x > maxl ? maxl : x))
| | ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (26) following ‘true’ branch...
280098.c:129:17: note: in expansion of macro ‘CGL_utils_clamp’
| 129 | *key_size = CGL_utils_clamp(*key_size, 1, CGL_HASHTABLE_MAX_KEY_SIZE);
| | ^~~~~~~~~~~~~~~
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 27
|
| 129 | *key_size = CGL_utils_clamp(*key_size, 1, CGL_HASHTABLE_MAX_KEY_SIZE);
| | ^~~~~~~~~
| | |
| | (27) ...to here
280098.c:10:48: note: in definition of macro ‘CGL_utils_clamp’
| 10 | (x < minl ? minl : (x > maxl ? maxl : x))
| | ^
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 28
| | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
|
| 130 | uint32_t hash = table->hash_function(key, *key_size);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (28) calling ‘CGL_utils_super_fast_hash’ from ‘__CGL_hashtable_get_key_size_and_table_index’
|
+--> ‘CGL_utils_super_fast_hash’: events 29-32
|
| 42 | uint32_t CGL_utils_super_fast_hash(const void* dat, size_t len)
| | ^~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (29) entry to ‘CGL_utils_super_fast_hash’
|......
| 49 | if (len <= 0 || data == NULL) return 0;
| | ~
| | |
| | (30) following ‘false’ branch...
| 50 |
| 51 | rem = len & 3;
| | ~~~~~~~
| | |
| | (31) ...to here
|......
| 55 | for (;len > 0; len--) {
| | ~~~~~~~
| | |
| | (32) following ‘true’ branch (when ‘len != 0’)...
|
‘CGL_utils_super_fast_hash’: event 33
| | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
|
| 38 | #define CGL_get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
| | ^
| | |
| | (33) ...to here
280098.c:56:22: note: in expansion of macro ‘CGL_get16bits’
| 56 | hash += CGL_get16bits (data);
| | ^~~~~~~~~~~~~
|
‘CGL_utils_super_fast_hash’: events 34-35
|
| 64 | switch (rem) {
| | ^~~~~~
| | |
| | (34) following ‘default:’ branch...
|......
| 80 | hash ^= hash << 3;
| | ~~~~~~~~~
| | |
| | (35) ...to here
|
<------+
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 36
|
| 130 | uint32_t hash = table->hash_function(key, *key_size);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | | | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
| | |
| | (36) returning to ‘__CGL_hashtable_get_key_size_and_table_index’ from ‘CGL_utils_super_fast_hash’
|
<------+
|
‘__CGL_hashtable_get_entry_ptr’: event 37
|
| 137 | __CGL_hashtable_get_key_size_and_table_index(table, &key_size, &hash_table_index, key);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (37) returning to ‘__CGL_hashtable_get_entry_ptr’ from ‘__CGL_hashtable_get_key_size_and_table_index’
|
<------+
|
‘CGL_hashtable_set’: events 38-39
|
| 174 | CGL_hashtable_entry* entry_ptr = __CGL_hashtable_get_entry_ptr(table, key);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (38) returning to ‘CGL_hashtable_set’ from ‘__CGL_hashtable_get_entry_ptr’
| 175 | if(entry_ptr)
| | ~
| | |
| | (39) following ‘false’ branch (when ‘entry_ptr’ is NULL)...
|
‘CGL_hashtable_set’: events 40-41
|
| 188 | entry.set = true;
| | ^
| | |
| | (40) ...to here
|......
| 194 | if(value_size > 0)
| | ~
| | |
| | (41) following ‘true’ branch (when ‘value_size != 0’)...
|
‘CGL_hashtable_set’: event 42 | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
|
‘CGL_hashtable_set’: event 42
|
| 12 | #define CGL_malloc(size) malloc(size)
| | ^~~~~~~~~~~~
| | |
| | (42) ...to here
280098.c:196:27: note: in expansion of macro ‘CGL_malloc’
| 196 | entry.value = CGL_malloc(value_size);
| | ^~~~~~~~~~
|
‘CGL_hashtable_set’: events 43-44
|
| 199 | if(table->entries[hash_table_index].set)
| | ^
| | |
| | (43) following ‘true’ branch...
| 200 | {
| 201 | CGL_hashtable_entry* entry_to_place = &table->entries[hash_table_index];
| | ~~~~~~~~~~~~~~
| | |
| | (44) ...to here
|
‘CGL_hashtable_set’: event 45
|
| 12 | #define CGL_malloc(size) malloc(size)
| | ^~~~~~~~~~~~
| | |
| | (45) allocated here
280098.c:204:64: note: in expansion of macro ‘CGL_malloc’
| 204 | entry_to_place->next_entry = (CGL_hashtable_entry*)CGL_malloc(sizeof(CGL_hashtable_entry));
| | ^~~~~~~~~~
|
‘CGL_hashtable_set’: event 46
|
| 205 | memcpy(entry_to_place->next_entry, &entry, sizeof(CGL_hashtable_entry));
| | ~~~~~~~~~~~~~~^~~~~~~~~~~~ | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
| | ~~~~~~~~~~~~~~^~~~~~~~~~~~
| | |
| | (46) ‘<unknown>’ leaks here; was allocated at (45)
| | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
Use Valgrind to help find memory errors
Valgrind is a useful tool to spot leaks, use-after-free, double-free and lots of other errors. With the provided main(), it reveals this leak:
valgrind --leak-check=full ./280098
==129433== Memcheck, a memory error detector
==129433== Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al.
==129433== Using Valgrind-3.19.0 and LibVEX; rerun with -h for copyright info
==129433== Command: ./280098
==129433==
Age : 18
Float Data : 454.485413
Name : Jaysmito
Name 2 : Jack
==129433==
==129433== HEAP SUMMARY:
==129433== in use at exit: 9 bytes in 1 blocks
==129433== total heap usage: 7 allocs, 6 frees, 2,961,086 bytes allocated
==129433==
==129433== 9 bytes in 1 blocks are definitely lost in loss record 1 of 1
==129433== at 0x48437B4: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==129433== by 0x10977F: CGL_hashtable_set (280098.c:196)
==129433== by 0x109AB2: main (280098.c:255)
==129433==
==129433== LEAK SUMMARY:
==129433== definitely lost: 9 bytes in 1 blocks
==129433== indirectly lost: 0 bytes in 0 blocks
==129433== possibly lost: 0 bytes in 0 blocks
==129433== still reachable: 0 bytes in 0 blocks
==129433== suppressed: 0 bytes in 0 blocks
==129433==
==129433== For lists of detected and suppressed errors, rerun with: -s
==129433== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Consider a singly-linked list
We take the trouble to maintain prev_entry pointers in our list nodes, but never actually use them. We could make our nodes smaller, and our code faster, by using a simpler forward-list instead. | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
c#, algorithm, combinatorics, complexity
Title: Subset sum simple iterative implementation
Question: Here is the simplest iterative implementation of Subset sum problem that I could come up with1, as a follow up to this recursive implementation of the same problem:
using System;
using System.Linq;
namespace Exercise
{
class SubsetSumBinaryNumber
{
static void Main(string[] args)
{
int[] arr = { 2, 3, 1, -1 };
PrintSet(arr, "Initial Set:");
int wantedSum = 4;
Console.WriteLine("Wanted sum = {0}", wantedSum);
FindSubsetSum(arr, wantedSum);
}
//-----------------------------------------------------------------------
/* Method: FindSubsetSum(int[] arr, int sum) */
private static void FindSubsetSum(int[] arr, int targetSum)
{
// convert to base
int toBase = 2;
// length of binary number
int length = arr.Length;
// max value of binary number with "arr.Length" digits
int iEnd = (int) Math.Pow(length, 2);
for (int number = 0; number < iEnd; number++)
{
// convert current number to binary array
bool[] binaryNumber = Enumerable.Range(1, length).Select(i => number / (1 << (length - i)) % 2 == 1).ToArray();
// sum all elements with "true" indexes
int currentSum = 0;
for (int j = 0; j < binaryNumber.Length; j++)
{
if(binaryNumber[j] == true)
{
currentSum += arr[j];
}
}
// check for sum and print if equal
if (currentSum == targetSum)
{
PrintSubSet(arr, binaryNumber);
}
}
}
}
}
Input:
-
Output:
Initial Set.
{2 ,3 ,1 ,-1}
Wanted sum = 4
(1 ,3,)
(-1 ,3 ,2) | {
"domain": "codereview.stackexchange",
"id": 43941,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, algorithm, combinatorics, complexity",
"url": null
} |
c#, algorithm, combinatorics, complexity
The algorithm is based on viewing all the combination of indexes of the initial set as a binary number (0's and 1's), then in order to go through all the combinations we simply increment through all the consecutive binary values from 0 to 2set cardinality and sum the set elements that match the 1's in the binary value, check the sum and print them if sum matches the wanted value.
Could the for loop be reduced in half if both current binary and its complement are checked simultaneously?
What is the complexity of this algorithm?
Any remarks regarding style and optimization will be appreciated.
Helper functions:
/* Method: PrintSubSet(int[] arr, bool[] subSet) */
private static void PrintSubSet(int[] arr, bool[] subSet)
{
Console.Write("(");
for (int i = 0; i < arr.Length; i++)
{
if (subSet[i] == true)
{
Console.Write(arr[i]);
if (i < arr.Length - 1)
{
Console.Write(" ,");
}
}
}
Console.WriteLine(")");
}
//----------------------------------------------------------------------
/* Method: PrintSet(int[] arr, string label = "") */
private static void PrintSet(int[] arr, string label = "")
{
Console.WriteLine(label);
Console.Write("{");
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i]);
if (i < arr.Length - 1)
{
Console.Write(" ,");
}
}
Console.WriteLine("}");
}
1. The most of the algorithms (that I could find) use recursion, dynamic programming and other fairly complex iterative approaches. | {
"domain": "codereview.stackexchange",
"id": 43941,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, algorithm, combinatorics, complexity",
"url": null
} |
c#, algorithm, combinatorics, complexity
Answer: Again has \$O(n*2^n)\$ complexity
This program, like the recursive solution in the previous question, has \$O(n*2^n)\$ complexity. It is simple to see that you iterate \$2^n\$ times, and on each iteration you compute the sum in \$O(n)\$ time.
Using Gray code to achieve \$O(2^n)\$ time
The key to reducing the run time of this iterative solution is to remove the \$O(n)\$ summation loop. You can only do this if you can compute the next sum from the previous sum in \$O(1)\$ time. Unfortunately, between one iteration and the next, up to \$n\$ numbers might need to be added/subtracted. For example, if you were on this bit pattern:
0 1 1 1 1 = arr[0] + arr[1] + arr[2] + arr[3]
The next bit pattern would be:
1 0 0 0 0 = arr[4]
You would need to add one number and subtract 4 numbers to get from the previous sum to the next sum. This is where the Gray code comes in to play. The Gray code is a numerical sequence where each number in the sequence differs from the previous by only 1 bit. So if you counted upwards using a Gray code sequence, then the next sum can be computed from the previous sum by only adding/subtracting one number.
Luckily, it is easy to count upwards in a Gray code sequence. You can just count upwards in the normal way and then convert your normal number to the corresponding Gray code number using the formula:
grayCode = n ^ (n >> 1)
Then to find the bit that changed, you can xor the new gray number with the previous one:
bitChanged = oldGray ^ newGray;
One tricky part is that you need to know the bit number of the bit that changed. Normally, I would do:
bitIndex = 31 - CLZ(bitChanged); | {
"domain": "codereview.stackexchange",
"id": 43941,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, algorithm, combinatorics, complexity",
"url": null
} |
c#, algorithm, combinatorics, complexity
where CLZ() is a builtin "count leading zeros" function. I couldn't find a builtin function in C# for that though, so I wrote my own. There are fast versions of CLZ() that can be done in constant time using a lookup table, but I decided to use a looping version. In the case of counting upwards using Gray numbers, bitChanged will be 0x1 50% of the time, 0x2 25% of the time, 0x4 12.5% of the time, etc. Because of this, the looping variant will take amortized constant time since it operates faster on smaller bit numbers.
Sample Gray code implementation
I took your program and changed two functions: FindSubsetSum() and PrintSubset(). I also added my own clz() function. Here is the modified parts of your code:
private static void FindSubsetSum(int[] arr, int targetSum)
{
int length = arr.Length;
int iEnd = 1 << length;
int currentSum = 0;
int oldGray = 0;
for (int i = 1; i < iEnd; i++)
{
int newGray = i ^ (i >> 1);
int bitChanged = oldGray ^ newGray;
int bitNumber = 31 - clz(bitChanged);
if ((newGray & bitChanged) != 0)
{
// Bit turned to 1 = Add element.
currentSum += arr[bitNumber];
}
else
{
// Bit turned to 0 = Subtract element.
currentSum -= arr[bitNumber];
}
// Check for sum and print if equal
if (currentSum == targetSum)
{
PrintSubSet(arr, newGray);
}
oldGray = newGray;
}
}
private static void PrintSubSet(int[] arr, int bits)
{
Console.Write("(");
for (int i = 0; i < arr.Length; i++)
{
if ((bits & (1 << i)) != 0)
{
Console.Write(arr[i]); | {
"domain": "codereview.stackexchange",
"id": 43941,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, algorithm, combinatorics, complexity",
"url": null
} |
c#, algorithm, combinatorics, complexity
if (i < arr.Length - 1)
{
Console.Write(" ,");
}
}
}
Console.WriteLine(")");
}
// This can be replaced with a better variant, but this variant
// will do the job for the Gray code sequence since the low
// bit numbers will appear the vast majority of the time.
private static int clz(int x)
{
int lz = 32;
while (x != 0) {
x >>= 1;
lz--;
}
return lz;
} | {
"domain": "codereview.stackexchange",
"id": 43941,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, algorithm, combinatorics, complexity",
"url": null
} |
python, python-3.x, simulation, physics
Title: Membrane protein diffusion in different confinement models
Question: I am a junior Software Engineer, C++ is usually my main jam but I started picking up Python for a research project I am doing in college. I am eager to learn as much Python syntax, tricks, best practices or software architecture in general as possible. So here is a portion of my project ~300 lines of code that simulate two types of protein movement through Brownian diffusion: diffusion in small circular domains (nanodomain simulation) and in a meshwork with compartments (hop diffusion). I hope I can get any tips and feedback on the code!
Project Structure
.
├── main.py
├── plotGenerator.py
├── requirements-dev.txt
├── simulations
│ ├── __init__.py
│ ├── hopDiffusionSimulation.py
│ ├── nanodomainSimulation.py
│ └── simulation.py
└── util.py
In Action Example
The Code
./main.py
from simulations.simulation import *
from simulations.nanodomainSimulation import *
from simulations.hopDiffusionSimulation import *
from plotGenerator import *
from util import *
#nanoDomain = Nanodomain()
hopDiffusion = HopDiffusion();
plot(hopDiffusion, SimulationType.HOPDIFFUSION)
./simulations/simulation.py
from typing import List, Tuple
import random
import numpy as np
from enum import Enum
class SimulationType(Enum):
BROWNIAN = 1
NANODOMAIN = 2
HOPDIFFUSION = 3
PATH = Tuple[List[float]]
DPI = 100
RADIUS_PADDING = 10
RADIUS = 250
CORRECTED_CANVAS_RADIUS = RADIUS - RADIUS_PADDING
TIME_PER_FRAME: float = 0.02 # 20 ms
DIFFUSION_SPEED_CORRECTION: int = 35 # arbitrary
MEMBRANE_DIFFUSION_COEFFICIENT: float = 0.1 # micrometer^2 / s
MEMBRANE_DIFFUSION_FACTOR: float = 2 * np.sqrt(MEMBRANE_DIFFUSION_COEFFICIENT * TIME_PER_FRAME)
MEMBRANE_DIFFUSION_FATOR_CORRECTED: float = MEMBRANE_DIFFUSION_FACTOR * DIFFUSION_SPEED_CORRECTION | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
class Simulation:
def __init__(self, n: int = 5):
self.numberOfParticles: int = n
self.particlesLocation: List[Tuple[int, int]] = []
self.paths: List[List[Tuple[int, int]]] = []
self.init_particles()
self.init_paths()
def init_paths(self):
self.paths.extend([[coordinate] for coordinate in self.particlesLocation])
def init_particles(self) -> None:
mem: List[Tuple] = []
def get_random_canvas_value(self) -> int:
return int(random.randint(-(CORRECTED_CANVAS_RADIUS), CORRECTED_CANVAS_RADIUS))
def rec(self, x: int = 0, y: int = 0) -> Tuple[int, int]:
x, y = [get_random_canvas_value(self) for _ in range(2)]
while (x, y) in mem:
return rec(self, x, y)
mem.append((x, y))
return x,y
self.particlesLocation.extend([rec(self) for _ in range(5)])
./simulations/hopDiffusionSimulation.py
from typing import List, Tuple
from simulations.simulation import *
from util import *
BOUNDARY_THICKNESS: int = 15
NUMBER_OF_COMPARTMENTS_PER_DIRECTION: int = 3
BOUNDARY_JUMP: int = BOUNDARY_THICKNESS
BOUNDARY_OVERFLOW: int = 20
HOP_PROBABILITY_PERCENTAGE: float = 0.15 | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
class HopDiffusion(Simulation):
def __init__(self, n: int = 5):
self.boundary_coordinates_for_plot: List[List] = []
self.boundary_coordinates: List[Tuple[Tuple]] = []
self.generate_boundaries()
super().__init__(n)
def generate_boundaries(self):
step: int = int((RADIUS << 1) / NUMBER_OF_COMPARTMENTS_PER_DIRECTION)
for i in range(6):
if i % 3 == 0: continue
horizontal: bool = i < NUMBER_OF_COMPARTMENTS_PER_DIRECTION
curr = i * step if horizontal else (i - NUMBER_OF_COMPARTMENTS_PER_DIRECTION) * step
width = BOUNDARY_THICKNESS if horizontal else (RADIUS << 1) + (BOUNDARY_OVERFLOW << 1)
height = BOUNDARY_THICKNESS if not horizontal else (RADIUS << 1) + (BOUNDARY_OVERFLOW << 1)
x = curr - RADIUS - (BOUNDARY_THICKNESS >> 1) if horizontal else -RADIUS - BOUNDARY_OVERFLOW
y = curr - RADIUS - (BOUNDARY_THICKNESS >> 1) if not horizontal else -RADIUS - BOUNDARY_OVERFLOW
self.boundary_coordinates_for_plot.append(list([x, y, width, height]))
self.boundary_coordinates.append(list([tuple((x, x + width)), tuple((y, y + height))]))
@property
def get_boundary_coordinates(self):
return self.boundary_coordinates_for_plot
def can_particle_hop_boundary_probability(self) -> bool:
return random.random() < HOP_PROBABILITY_PERCENTAGE | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
def is_particle_on_specific_boudnary(self, pos: Tuple, idx: int):
return Util.is_point_within_bounds(pos, self.boundary_coordinates[idx])
def is_particle_on_boundary(self, pos: Tuple):
return any(
Util.is_point_within_bounds(pos, bounds_of_boundary)
for bounds_of_boundary in self.boundary_coordinates
)
def is_particle_in_compartment(self, particle) -> bool:
return not self.is_particle_on_boundary(particle)
def get_surrounding_boundary_of_particle(self, pos: Tuple) -> int:
for idx, bounds_of_boundary in enumerate(self.boundary_coordinates):
if Util.is_point_within_bounds(pos, bounds_of_boundary):
return idx
return -1
def make_particle_jump(self, newPos: Tuple, x_dir: int, y_dir: int):
surrounding_boundary_idx = self.get_surrounding_boundary_of_particle(newPos)
while (self.is_particle_on_specific_boudnary(newPos, surrounding_boundary_idx)):
newPos = Util.increment_tuple_by_val(
newPos, tuple((Util.sign(x_dir), Util.sign(y_dir)))
)
newPos = Util.increment_tuple_by_val(
newPos, tuple(
(Util.sign(x_dir) * BOUNDARY_JUMP,
Util.sign(y_dir) * BOUNDARY_JUMP)
)
)
# Special case: In some instances the jump may land the particle
# on a subsequent boundary so we repeat the function. We decrement
# the particle's coordinates until it is out.
new_surrounding_boundary_idx = self.get_surrounding_boundary_of_particle(newPos)
while (self.is_particle_on_boundary(newPos)):
newPos = Util.increment_tuple_by_val(
newPos, tuple((Util.sign(-x_dir), Util.sign(-y_dir)))
)
return newPos
def update_path(self, idx: int):
x, y = self.paths[idx][-1] | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
return newPos
def update_path(self, idx: int):
x, y = self.paths[idx][-1]
assert(not self.is_particle_on_boundary(tuple((x, y))))
diffusion_factor = MEMBRANE_DIFFUSION_FATOR_CORRECTED
x_dir, y_dir = [Util.get_random_normal_direction() * diffusion_factor for _ in range(2)]
newPos = tuple((x + x_dir, y + y_dir))
if self.is_particle_on_boundary(newPos):
if self.can_particle_hop_boundary_probability():
newPos = self.make_particle_jump(newPos, x_dir, y_dir)
else:
newPos = Util.change_direction(tuple((x, y)), tuple((x_dir, y_dir)))
self.paths[idx].append(newPos)
def update(self):
for i in range(self.numberOfParticles): self.update_path(i)
def init_particles(self) -> None:
mem: List[Tuple[int, int]] = []
def get_random_canvas_value(self) -> int:
return int(random.randint(-(CORRECTED_CANVAS_RADIUS), CORRECTED_CANVAS_RADIUS))
def rec(self, x: int = 0, y: int = 0) -> Tuple[int, int]:
x, y = [get_random_canvas_value(self) for _ in range(2)]
while (x, y) in mem or self.is_particle_on_boundary(tuple((x, y))):
return rec(self, x, y)
mem.append((x, y))
return x, y
self.particlesLocation.extend([rec(self) for _ in range(5)]) | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
./simulations/nanodomainDiffusionSimulation.py
from typing import List, Tuple
from simulations.simulation import *
from util import *
NANODOMAIN_DIFFUSION_FATOR_CORRECTED: float = MEMBRANE_DIFFUSION_FATOR_CORRECTED * 0.4 # type : ignore
class Nanodomain(Simulation):
def __init__(self, n: int = 5):
super().__init__(n)
self.nanodomain_coordinates: List[Tuple[int, int]] = [
(-100, 100), (0, 0), (150, -60), (-130, -160)
]
self.nanodomain_radii: List[int] = [80, 20, 50, 140]
@property
def get_nanodomain_coordinates(self) -> List[Tuple[int, int]]:
return self.nanodomain_coordinates
@property
def get_nanodomain_radii(self) -> List[int]:
return self.nanodomain_radii
def get_nanodomain_attributes(self) -> List[Tuple]:
return list(map(
lambda coord, radius: (coord, radius),
self.get_nanodomain_coordinates,
self.get_nanodomain_radii
))
def is_particle_in_nanodomain(self, particle: Tuple) -> bool:
return any(
Util.compute_distance(particle, circle_center) <= radius
for circle_center, radius in
zip(self.get_nanodomain_coordinates, self.get_nanodomain_radii)
)
def update_path(self, idx):
x, y = self.paths[idx][-1]
diffusion_factor = NANODOMAIN_DIFFUSION_FATOR_CORRECTED if (self.is_particle_in_nanodomain((x, y))) else MEMBRANE_DIFFUSION_FATOR_CORRECTED
x_dir, y_dir = [Util.get_random_normal_direction() * diffusion_factor for _ in range(2)]
self.paths[idx].append((x + x_dir, y + y_dir))
def update(self):
[self.update_path(i) for i in range(self.numberOfParticles)]
./plotGenerator.py
from simulations.hopDiffusionSimulation import HopDiffusion
from simulations.nanodomainSimulation import Nanodomain
from simulations.simulation import *
from util import * | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
from matplotlib.animation import FuncAnimation # type: ignore
from matplotlib.pyplot import figure
import matplotlib.pyplot as plt
from typing import List, Tuple
import numpy as np
from matplotlib import rcParams # type: ignore
colors: List[str] = ['r', 'b', "orange", 'g', 'y', 'c']
markers: List[str] = ['o', 'v', '<', '>', 's', 'p']
def handle_nanodomain(ax, sim: Nanodomain):
nanodomains = [
plt.Circle( # type: ignore
*param,
color = 'black',
alpha = 0.2)
for param in sim.get_nanodomain_attributes()
]
[ax.add_patch(nanodomain) for nanodomain in nanodomains]
def handle_hop_diffusion(ax, sim: HopDiffusion):
compartments = [
plt.Rectangle( # type: ignore
tuple((param[0], param[1])),
param[2], param[3],
color = 'black',
alpha = 0.7,
clip_on = False)
for param in sim.boundary_coordinates_for_plot
]
[ax.add_patch(boundary) for boundary in compartments]
def get_coordinates_for_plot(sim, idx: int):
return Util.get_x_coordinates(sim.paths[idx]), Util.get_y_coordinates(sim.paths[idx])
def get_coordinates_for_heads(sim, idx: int):
return Util.get_last_point(sim.paths[idx])
def set_plot_parameters(ax):
ax.tick_params(axis = 'y', direction = "in", right = True, labelsize = 16, pad = 20)
ax.tick_params(axis = 'x', direction = "in", top = True, bottom = True, labelsize = 16, pad = 20)
## legends and utilities
ax.set_xlabel(r"nm", fontsize=16)
ax.set_ylabel(r"nm", fontsize=16)
## border colors
ax.patch.set_edgecolor('black')
ax.patch.set_linewidth('2')
ax.set_xlim(-RADIUS, RADIUS)
ax.set_ylim(-RADIUS, RADIUS)
def plot(sim: Simulation, type: SimulationType):
fig, ax = plt.subplots(figsize = [5, 5], dpi = DPI) # type: ignore | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
path_plots: List = [
ax.plot(
*get_coordinates_for_plot(sim, i),
markersize=15, color = colors[i])[0]
for i in range(5)
]
head_plots: List = [
ax.plot(
*get_coordinates_for_heads(sim, i),
markersize=7, color = colors[i], marker = markers[i],
markerfacecolor="white")[0]
for i in range(5)
]
def initialize_animation():
set_plot_parameters(ax)
if type == SimulationType.NANODOMAIN: handle_nanodomain(ax, sim)
elif type == SimulationType.HOPDIFFUSION: handle_hop_diffusion(ax, sim)
return path_plots
def update_animation(frame):
sim.update()
for i, plot in enumerate(path_plots):
plot.set_data(*get_coordinates_for_plot(sim, i))
for i, head_marker in enumerate(head_plots):
head_marker.set_data(*get_coordinates_for_heads(sim, i))
return path_plots
animation = FuncAnimation(
fig,
update_animation,
init_func = initialize_animation,
interval = 20
)
plt.show(block = True) # type: ignore
fig.tight_layout()
rcParams.update({'figure.autolayout': True})
./util.py
from typing import List, Tuple
import numpy as np
import random
class Util:
@staticmethod
def get_bounds(lists) -> Tuple[int, ...]:
x_min: int = min([min(elem[0]) for elem in lists])
x_max: int = max([max(elem[0]) for elem in lists])
y_min: int = min([min(elem[1]) for elem in lists])
y_max: int = max([max(elem[1]) for elem in lists])
return x_min, x_max, y_min, y_max
@staticmethod
def compute_distance(p1: Tuple, p2: Tuple) -> float:
return np.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)
@staticmethod
def get_last_point(path: List[Tuple]) -> Tuple[int, ...]:
return path[-1][0], path[-1][1] | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
@staticmethod
def get_x_coordinates(path) -> List:
return list(list(zip(*path))[0])
@staticmethod
def get_y_coordinates(path) -> List:
return list(list(zip(*path))[1])
@staticmethod
def get_random_normal_direction():
return np.random.normal() * np.random.choice([1, -1])
@staticmethod
def is_point_within_bounds(pos: Tuple, bounds: Tuple[Tuple, ...]):
x, y = pos[0], pos[1]
return x >= bounds[0][0] and x <= bounds[0][1] and y >= bounds[1][0] and y <= bounds[1][1]
@staticmethod
def sign(x):
return ((x >= 0) << 1) - 1
@staticmethod
def increment_tuple_by_val(tuple_object: Tuple, val):
tuple_object = tuple((tuple_object[0] + val[0], tuple_object[1] + val[1]))
return tuple_object
@staticmethod
def change_direction(tuple_object: Tuple, dir):
tuple_object = tuple((tuple_object[0] - dir[0], tuple_object[1] - dir[1]))
return tuple_object
Answer: Spelling: FATOR -> FACTOR, boudnary -> boundary.
Upgrade Python and then use list and tuple directly as typehints instead of the older List and Tuple.
Simplify your chained comparisons; the one for is_point_within_bounds can look like:
return (
bounds[0][0] <= x <= bounds[0][1] and
bounds[1][0] <= y <= bounds[1][1]
) | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
Having an argument called dir to change_direction shadows a built-in, dir. Name it something else, in this case direction.
You have incomplete type hints in many places. Don't leave list unspecified; fill its element type in []. Configure Mypy to disallow unspecified types.
Util should not be a class. Just put those functions in the global namespace, but then in dependent modules write import util without a from to create a containing namespace.
tuple_object is not a good name. Of course it's a tuple: you're doing the right thing in type-hinting it as such (though the type hint is incomplete). Name it according to the meaning of its contents and not its type.
You have a habit of casting sequences that don't need to be cast, as in
self.boundary_coordinates.append(list([tuple((x, x + width)), tuple((y, y + height))]))
That's really just
self.boundary_coordinates.append(
[
(x, x + width), (y, y + height),
]
)
This:
def sign(x):
return ((x >= 0) << 1) - 1
is tricky and unnecessary. Just use np.sign.
ax.patch.set_linewidth('2') will never work; that string needs to be a numeric literal.
-(CORRECTED_CANVAS_RADIUS) should not have parens.
rec exists in init_particles, so already has access to a self in closure scope; don't write it again in the signature to rec. x and y are never used in the signature either, so delete them too.
get_random_canvas_value should be moved out to a staticmethod of Simulation; and don't repeat it - stop copying and pasting code.
This loop makes no sense:
while (x, y) in mem:
return rec(self, x, y)
That's really just an if and not a while.
rec should be redesigned so that it does not recurse. This is a stack overflow waiting to happen.
This list comprehension:
x, y = [self.get_random_canvas_value() for _ in range(2)] | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
should be left as a generator () and not a list []. Likewise, all of the inner list comprehensions in get_bounds should be converted to generators; basically delete the [].
colors and markers should be tuples.
numberOfParticles should be number_of_particles by PEP8.
get_bounds is unused so delete it.
You should use floor division here:
step: int = int((RADIUS << 1) // NUMBER_OF_COMPARTMENTS_PER_DIRECTION)
Your use of << and >> in an attempt to speed up multiplication and division by two is premature optimisation, and there are areas of your program that have comparatively gigantic inefficiencies. Just do the comprehensible thing and write 2. And anyway: you have a fixed framerate. So long as that framerate is being hit, there is no point whatsoever in attempting micro-optimisation.
It would be a good idea to make get_nanodomain_coordinates a property as you have, but in that case delete "get_" since its invocation is variable-like and not method-like. However. You have variables with those names already, so do the opposite: remove @property from those methods.
You mix built-in random with np.random. Don't do that. Probably use np.random only.
Don't write no-assignment comprehensions such as [self.update_path(i) for i in range(self.n_particles)]. Just write a loop.
Comprehensions are not helping in handle_hop_diffusion. Just expand it to a regular loop:
def handle_hop_diffusion(ax: plt.Axes, sim: HopDiffusion):
for param in sim.boundary_coordinates_for_plot:
boundary = plt.Rectangle( # type: ignore
tuple((param[0], param[1])),
param[2], param[3],
color='black',
alpha=0.7,
clip_on=False,
)
ax.add_patch(boundary)
type as a parameter needs to go away. You already know the type - use isinstance() on the sim variable.
Simulation is effectively an abstract class. You need an update stub on it:
def update(self) -> None:
raise NotImplementedError() | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
This statement has no effect, so delete it:
new_surrounding_boundary_idx = self.get_surrounding_boundary_of_particle(new_pos)
You have a latent bug. for i in range(6): hard-codes the number of compartments, when that should really be derived from NUMBER_OF_COMPARTMENTS_PER_DIRECTION. The moment that that constant changes, your code will not do what you want. Likewise, for _ in range(5): hard-codes the particle count instead of using the count parameter set in n_particles.
First pass
A first pass covering much of the above looks like:
import random
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rcParams # type: ignore
from matplotlib.animation import FuncAnimation # type: ignore
DPI = 100
RADIUS_PADDING = 10
RADIUS = 250
CORRECTED_CANVAS_RADIUS = RADIUS - RADIUS_PADDING
TIME_PER_FRAME: float = 0.02 # 20 ms
DIFFUSION_SPEED_CORRECTION: int = 35 # arbitrary
MEMBRANE_DIFFUSION_COEFFICIENT: float = 0.1 # micrometer^2 / s
MEMBRANE_DIFFUSION_FACTOR: float = 2 * np.sqrt(MEMBRANE_DIFFUSION_COEFFICIENT * TIME_PER_FRAME)
MEMBRANE_DIFFUSION_FACTOR_CORRECTED: float = MEMBRANE_DIFFUSION_FACTOR * DIFFUSION_SPEED_CORRECTION
NANODOMAIN_DIFFUSION_FACTOR_CORRECTED: float = MEMBRANE_DIFFUSION_FACTOR_CORRECTED * 0.4
BOUNDARY_THICKNESS: int = 15
NUMBER_OF_COMPARTMENTS_PER_DIRECTION: int = 3
BOUNDARY_JUMP: int = BOUNDARY_THICKNESS
BOUNDARY_OVERFLOW: int = 20
HOP_PROBABILITY_PERCENTAGE: float = 0.15
colors: tuple[str, ...] = ('r', 'b', 'orange', 'g', 'y', 'c')
markers: tuple[str, ...] = ('o', 'v', '<', '>', 's', 'p')
class util: # convert this to an import of a module with global functions
@staticmethod
def compute_distance(p1: tuple[float, float], p2: tuple[float, float]) -> float:
return np.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)
@staticmethod
def get_last_point(path: list[tuple[float, float]]) -> tuple[float, float]:
return path[-1][0], path[-1][1] | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
@staticmethod
def get_x_coordinates(path: list[tuple[float, float]]) -> list[float]:
return list(list(zip(*path))[0])
@staticmethod
def get_y_coordinates(path: list[tuple[float, float]]) -> list[float]:
return list(list(zip(*path))[1])
@staticmethod
def get_random_normal_direction() -> float:
return np.random.normal() * np.random.choice([1, -1])
@staticmethod
def is_point_within_bounds(
pos: tuple[float, float],
bounds: tuple[tuple[float, float], tuple[float, float]],
) -> bool:
x, y = pos[0], pos[1]
return (
bounds[0][0] <= x <= bounds[0][1] and
bounds[1][0] <= y <= bounds[1][1]
)
@staticmethod
def increment_tuple_by_val(tuple_object: tuple[float, float], val: tuple[float, float]) -> tuple[float, float]:
return tuple_object[0] + val[0], tuple_object[1] + val[1]
@staticmethod
def change_direction(
tuple_object: tuple[float, float],
direction: tuple[float, float],
) -> tuple[float, float]:
return tuple_object[0] - direction[0], tuple_object[1] - direction[1]
class Simulation:
def __init__(self, n: int = 5) -> None:
self.n_particles: int = n
self.particle_locations: list[tuple[float, float]] = list(self.init_particles())
self.paths: list[list[tuple[float, float]]] = [
[coordinate] for coordinate in self.particle_locations
]
@staticmethod
def get_random_canvas_value() -> int:
return int(random.randint(-CORRECTED_CANVAS_RADIUS, CORRECTED_CANVAS_RADIUS))
def init_particles(self) -> set[tuple[float, float]]:
mem: set[tuple[float, float]] = set()
for _ in range(5):
while True:
pair = (self.get_random_canvas_value(), self.get_random_canvas_value())
if pair not in mem:
break
mem.add(pair)
return mem | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
return mem
def update(self) -> None:
raise NotImplementedError()
class HopDiffusion(Simulation):
def __init__(self, n: int = 5) -> None:
self.boundary_coordinates_for_plot: list[tuple[int, int, int, int]] = []
self.boundary_coordinates: list[tuple[tuple[float, float], tuple[float, float]]] = []
self.generate_boundaries()
super().__init__(n)
def generate_boundaries(self) -> None:
step: int = (RADIUS * 2) // NUMBER_OF_COMPARTMENTS_PER_DIRECTION
for i in range(6):
if i % 3 == 0:
continue
horizontal: bool = i < NUMBER_OF_COMPARTMENTS_PER_DIRECTION
curr = i * step if horizontal else (i - NUMBER_OF_COMPARTMENTS_PER_DIRECTION) * step
width = BOUNDARY_THICKNESS if horizontal else (RADIUS * 2) + (BOUNDARY_OVERFLOW * 2)
height = BOUNDARY_THICKNESS if not horizontal else (RADIUS * 2) + (BOUNDARY_OVERFLOW * 2)
x = curr - RADIUS - (BOUNDARY_THICKNESS // 2) if horizontal else -RADIUS - BOUNDARY_OVERFLOW
y = curr - RADIUS - (BOUNDARY_THICKNESS // 2) if not horizontal else -RADIUS - BOUNDARY_OVERFLOW
self.boundary_coordinates_for_plot.append((x, y, width, height))
self.boundary_coordinates.append(
((x, x + width), (y, y + height))
)
@staticmethod
def can_particle_hop_boundary_probability() -> bool:
return random.random() < HOP_PROBABILITY_PERCENTAGE
def is_particle_on_specific_boundary(self, pos: tuple[float, float], idx: int) -> bool:
return util.is_point_within_bounds(pos, self.boundary_coordinates[idx])
def is_particle_on_boundary(self, pos: tuple[float, float]) -> bool:
return any(
util.is_point_within_bounds(pos, bounds_of_boundary)
for bounds_of_boundary in self.boundary_coordinates
) | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
def is_particle_in_compartment(self, particle: tuple[float, float]) -> bool:
return not self.is_particle_on_boundary(particle)
def get_surrounding_boundary_of_particle(self, pos: tuple[float, float]) -> int:
for idx, bounds_of_boundary in enumerate(self.boundary_coordinates):
if util.is_point_within_bounds(pos, bounds_of_boundary):
return idx
return -1
def make_particle_jump(
self,
new_pos: tuple[float, float],
x_dir: float, y_dir: float,
) -> tuple[float, float]:
surrounding_boundary_idx = self.get_surrounding_boundary_of_particle(new_pos)
while self.is_particle_on_specific_boundary(new_pos, surrounding_boundary_idx):
new_pos = util.increment_tuple_by_val(
new_pos, (np.sign(x_dir), np.sign(y_dir))
)
new_pos = util.increment_tuple_by_val(
new_pos, (
np.sign(x_dir) * BOUNDARY_JUMP,
np.sign(y_dir) * BOUNDARY_JUMP,
),
)
# Special case: In some instances the jump may land the particle
# on a subsequent boundary so we repeat the function. We decrement
# the particle's coordinates until it is out.
while self.is_particle_on_boundary(new_pos):
new_pos = util.increment_tuple_by_val(
new_pos, (np.sign(-x_dir), np.sign(-y_dir))
)
return new_pos
def update_path(self, idx: int) -> None:
x, y = self.paths[idx][-1]
assert not self.is_particle_on_boundary((x, y))
diffusion_factor = MEMBRANE_DIFFUSION_FACTOR_CORRECTED
x_dir, y_dir = [util.get_random_normal_direction() * diffusion_factor for _ in range(2)]
new_pos = x + x_dir, y + y_dir | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
if self.is_particle_on_boundary(new_pos):
if self.can_particle_hop_boundary_probability():
new_pos = self.make_particle_jump(new_pos, x_dir, y_dir)
else:
new_pos = util.change_direction((x, y), (x_dir, y_dir))
self.paths[idx].append(new_pos)
def update(self) -> None:
for i in range(self.n_particles):
self.update_path(i)
def init_particles(self) -> set[tuple[float, float]]:
mem: set[tuple[float, float]] = set()
for _ in range(5):
while True:
pair = (self.get_random_canvas_value(), self.get_random_canvas_value())
if not (pair in mem or self.is_particle_on_boundary(pair)):
break
mem.add(pair)
return mem
class Nanodomain(Simulation):
def __init__(self, n: int = 5):
super().__init__(n)
self.nanodomain_coordinates: list[tuple[float, float]] = [
(-100, 100), (0, 0), (150, -60), (-130, -160)
]
self.nanodomain_radii: list[int] = [80, 20, 50, 140]
def get_nanodomain_attributes(self) -> list[tuple]:
return list(map(
lambda coord, radius: (coord, radius),
self.nanodomain_coordinates,
self.nanodomain_radii,
))
def is_particle_in_nanodomain(self, particle: tuple) -> bool:
return any(
util.compute_distance(particle, circle_center) <= radius
for circle_center, radius in
zip(self.nanodomain_coordinates, self.nanodomain_radii)
)
def update_path(self, idx: int) -> None:
x, y = self.paths[idx][-1]
diffusion_factor = NANODOMAIN_DIFFUSION_FACTOR_CORRECTED if (
self.is_particle_in_nanodomain((x, y))) else MEMBRANE_DIFFUSION_FACTOR_CORRECTED
x_dir, y_dir = [util.get_random_normal_direction() * diffusion_factor for _ in range(2)]
self.paths[idx].append((x + x_dir, y + y_dir)) | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
def update(self) -> None:
for i in range(self.n_particles):
self.update_path(i)
def handle_nanodomain(ax: plt.Axes, sim: Nanodomain) -> None:
nanodomains = [
plt.Circle(
*param,
color='black',
alpha=0.2,
)
for param in sim.get_nanodomain_attributes()
]
for nanodomain in nanodomains:
ax.add_patch(nanodomain)
def handle_hop_diffusion(ax: plt.Axes, sim: HopDiffusion) -> None:
for param in sim.boundary_coordinates_for_plot:
boundary = plt.Rectangle(
tuple((param[0], param[1])),
param[2], param[3],
color='black',
alpha=0.7,
clip_on=False,
)
ax.add_patch(boundary)
def get_coordinates_for_plot(sim: Simulation, idx: int):
return util.get_x_coordinates(sim.paths[idx]), util.get_y_coordinates(sim.paths[idx])
def get_coordinates_for_heads(sim, idx: int):
return util.get_last_point(sim.paths[idx])
def set_plot_parameters(ax):
ax.tick_params(axis='y', direction='in', right=True, labelsize=16, pad=20)
ax.tick_params(axis='x', direction='in', top=True, bottom=True, labelsize=16, pad=20)
# legends and utilities
ax.set_xlabel(r'nm', fontsize=16)
ax.set_ylabel(r'nm', fontsize=16)
# border colors
ax.patch.set_edgecolor('black')
ax.patch.set_linewidth(2)
ax.set_xlim(-RADIUS, RADIUS)
ax.set_ylim(-RADIUS, RADIUS)
def plot(sim: Simulation) -> None:
fig, ax = plt.subplots(figsize=[5, 5], dpi=DPI)
path_plots: list[plt.Line2D] = [
ax.plot(
*get_coordinates_for_plot(sim, i),
markersize=15, color=colors[i],
)[0]
for i in range(5)
]
head_plots: list[plt.Line2D] = [
ax.plot(
*get_coordinates_for_heads(sim, i),
markersize=7, color=colors[i], marker=markers[i],
markerfacecolor='white')[0]
for i in range(5)
] | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
def initialize_animation() -> list[plt.Artist]:
set_plot_parameters(ax)
if isinstance(sim, Nanodomain):
handle_nanodomain(ax, sim)
elif isinstance(sim, HopDiffusion):
handle_hop_diffusion(ax, sim)
return path_plots
def update_animation(frame: int) -> list[plt.Artist]:
sim.update()
for i, axes in enumerate(path_plots):
coords = get_coordinates_for_plot(sim, i)
axes.set_data(*coords)
for i, head_marker in enumerate(head_plots):
coords = get_coordinates_for_heads(sim, i)
head_marker.set_data(*coords)
return path_plots
animation = FuncAnimation(
fig,
update_animation,
init_func=initialize_animation,
interval=20,
)
fig.tight_layout()
plt.show(block=True)
def main() -> None:
rcParams.update({'figure.autolayout': True})
sim = HopDiffusion() # Nanodomain()
plot(sim)
if __name__ == '__main__':
main()
Second pass
For any kind of serious simulation, and especially if you ever need to convert this from an animated visualisation to a high-throughput headless simulation, you need to vectorise with Numpy. This is a long process and requires rewriting most of your code. I will show examples but not the complete program.
generate_boundaries() becomes a function that produces two three-dimensional arrays:
@staticmethod
def generate_boundaries() -> tuple[np.ndarray, np.ndarray]:
stop = RADIUS + BOUNDARY_OVERFLOW
inner_edges = np.linspace(
start=-RADIUS, stop=RADIUS, num=NUMBER_OF_COMPARTMENTS_PER_DIRECTION + 1,
)[1: -1]
n_edges = len(inner_edges) | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
python, python-3.x, simulation, physics
# edges by x/y by start/stop
bound_coords = np.empty((2*n_edges, 2, 2))
bound_coords[:n_edges, 0, 0] = inner_edges - BOUNDARY_THICKNESS/2
bound_coords[:n_edges, 0, 1] = inner_edges + BOUNDARY_THICKNESS/2
bound_coords[:n_edges, 1, :] = -stop, stop
bound_coords[n_edges:, ...] = bound_coords[:n_edges, ::-1, :]
# edges by x/y by start/size
plot_coords = bound_coords.copy()
plot_coords[..., 1] = bound_coords[..., 1] - bound_coords[..., 0]
return plot_coords, bound_coords
Your random generator becomes
from numpy.random import default_rng
from numpy.random._generator import Generator
rand: Generator = default_rng(seed=0)
and then normally-distributed Brownian offset generation becomes
def get_random_normal_direction() -> float:
return rand.normal(scale=MEMBRANE_DIFFUSION_FACTOR_CORRECTED, size=2)
Bounds-checking becomes
def is_point_within_bounds(
pos: np.ndarray,
bounds: np.ndarray,
) -> bool:
return (
(bounds[:, 0] <= pos) &
(bounds[:, 1] >= pos)
).all()
Your initial particle state loses all of its uniqueness concerns, operates on floats only, and becomes
def init_particles(self) -> np.ndarray:
return rand.uniform(
low=-CORRECTED_CANVAS_RADIUS,
high=CORRECTED_CANVAS_RADIUS,
size=(self.n_particles, 2),
)
etc. | {
"domain": "codereview.stackexchange",
"id": 43942,
"lm_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, simulation, physics",
"url": null
} |
rust
Title: Trying to find an idiomatic Rust way of calling a series of functions and early out'ing on failure of one
Question: I would like to condense down a bunch of function calls that occur sequentially, and need to early out so they don't waste more computation later on.
I've been able to get it down to the following, but I am wondering if there's a cleaner way of doing this or not.
Here is an MCVE:
pub struct MyStruct {
// ...
}
impl MyStruct {
pub fn new(data: &[u8]) -> Option<MyStruct> {
let result = MyStruct {
// initialize fields
};
// CAN I DO THIS PART BETTER?
result.process_stuff1()?;
result.process_stuff2()?;
// ...
result.process_stuffn()?;
Some(result)
}
fn process_stuff1(&self) -> Option<()> {
// ...
println!("Ran process_stuff1");
Some(())
}
fn process_stuff2(&self) -> Option<()> {
// ...
println!("Ran process_stuff2");
None
}
// ...
fn process_stuffn(&self) -> Option<()> {
// ...
println!("Ran process_stuffn");
Some(())
}
}
fn main() {
let data: [u8; 1] = [0];
match MyStruct::new(&data[..]) {
Some(_) => println!("Success"),
None => println!("Failure")
}
}
with the expected output (I made process_stuff2 fail just to make sure it did in fact short circuit):
Ran process_stuff1
Ran process_stuff2
Failure
I feel like I'm abusing the language a bit, but it is nicer to read than something like
if !result.process_stuff1() {
None
}
if !result.process_stuff2() {
None
}
// ...etc
Is there a better way of doing this?
I was trying to see if there was some kind of all(...) function that I could call.
I am new to Rust so there might be better ways of doing this, and you should not assume I know a lot. | {
"domain": "codereview.stackexchange",
"id": 43943,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
Answer: Technically you could use iterators to do this:
pub fn new(data: &[u8]) -> Option<MyStruct> {
let result = MyStruct {
// initialize fields
};
[
Self::process_stuff1,
Self::process_stuff2,
Self::process_stuffn,
]
.into_iter()
.map(|f| f(&result))
.collect::<Option<()>>()?;
Some(result)
}
The reason this works is that FromIterator (the trait collect() uses) is implemented for Option as an early exit (aborting iteration), and is implemented for () to just return () (any number of ()s become ()).
However, I wouldn't recommend actually writing this code — it is less clear than what you have, and more concise unless you have a lot more functions to call. I think you should keep the code structure you have, unless there is some way to express your multiple functions as, say, one function with different parameters.
One thing I do think you should consider changing is returning a Result instead of an Option. The logic with ? is exactly the same, but you can return an "error" value reporting which of the sequence of functions failed. This can be key to efficiently diagnosing either program bugs or problems with the input data. (Of course, this may be unnecessary for reasons in your actual application, like obvious side effects of each function.) | {
"domain": "codereview.stackexchange",
"id": 43943,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi
Title: Azure DevOps Git: Fork into another Repo using Azure DevOps REST API
Question: In my Azure DevOps Project, I have a Git repository that I would like to copy to another Azure DevOps Project.
In other words, I should be able to copy the original repo into other Azure DevOps projects as needed.
To import work items into Azure DevOps, I have written the following code.
Would you be able to review and make suggestions? Especially, I want to optimize the way HttpClient is being passed to the core service layer from the controller..
Part of this code is already reviewed as you see in this post - Export and import work items from Azure DevOps.
Note:
Since the destination and/or source of the HttpClient changes every time, I would get the details from the payload.
At times, the Post method has to return "id" as int/string/nothing.
public class ImportController : Controller
{
private readonly ILogger<ImportController> _logger;
private readonly IImportFactory _importFactory;
public ImportController(ILogger<ImportController> logger, IImportFactory importFactory)
{
_logger = logger;
_importFactory = importFactory;
}
[HttpPost]
public async Task<IActionResult> ImportData([FromForm]ImportData importData)
{
_importFactory.Initialize(importData.devOpsProjectSettings);
await _importFactory.Import(importData.file);
return Ok();
}
}
public interface IImportService<T> where T : class
{
Task<T> Post(string uri, HttpContent content);
void SetHttpClient(HttpClient httpClient);
}
public class ImportService<T> : BaseService<T>, IImportService<T>
where T : class
{
private readonly ILogger<ImportService<T>> _logger;
public ImportService(ILogger<ImportService<T>> logger) : base()
{
_logger = logger;
}
public async Task<T> Post(string uri, HttpContent content)
{
var result = await SendRequest(uri, content);
return result;
} | {
"domain": "codereview.stackexchange",
"id": 43944,
"lm_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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi",
"url": null
} |
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi
return result;
}
public void SetHttpClient(HttpClient httpClient)
{
this._httpClient = httpClient;
}
}
public class SprintCore
{
[Newtonsoft.Json.JsonIgnore]
public string id { get; set; }
}
public class WorkItemCore
{
public int id { get; set; }
public string identifier { get; set; }
}
public class ServiceEndpointCore
{
public string id { get; set; }
}
public class ImportFactory : IImportFactory
{
private ConcurrentDictionary<int, int> idMapper = new ConcurrentDictionary<int, int>();
private readonly ILogger<ImportFactory> _logger;
private readonly DevOps _devopsConfiguration;
private readonly IImportService<WorkItemCore> _importWorkItemService;
private readonly IImportService<SprintCore> _importSprintService;
private readonly IImportService<ServiceEndpointCore> _importRepositoryService;
private const string WorkItemPathPrefix = "/fields/";
private readonly string _versionQueryString;
private DevOpsProjectSettings _devOpsProjectSettings { get; set; }
private HttpClient _httpClient;
private string _sprintCreationURL;
private string _sprintPublishURL;
private string _projectId;
private string _repositoryCreationURL; | {
"domain": "codereview.stackexchange",
"id": 43944,
"lm_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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi",
"url": null
} |
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi
public ImportFactory(ILogger<ImportFactory> logger, IConfiguration configuration, IImportService<SprintCore> importSprintService, IImportService<WorkItemCore> importWorkItemService, IImportService<ServiceEndpointCore> importRepositoryService)
{
_logger = logger;
_devopsConfiguration = configuration.GetSection(nameof(DevOps)).Get<DevOps>();
_importSprintService = importSprintService;
_importWorkItemService = importWorkItemService;
_importRepositoryService = importRepositoryService;
_versionQueryString = $"?api-version={_devopsConfiguration.APIVersion}";
}
public void Initialize(DevOpsProjectSettings devOpsProjectSettings)
{
_devOpsProjectSettings = devOpsProjectSettings;
_projectId = devOpsProjectSettings.ProjectId;
_sprintCreationURL = $"{_projectId}/_apis/wit/classificationNodes/Iterations{_versionQueryString}";
_sprintPublishURL = $"{_projectId}/{devOpsProjectSettings.TeamId}/_apis/work/teamsettings/iterations{_versionQueryString}";
_repositoryCreationURL = $"_apis/git/repositories{_versionQueryString}";
_httpClient = new HttpClient();
_httpClient.BaseAddress = new Uri(devOpsProjectSettings.DevOpsOrgURL);
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "", devOpsProjectSettings.PersonalAccessToken))));
_importSprintService.SetHttpClient(_httpClient);
_importWorkItemService.SetHttpClient(_httpClient);
_importRepositoryService.SetHttpClient(_httpClient);
}
public async Task<Board> Import(IFormFile file)
{
using var reader = new StreamReader(file.OpenReadStream());
string fileContent = await reader.ReadToEndAsync();
var board = JsonConvert.DeserializeObject<Board>(fileContent); | {
"domain": "codereview.stackexchange",
"id": 43944,
"lm_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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi",
"url": null
} |
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi
var board = JsonConvert.DeserializeObject<Board>(fileContent);
await CreateSprints(board.sprints);
await CreateWorkItems(board.workItemCollection);
await CreateRepositories(board.repositories);
await ImportRepository(board.repositories, _devOpsProjectSettings);
return board;
}
private async Task ImportRepository(Repositories repositories, DevOpsProjectSettings devOpsProjectSettings)
{
var _serviceEndpointImportURL = string.Empty;
var _serviceEndpointCreationURL = $"_apis/serviceendpoint/endpoints{_versionQueryString}";
foreach (Repository repository in repositories.value)
{
_serviceEndpointImportURL = $"{_projectId}/_apis/git/repositories/{repository.name}/importRequests{_versionQueryString}";
devOpsProjectSettings.serviceEndpoint.name = $"Import_External_Repo_{repository.name}";
devOpsProjectSettings.serviceEndpoint.url = $"{devOpsProjectSettings.DevOpsSourceURL}{Uri.EscapeDataString(repository.name)}";
devOpsProjectSettings.serviceEndpoint.serviceEndpointProjectReferences[0].name= $"Import_External_Repo_{repository.name}";
var serviceEndpointId = await _importRepositoryService.Post(_serviceEndpointCreationURL, GetJsonContent(devOpsProjectSettings.serviceEndpoint));
var importRepo = new ImportRepo();
importRepo.parameters.serviceEndpointId = serviceEndpointId.id;
importRepo.parameters.gitSource.url = devOpsProjectSettings.serviceEndpoint.url;
await _importRepositoryService.Post(_serviceEndpointImportURL, GetJsonContent(importRepo));
}
} | {
"domain": "codereview.stackexchange",
"id": 43944,
"lm_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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi",
"url": null
} |
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi
private async Task CreateRepositories(Repositories repositories)
{
foreach (Repository repository in repositories.value)
{
repository.project.id = _projectId;
await _importSprintService.Post(_repositoryCreationURL, GetJsonContent(repository));
}
}
private async Task CreateSprints(Sprints sprints)
{
foreach (Sprint sprint in sprints.value)
{
var result = await _importWorkItemService.Post(_sprintCreationURL, GetJsonContent(sprint));
await _importSprintService.Post(_sprintPublishURL, GetJsonContent(new { id = result.identifier }));
}
}
private async Task CreateWorkItems(Dictionary<string, WorkItemQueryResult> workItems)
{
foreach (var workItemCategory in workItems.Keys)
{
var categoryURL = $"{_projectId}/_apis/wit/workitems/%24{workItemCategory}{_versionQueryString}";
foreach (var workItem in workItems[workItemCategory].workItems)
{
await CreateWorkItem(categoryURL, workItem);
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43944,
"lm_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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi",
"url": null
} |
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi
private async Task CreateWorkItem(string categoryURL, WorkItem workItem)
{
var operations = new List<WorkItemOperation>
{
new WorkItemOperation()
{
path = $"{WorkItemPathPrefix}System.Title",
value = workItem.details.fields.Title ?? ""
},
new WorkItemOperation()
{
path = $"{WorkItemPathPrefix}System.Description",
value = workItem.details.fields.Description ?? ""
},
new WorkItemOperation()
{
path = $"{WorkItemPathPrefix}Microsoft.VSTS.Common.AcceptanceCriteria",
value = workItem.details.fields.AcceptanceCriteria ?? ""
},
new WorkItemOperation()
{
path = $"{WorkItemPathPrefix}System.IterationPath",
value = workItem.details.fields.IterationPath.Replace(_devOpsProjectSettings.SourceProjectName, _devOpsProjectSettings.TargetProjectName)
}
};
var parentId = FindParentId(workItem.details);
if (parentId != 0)
{
operations.Add(new WorkItemOperation()
{
path = "/relations/-",
value = new Relationship()
{
url = $"{_devOpsProjectSettings.DevOpsOrgURL}{_projectId}/_apis/wit/workitems/{idMapper[parentId]}",
attributes = new RelationshipAttribute()
}
});
}
var result = await _importWorkItemService.Post(categoryURL, GetJsonContent(operations, "application/json-patch+json"));
if (!idMapper.ContainsKey(workItem.id))
{
idMapper.TryAdd(workItem.id, result.id);
}
} | {
"domain": "codereview.stackexchange",
"id": 43944,
"lm_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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi",
"url": null
} |
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi
private int FindParentId(WorkItemDetails details)
{
var parentRelation = details.relations?.Where(relation => relation.attributes.name.Equals("Parent")).FirstOrDefault();
return parentRelation == null ? 0 : int.Parse(parentRelation.url.Split("/")[parentRelation.url.Split("/").Length - 1]);
}
private HttpContent GetJsonContent(object data, string mediaType = "application/json")
{
var jsonString = JsonConvert.SerializeObject(data);
return new StringContent(jsonString, Encoding.UTF8, mediaType);
}
}
Answer: ImportController
ImportData
In software industry the data is a magic word for anything
Please try to be more precise with naming to bring clarity
_importFactory.Initialize seems pretty weird
The Factory suffix is usually used when you have applied the factory design pattern
Your current naming might be misleading
Also be aware of the fact that the compiler can't enforce you to call the Initialize before calling the Import
This makes your code fragile
As I can see the Import method call can throw several different exceptions
I hope there is a middleware in your pipeline which logs these exceptions and converts the response to 500
I would suggest to consider to return with 201 (Created) rather than 200 (Ok)
Since you have exposed an Import API that's why it would make sense to confirm that the import has created all the resources in the given system with success
ImportService
Without knowing what BaseService does it is impossible to provide insightful suggestions
Although here are several tiny observations:
The _logger is not used, just initialized
The string uri might contain invalid url
This SetHttpClient feels pretty weird
This api allows the consumer of this class to change the HttpClient between two Post calls
Also the compiler can't enforce that you should call the SetHttpClient before the call of Post | {
"domain": "codereview.stackexchange",
"id": 43944,
"lm_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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi",
"url": null
} |
c#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi
In your question you have mentioned the Post method has to return "id" as int/string/nothing
But you have restricted T to be a class, so you can't use int as type parameter
SprintCore, ... , ServiceEndpointCore
Please prefer C# naming convention for your public properties
Please prefer Id over id
Or use JsonPropertyAttribute for renaming (if needed at all)
What does this Core suffix mean?
They all look like DTO classes
ImportFactory
Since I have reviewed the majority of this class in your previous post that's why I will try to focus only on the new stuff
Initialize
As I have stated several times this Initialize "pattern" makes your code fragile, since you can't enforce the call of this method prior any other publicly exposed method
I'm not sure which .NET version are you using but if not the recent ones then please consider to use IHttpClientFactory to create a new HttpClient instance
Please prefer Uri.TryCreate over new Uri to parse string as Uri
Please try to avoid basic auth (AuthenticationHeaderValue("Basic" ...) since it is not secure by any means
ImportRepository
It is unnecessary to pass the _devOpsProjectSettings field as a parameter since this method can access that as well
Also please adjust naming
It imports repositories, not just a single one
The _serviceEndpointCreationURL can be constructed only once, there is no need to regenerate it every time when this method is being called
ImportRepo: Please try to avoid any unnecessary abbreviations Repo >> Repository
CreateRepositories
It might make sense to combine this method with the ImportRepositories since you iterate through the same collection | {
"domain": "codereview.stackexchange",
"id": 43944,
"lm_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#, asp.net-core, asp.net-web-api, .net-core, asp.net-core-webapi",
"url": null
} |
c#, asp.net-core, authorization, azure
Title: Azure AD Role Based Authorization : Allow specific roles for all GET methods and another set of roles for POSTS
Question: There is a need to authorize the Users based on their Roles, particularly a set of roles that should allow all GET operations and a second set that should allow all POST operations.
Eg:
All Get methods should be accessible to the reader
Post method access is granted to contributors
I don't want to mark the individual methods with the [Authorize()] as I have ~20 controllers with each supporting all 4 Http Verbs.
I have implemented something like this
[RoleBasedAuthorizeAttribute(new string[2] { "CJE.Reader", "CJE.Contributor" }, new string[1] { "CJE.Contributor" }, new string[1] { "CJE.Contributor" }, new string[1] { "CJE.Contributor" })]
public abstract class BaseController : ControllerBase
{
and
public sealed class RoleBasedAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
public RoleBasedAuthorizeAttribute(string[] getRoleMap, string[] postRoleMap, string[] putRoleMap, string[] deleteRoleMap)
{
this.GetRoleMap = getRoleMap;
this.PostRoleMap = postRoleMap;
this.PutRoleMap = putRoleMap;
this.DeleteRoleMap = deleteRoleMap;
}
public string[] GetRoleMap { get; }
public string[] PostRoleMap { get; }
public string[] PutRoleMap { get; }
public string[] DeleteRoleMap { get; }
public void OnAuthorization(AuthorizationFilterContext context)
{
if (!this.IsUserAllowed(context))
{
context.Result = new UnauthorizedResult();
}
}
private bool IsUserAllowed(AuthorizationFilterContext context)
{
var roles = ((ClaimsIdentity)context.HttpContext.User.Identity).Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => c.Value); | {
"domain": "codereview.stackexchange",
"id": 43945,
"lm_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#, asp.net-core, authorization, azure",
"url": null
} |
c#, asp.net-core, authorization, azure
switch (context.HttpContext.Request.Method)
{
case "GET":
return this.GetRoleMap.Any(r => roles.Contains(r));
case "POST":
return this.PostRoleMap.Any(r => roles.Contains(r));
case "PUT":
return this.PutRoleMap.Any(r => roles.Contains(r));
case "DELETE":
return this.DeleteRoleMap.Any(r => roles.Contains(r));
default:
return false;
}
}
}
this works fine. However, I feel that this needs to be optimized. Any suggestions?
Answer: BaseController
There is no need to use the Attribute suffix whenever you apply an attribute
[RoleBasedAuthorize(new string[2] { ... })]
public abstract class BaseController : ControllerBase
If possible please prefer enum over string since they are less error-prone
[RoleBasedAuthorize(new CJERoles[2] { CJERoles.Reader, CJERoles.Contributor }, ...)]
public enum CJERoles
{
[Display(Name = "CJE.Reader")]
Reader = 0,
[Display(Name = "CJE.Contributor")]
Contributor = 1,
}
Please also prefer named arguments and line breaks
I would also suggest to use xyzRoles parameter names over xyzRoleMap
[RoleBasedAuthorize(
getRoles: new CJERoles[2] { CJERoles.Reader, CJERoles.Contributor },
postRoles: new CJERoles[1] { CJERoles.Contributor },
putRoles: new CJERoles[1] { CJERoles.Contributor },
deleteRoles: new CJERoles[1] { CJERoles.Contributor })]
RoleBasedAuthorizeAttribute
XYZRoleMap
It is good that you have made the properties read-only
You could also remove the public access modifier since they are used only internally
Constructor
By accepting enums rather than strings you need to perform some mapping
I would suggest to map your enums to strings, because I assume not all user roles can be mapped to an enum value
In order to ease this mapping I would suggest to introduce the following extension method | {
"domain": "codereview.stackexchange",
"id": 43945,
"lm_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#, asp.net-core, authorization, azure",
"url": null
} |
c#, asp.net-core, authorization, azure
In order to ease this mapping I would suggest to introduce the following extension method
public static class CJERolesExtensions
{
public static string GetDisplayName(this CJERoles enumValue)
=> typeof(CJERoles)
.GetMember(enumValue.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()
.GetName();
}
With this in our hand we can perform the mappings like this
First create a local method which can do the mapping
Then perform the assignments with the help of ValueTuple and deconstruction
public RoleBasedAuthorizeAttribute(CJERoles[] getRoles, CJERoles[] postRoles, CJERoles[] putRoles, CJERoles[] deleteRoles)
{
Func<CJERoles[], string[]> map = roles => roles.Select(role => role.GetDisplayName()).ToArray();
(GetRoleMap, PostRoleMap, PutRoleMap, DeleteRoleMap) = (map(getRoles), map(postRoles), map(putRoles), map(deleteRoles));
}
IsUserAllowed
I would suggest to inline this method inside the OnAuthorization
I would also suggest to avoid code duplication use switch expression to select the proper string[] role map
public void OnAuthorization(AuthorizationFilterContext context)
{
var roles = ((ClaimsIdentity)context.HttpContext.User.Identity).Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => c.Value);
var roleMap = context.HttpContext.Request.Method switch
{
"GET" => GetRoleMap,
"POST" => PostRoleMap,
"PUT" => PutRoleMap,
"DELETE" => DeleteRoleMap,
_ => new string[] { }
};
if (!roleMap.Any(roles.Contains))
{
context.Result = new UnauthorizedResult();
}
} | {
"domain": "codereview.stackexchange",
"id": 43945,
"lm_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#, asp.net-core, authorization, azure",
"url": null
} |
c#, .net, excel
Title: Parsing information from Excel files
Question: I have to parse information from several Excel files (.xls, .xlsx). The structure of the files is nearly identical except for the columns order. In this case it is # Number Name but in other cases it might be # Name Number.
Sample .xlsx file can be found here (Google Spreadsheets).
Assumptions:
Industry name: ^Industry: (.*)$. I'm fine with the current regex expression.
List of the people:
First of all, it should be List<Person> instead of List<string>, because Person consists of "Number" and "Name", not just the name.
my assumptions here are wrong because it is looking for the 6-digit length number and then it relies on the column order because it actually makes the assumption that "Name" is the next column to the "Number". Perhaps this should be replaced with simple regex expressions such as Number = ^[0-9]{6}$ (always 6 digits), Name = ^([a-zA-Z]+\s?\b){2,}$ (at least 2 words separated by spaces because there are some people with FirstName LastName and there are others with FirstName MiddleName LastName; however, the names can also be in cyrillic; there are names such as Anna-Maria i.e. including hypens)
I would like to get a review because the code looks so bad, it doesn't meet any principles such as Keep it Simple, Stupid (KISS), Do not repeat yourself (DRY), etc. and most importantly, it is not testable. Once I put the logic for exporting to Excel files, I would be making unit tests for the import and the parsing, which is not possible with the current code base.
var excel = new ExcelParser();
var sheet1 = excel.Import(@"test.xlsx");
var result = ParseSheet(sheet1);
Console.ReadLine();
static (string industryName, List<string> peopleNames) ParseSheet(DataTable sheet1)
{
Console.OutputEncoding = Encoding.UTF8; // needed for the cyrillic names
var industryRegex = new Regex("^Industry: (.*)$");
// 1. Get Indices of industry cell and first Name in people names.. | {
"domain": "codereview.stackexchange",
"id": 43946,
"lm_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#, .net, excel",
"url": null
} |
c#, .net, excel
// 1. Get Indices of industry cell and first Name in people names..
var industryCellIndex = (-1, -1, false);
var peopleFirstCellIndex = (-1, -1, false);
for (var i = 0; i < sheet1.Rows.Count; i++)
{
for (var j = 0; j < sheet1.Columns.Count; j++)
{
var cell = sheet1.Rows[i][j].ToString()?.Trim();
// match Industry
var matches = industryRegex.Match(cell);
if (matches.Success)
{
var industryName2 = matches.Groups[1];
industryCellIndex = (i, j, true);
break;
}
// the name after the first 6-digits number cell will be the first name in people records
if (cell.Length == 6 && int.TryParse(cell, out _))
{
peopleFirstCellIndex = (i, j + 1, true);
break;
}
}
if (industryCellIndex.Item3 && peopleFirstCellIndex.Item3)
break;
}
if (!industryCellIndex.Item3 || !peopleFirstCellIndex.Item3)
{
throw new Exception("Excel file is not normalized!");
}
// 2. retrieve the desired data
var industryName = industryRegex.Match(sheet1.Rows[industryCellIndex.Item1][industryCellIndex.Item2].ToString()?.Trim()).Groups[1].Value;
var peopleNames = new List<string>();
var colIndex = peopleFirstCellIndex.Item2;
for (var rowIndex = peopleFirstCellIndex.Item1;
rowIndex < sheet1.Rows.Count;
rowIndex++)
{
peopleNames.Add(sheet1.Rows[rowIndex][colIndex].ToString()?.Trim());
}
return (industryName, peopleNames);
}
public class Person
{
public string Number { get; init; } = default!;
public string Name { get; init; } = default!;
}
public sealed class ExcelParser
{
public ExcelParser()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
} | {
"domain": "codereview.stackexchange",
"id": 43946,
"lm_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#, .net, excel",
"url": null
} |
c#, .net, excel
public DataTable Import(string filePath)
{
// does file exist?
if (!File.Exists(filePath))
{
throw new FileNotFoundException();
}
// .xls or .xlsx allowed
var extension = new FileInfo(filePath).Extension.ToLowerInvariant();
if (extension is not (".xls" or ".xlsx"))
{
throw new NotSupportedException();
}
// read .xls or .xlsx
using var stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
using var reader = ExcelReaderFactory.CreateReader(stream);
var dataSet = reader.AsDataSet(new ExcelDataSetConfiguration
{
ConfigureDataTable = _ => new ExcelDataTableConfiguration
{
UseHeaderRow = false
}
});
// Sheet1
return dataSet.Tables[0];
}
}
Answer: ExcelParser
Import
Please do not use the comments to echo what you are about to do
Use the comments to capture the why or why not which can't be read from the code
// does file exist?
if (!File.Exists(filePath))
{
throw new FileNotFoundException();
}
I would suggest a different name for this method like LoadSheet1IntoDataTable or GetSheet1AsDataTable or ...
Please try to avoid magic numbers, please prefer constants
const int SheetOneIndex = 0;
...
return dataSet.Tables[SheetOneIndex]
const int SheetOneIndex = 0;
const string Xls = ".xls", Xlsx = ".xlsx";
public DataTable GetSheet1AsDataTable(string filePath)
{
if (!File.Exists(filePath))
throw new FileNotFoundException();
var extension = new FileInfo(filePath).Extension.ToLowerInvariant();
if (extension is not (Xls or Xlsx))
throw new NotSupportedException();
using var stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
using var reader = ExcelReaderFactory.CreateReader(stream); | {
"domain": "codereview.stackexchange",
"id": 43946,
"lm_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#, .net, excel",
"url": null
} |
c#, .net, excel
var dataSet = reader.AsDataSet(new () { ConfigureDataTable = _ => new () { UseHeaderRow = false } });
return dataSet.Tables[SheetOneIndex];
}
ParseSheet
I would suggest to create several smaller functions to make your code more legible
First, I would introduce the following two tester-doer helpers
static Regex industryRegex = new Regex("^Industry: (.*)$", RegexOptions.Compiled);
const int CaptureGroupIndex = 1;
static bool TryGetIndustryName(string cell, out string industryName)
{
var matches = industryRegex.Match(cell);
industryName = matches.Success ? matches.Groups[CaptureGroupIndex].ToString() : default;
return matches.Success;
}
const int SixDigitLong = 6;
static bool TryGetFirstPersonIndex(string cell, int row, int column, out (int Row, int Column) firstPersonIndex)
{
var isASixDigitLongInteger = cell.Length == SixDigitLong && int.TryParse(cell, out _);
//+1 is needed to point to "Name" column rather than "Number"
firstPersonIndex = isASixDigitLongInteger ? (row, column + 1) : default;
return isASixDigitLongInteger;
}
With these in our hand the first part of ParseSheet can be achieved like this
Instead of using two triple tuple I have declared two more simple variable
I have used two foreach loops inside of two fors
I also made the cell checks lazy (evaluate only if we haven't found yet)
static (string IndustryName, (int Row, int Column) FirstPersonIndex) GetIndustryAndFirstPersonIndex(DataTable sheet)
{
string industryName = default;
(int Row, int Column) firstPersonIndex = default;
foreach (DataRow row in sheet.Rows)
foreach (DataColumn column in sheet.Columns)
{
if (industryName != default && firstPersonIndex != default)
return (industryName, firstPersonIndex);
var cell = row[column].ToString().Trim();
if (industryName == default
&& TryGetIndustryName(cell, out industryName))
break; | {
"domain": "codereview.stackexchange",
"id": 43946,
"lm_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#, .net, excel",
"url": null
} |
c#, .net, excel
if (firstPersonIndex == default
&& TryGetFirstPersonIndex(cell, sheet.Rows.IndexOf(row), sheet.Columns.IndexOf(column), out firstPersonIndex))
break;
}
throw new Exception("Excel file is not normalized!");
}
The second part of the ParseSheet can be achieved with the following Linq:
Please bear in mind the .Range requires start and count parameters not start and end
static (string industryName, List<string> peopleNames) ParseSheet(DataTable sheet)
{
var (industryName, firstPersonIndex) = GetIndustryAndFirstPersonIndex(sheet);
var peopleNames = Enumerable.Range(firstPersonIndex.Row, sheet.Rows.Count - firstPersonIndex.Row)
.Select(rowIndex => sheet.Rows[rowIndex][firstPersonIndex.Column].ToString()?.Trim())
.ToList();
return (industryName, peopleNames);
} | {
"domain": "codereview.stackexchange",
"id": 43946,
"lm_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#, .net, excel",
"url": null
} |
python, performance, pygame, collision
Title: Movement and collision function
Question: I just want this code optimized to the max and I don't mind knowing if the optimization is pretty much at the max already or if I am doing movement and collision wrong. My game is a 2d Minecraft style game so it will have a lot of other_rects. Hopefully my code is easy to read.
Code:
def move(rect, movement, other_rects): # move one axis at a time, returns moved rect and info on collisions
collisions = [0, 0, 0, 0] # left, right, up, down
if movement.x:
rect.x += movement.x
if movement.x < 0:
for tile in [tile for tile in other_rects if rect.colliderect(tile)]:
rect.left = tile.right
collisions[0] = 1
else:
for tile in [tile for tile in other_rects if rect.colliderect(tile)]:
rect.right = tile.left
collisions[1] = 1
if movement.y:
rect.y += movement.y
if movement.y < 0:
for tile in [tile for tile in other_rects if rect.colliderect(tile)]:
rect.top = tile.bottom
collisions[2] = 1
else:
for tile in [tile for tile in other_rects if rect.colliderect(tile)]:
rect.bottom = tile.top
collisions[3] = 1
return rect, collisions
Code for testing:
import pygame
import pygame.math
pygame.init()
pygame.display.set_caption('Physics')
screen = pygame.display.set_mode((500,500),0,32)
clock = pygame.time.Clock()
player = pygame.Rect(100,100,40,80)
tiles = [pygame.Rect(200,350,50,50),pygame.Rect(260,320,50,50)] # could be made bigger
speed = 5
def move(rect, movement, other_rects):
... # put move function here
while 1:
movement = pygame.math.Vector2(0)
for e in pygame.event.get():
if e.type == pygame.QUIT:
pygame.quit()
exit()
keys = pygame.key.get_pressed() | {
"domain": "codereview.stackexchange",
"id": 43947,
"lm_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, pygame, collision",
"url": null
} |
python, performance, pygame, collision
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and not keys[pygame.K_d]:
movement.x -= speed
if keys[pygame.K_d] and not keys[pygame.K_a]:
movement.x += speed
if keys[pygame.K_w] and not keys[pygame.K_s]:
movement.y -= speed
if keys[pygame.K_s] and not keys[pygame.K_w]:
movement.y += speed
player = move(player,movement,tiles)[0]
screen.fill((0,0,0))
pygame.draw.rect(screen,(255,255,255),player)
for tile in tiles:
pygame.draw.rect(screen,(255,0,0),tile)
pygame.display.update()
clock.tick(60)
Answer: Thanks everyone who has helped me (in the end it was mainly @Reinderien). Taking bits and pieces of advice I have put together an optimized (most likely not fully) 'movement and collision function'.
Reveiwed code
import pygame
import pygame.math
pygame.init()
pygame.display.set_caption('Physics')
screen = pygame.display.set_mode((500,500),0,32)
clock = pygame.time.Clock()
player = pygame.Rect(100,100,40,80)
tiles = [pygame.Rect(200,350,50,50),pygame.Rect(260,320,50,50)]
speed = 5
def move(rect, movement, other_rects): # move one axis at a time, returns info on collisions
collisions = [0, 0, 0, 0] # left, right, up, down
if movement.x:
rect.x += movement.x
collided_with = [other_rects[i] for i in rect.collidelistall(other_rects)]
if collided_with:
if movement.x < 0:
rect.left = max(tile.right for tile in collided_with)
collisions[0] = 1
else:
rect.right = min(tile.left for tile in collided_with)
collisions[1] = 1 | {
"domain": "codereview.stackexchange",
"id": 43947,
"lm_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, pygame, collision",
"url": null
} |
python, performance, pygame, collision
if movement.y:
rect.y += movement.y
collided_with = [other_rects[i] for i in rect.collidelistall(other_rects)]
if collided_with:
if movement.y < 0:
rect.top = max(tile.bottom for tile in collided_with)
collisions[2] = 1
else:
rect.bottom = min(tile.top for tile in collided_with)
collisions[3] = 1
return collisions
while 1:
movement = pygame.math.Vector2(0)
for e in pygame.event.get():
if e.type == pygame.QUIT:
pygame.quit()
exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and not keys[pygame.K_d]:
movement.x -= speed
if keys[pygame.K_d] and not keys[pygame.K_a]:
movement.x += speed
if keys[pygame.K_w] and not keys[pygame.K_s]:
movement.y -= speed
if keys[pygame.K_s] and not keys[pygame.K_w]:
movement.y += speed
move(player,movement,tiles)
screen.fill((0,0,0))
pygame.draw.rect(screen,(255,255,255),player)
for tile in tiles:
pygame.draw.rect(screen,(255,0,0),tile)
pygame.display.update()
clock.tick(60)
Optimizations
1 - Used collidelistall instead of colliderect, avoids checking for each individual rect. @Reinderien
2 - Used min and max functions to correctly uncollide, also avoids looping through the list of collisions. @Reinderien
3 - Removed the rect from return rect, collisions as the function is already modifying the rect. @Reinderien | {
"domain": "codereview.stackexchange",
"id": 43947,
"lm_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, pygame, collision",
"url": null
} |
strings, go, escaping
Title: Golang - Splitting a string by a separator not prefixed by an escape string
Question: I need to split a string by a separator but don't want to split if the separator is prefixed by the escape string.
For example:
"This works\\ but it\\ isn't pretty." with " " as the separator and "\\" as the escape string should produce the following: []string{"This", "works but", "it isn't", "pretty."}
I wrote the following code for it:
func SplitWithEscaping(s string, separator string, escapeString string) []string {
untreated := strings.Split(s, separator)
toReturn := make([]string, 0, len(untreated))
for i := 0; i < len(untreated); i++ {
next, ii := t(untreated, i, separator, escapeString)
i = ii - 1
toReturn = append(toReturn, strings.ReplaceAll(next, escapeString+separator, separator))
}
return toReturn
}
func t(stringSlice []string, i int, seperator, escapeString string) (string, int) {
if !strings.HasSuffix(stringSlice[i], escapeString) {
return stringSlice[i], i + 1
}
next, ii := t(stringSlice, i+1, seperator, escapeString)
return stringSlice[i] + seperator + next, ii
}
This is the playground link for my working code: https://play.golang.org/p/jfHFt9_vtE7
How can I make my code prettier but also more performant?
Answer: One approach that's simple, but is a bit of a dirty trick: first replace sequences of escape+separator with a string that's never going to occur in your text (for example a NUL byte "\x00"), then do the split, then do the reverse replace on each token. For example (Go Playground link):
func SplitWithEscaping(s, separator, escape string) []string {
s = strings.ReplaceAll(s, escape+separator, "\x00")
tokens := strings.Split(s, separator)
for i, token := range tokens {
tokens[i] = strings.ReplaceAll(token, "\x00", separator)
}
return tokens
} | {
"domain": "codereview.stackexchange",
"id": 43948,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, go, escaping",
"url": null
} |
strings, go, escaping
Your approach of splitting and then re-joining if the last character was an escape works, but it's a bit tricky, and it does more work than necessary. You may also want to name the t function a bit more meaningfully.
An alternative approach would be more of a tokenizer, where you loop through all the bytes in the string, looking for escape and space. Here's the code for that, but note that I've made the separator and escape a single byte to simplify it -- I'm guessing they will be in most cases anyway (Go Playground link):
func SplitWithEscaping(s string, separator, escape byte) []string {
var token []byte
var tokens []string
for i := 0; i < len(s); i++ {
if s[i] == separator {
tokens = append(tokens, string(token))
token = token[:0]
} else if s[i] == escape && i+1 < len(s) {
i++
token = append(token, s[i])
} else {
token = append(token, s[i])
}
}
tokens = append(tokens, string(token))
return tokens
}
The other approach that came to mind is regexes, but you have to be able to say "match space, but only if it's not preceded by this escape", which I think you can only do with lookbehind expressions like ?<, and Go's regexp package doesn't support those. | {
"domain": "codereview.stackexchange",
"id": 43948,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, go, escaping",
"url": null
} |
c#, .net
Title: Factory method doesn't meet the DRY principle
Question: I'm using Proto.Actor and I have an actor which acts as a proxy and forwards the messages to the appropriate exchange just because each exchange has different subscription methods, different parameters are passed, etc. I made a factory method which looks like below. What I don't like is the fact that there is a repeated logic. What would you recommend to me in order to follow up the DRY principle (Do not repeat yourself)?
using Proto;
namespace Api.Actors.Exchanges;
internal sealed class ExchangeFactory
{
private readonly IContext _context;
private readonly IServiceProvider _serviceProvider;
private readonly int _retryAttempts;
internal ExchangeFactory(IContext context, IServiceProvider serviceProvider, int retryAttempts)
{
_context = context;
_serviceProvider = serviceProvider;
_retryAttempts = retryAttempts;
}
internal PID CreateExchange(string exchange, string accountId)
{
switch (exchange)
{
case "ftx":
var exchangeProps = Props.FromProducer(() =>
// ActivatorUtilities is used for partial dependency injection.
ActivatorUtilities.CreateInstance<FtxSubscription>(_serviceProvider, accountId)
)
.WithChildSupervisorStrategy(
new OneForOneStrategy((_, _) => SupervisorDirective.Restart, _retryAttempts, null)
);
return _context.SpawnNamed(exchangeProps, $"{exchange}:{accountId}"); | {
"domain": "codereview.stackexchange",
"id": 43949,
"lm_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#, .net",
"url": null
} |
c#, .net
case "kraken":
var exchangeProps2 = Props.FromProducer(() =>
// ActivatorUtilities is used for partial dependency injection.
ActivatorUtilities.CreateInstance<KrakenSubscription>(_serviceProvider, accountId)
)
.WithChildSupervisorStrategy(
new OneForOneStrategy((_, _) => SupervisorDirective.Restart, _retryAttempts, null)
);
return _context.SpawnNamed(exchangeProps2, $"{exchange}:{accountId}");
default:
throw new NotSupportedException();
}
}
}
Answer: I don't know C#, so my answer is pretty generic. The only difference between the two cases is within the closure / lambda (or whatever C# calls it), so you can just assign the respective closure within the switch cases and call the common code afterwards.
Pseudo code:
using Proto;
namespace Api.Actors.Exchanges;
internal sealed class ExchangeFactory
{
private readonly IContext _context;
private readonly IServiceProvider _serviceProvider;
private readonly int _retryAttempts;
internal ExchangeFactory(IContext context, IServiceProvider serviceProvider, int retryAttempts)
{
_context = context;
_serviceProvider = serviceProvider;
_retryAttempts = retryAttempts;
}
internal PID CreateExchange(string exchange, string accountId)
{
var producer;
switch (exchange)
{
case "ftx":
producer = () => ActivatorUtilities.CreateInstance<FtxSubscription>(_serviceProvider, accountId);
break;
case "kraken":
producer = () => ActivatorUtilities.CreateInstance<KrakenSubscription>(_serviceProvider, accountId);
break; | {
"domain": "codereview.stackexchange",
"id": 43949,
"lm_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#, .net",
"url": null
} |
c#, .net
default:
throw new NotSupportedException();
}
var exchangeProps = Props.FromProducer(producer)
.WithChildSupervisorStrategy(
new OneForOneStrategy((_, _) => SupervisorDirective.Restart, _retryAttempts, null)
);
return _context.SpawnNamed(exchangeProps, $"{exchange}:{accountId}");
}
}
or, even better, just store the varying type:
using Proto;
namespace Api.Actors.Exchanges;
internal sealed class ExchangeFactory
{
private readonly IContext _context;
private readonly IServiceProvider _serviceProvider;
private readonly int _retryAttempts;
internal ExchangeFactory(IContext context, IServiceProvider serviceProvider, int retryAttempts)
{
_context = context;
_serviceProvider = serviceProvider;
_retryAttempts = retryAttempts;
}
internal PID CreateExchange(string exchange, string accountId)
{
var subscription_type;
switch (exchange)
{
case "ftx":
subscription_type = FtxSubscription;
break;
case "kraken":
subscription_type = KrakenSubscription;
break;
default:
throw new NotSupportedException();
}
var exchangeProps = Props.FromProducer(
() => ActivatorUtilities.CreateInstance<subscription_type>(_serviceProvider, accountId)
)
.WithChildSupervisorStrategy(
new OneForOneStrategy((_, _) => SupervisorDirective.Restart, _retryAttempts, null)
);
return _context.SpawnNamed(exchangeProps, $"{exchange}:{accountId}");
}
}
However, I don't know if this is possible in C#. | {
"domain": "codereview.stackexchange",
"id": 43949,
"lm_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#, .net",
"url": null
} |
javascript, html, timer
Title: Heartbeats per minute in vanilla HTML JS
Question: Attached is a fun little snippet demonstrating a button to be clicked along with your heartbeat and see how many beats per minute you're at. This is a mwe of the concept, any feedback is appreciated.
const $ = str => document.querySelector(str);
let beatStart;
let beatEnd;
let beatCount = 0;
const display = $(".display");
function updateDisplay() {
if (beatCount < 2) return;
const secondsPassed = (beatEnd - beatStart) / 1000;
const bpm = beatCount / secondsPassed * 60;
display.innerText = bpm.toFixed(2);
}
$(".heart").addEventListener("click", () => {
beatCount++;
if (beatStart === undefined) beatStart = Date.now();
beatEnd = Date.now();
updateDisplay();
});
$(".reset").addEventListener("click", () => {
beatStart = undefined;
beatEnd = undefined;
beatCount = 0;
display.innerText = "Tap Tap";
});
<span class="display">tap tap</span> bpm
<button class="heart">beat heart</button>
<button class="reset">reset</button>
Answer: You have an off-by-one error! Notice that even if you tap a steady beat, the display will initially show a high bpm before asymptotically settling down to something approximating the correct value.
The initial placeholder text is "tap tap", but after hitting the reset button, it's "Tap Tap".
I recommend extracting the reset code from the event handler into its own function, so that you can call it to initialize the variables.
If you're using ECMAScript 6 syntax to define functions, you may as well do so consistently everywhere.
const $ = str => document.querySelector(str);
const display = $(".display");
let beatStart, beatEnd, beatCount;
const reset = () => {
beatStart = undefined;
beatEnd = undefined;
beatCount = -1;
display.innerText = "tap tap";
}; | {
"domain": "codereview.stackexchange",
"id": 43950,
"lm_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, html, timer",
"url": null
} |
javascript, html, timer
const updateDisplay = () => {
const secondsPassed = (beatEnd - beatStart) / 1000;
const bpm = beatCount / secondsPassed * 60;
display.innerText = bpm.toFixed(2);
};
$(".heart").addEventListener("click", () => {
if (beatStart === undefined) beatStart = Date.now();
beatEnd = Date.now();
if (++beatCount) updateDisplay();
});
$(".reset").addEventListener("click", reset);
reset();
<span class="display">tap tap</span> bpm
<button class="heart">beat heart</button>
<button class="reset">reset</button> | {
"domain": "codereview.stackexchange",
"id": 43950,
"lm_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, html, timer",
"url": null
} |
random, graphics, asymptote
Title: Piece-wise radial uniformly random distribution of points around a reference point
Question: I have been learning Asymptote, which is a vector graphics programming language. In addition to its nice integration with LaTeX and friends, it is capable of generating 3D rendered artworks. For a semi-learning semi-research purpose, I'd like to generate some random points around a center point, called preMigrationCenter such that their distribution vary in different radial ranges from that point. In particular, for two radial ranges [r1,r2] and [r2,r3], if r1 < r2 < r3, then the density of points spread in [r1,r2] shall be higher than that of [r2,r3], with respect to some hyperparameter settings. The code below is the kernel of a very larger file which is the reason that some hyperparemeters, e.g., the overall size of the page, may seem larger than what it should be in this simplified case. Except the general stylistic comments on my code, I shall be grateful if one can share any optimization ideas on the random generation process of my code, say, the way I manage seed points, if possible.
General specifications:
TeX engine and unit size are set.
settings.tex="pdflatex";
unitsize(1mm);
Moreover, using the code borrowed from here, absolute page size is set to alleviate any future scaling issues.
pair page_min = (0, 0);
pair page_max = (500, 250);
clip(box(page_min, page_max));
fixedscaling(page_min, page_max);
Hyperparameters:
Here are the parameters to set a population for my points, radii, and the proportion of the sub-population associated with each radial range. Points base and preMigrationCenter are the reference point of the whole schematic and the center to define radii, respectively.
real totalRadius = 150;
real mostInnerRadius = totalRadius*0.1;
real innerRadius = totalRadius*0.2;
real outerRadius = totalRadius*0.3;
real mostOuterRadius = totalRadius*0.4; | {
"domain": "codereview.stackexchange",
"id": 43951,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "random, graphics, asymptote",
"url": null
} |
random, graphics, asymptote
real mostInnerPopulation = 30;
real innerPopulation = 25;
real outerPopulation = 20;
real mostOuterPopulation = 15;
pair base = (0,0);
pair preMigrationCenter = (150, 125);
Utility functions:
Each point has three properties, collectively known as configuration, all of which have to be set in a random manner, including its coordinate components and its orientation. The function below, given a radial range [lowerBound, upperBound], uses randunit() function of Asymptote. unitrand() returns a random number sampled from a uniform distribution whose range is [0,1]. The output of this function is the radius component of the polar coordinate of the desired random point.
real getRandomRadius(real lowerBound, real upperBound, int i)
{
srand(seconds()+i);
real randomRadius = (upperBound - lowerBound)*unitrand() + lowerBound;
return randomRadius;
}
The angle component of the desired point is computed by
real getRandomTheta(int i)
{
srand(seconds()+11*(i+3));
real randomTheta = 360*unitrand();
return randomTheta;
}
The code below randomly generates an orientation for the point, transforms its coordinate to a Cartesian frame, and returns a packaged configuration. (A point obviously has no orientation but, as one sees later, each point hosts a png image which is not symmetric, thereby requiring a specified orientation.)
real[] computeConfiguration(pair migrationCenter, real randomRadius, real randomTheta, int i)
{
srand(seconds()+i*19);
real xCoord = migrationCenter.x + randomRadius*Cos(randomTheta);
real yCoord = migrationCenter.y + randomRadius*Sin(randomTheta);
real orientation = unitrand()*360;
real[] configuration = {xCoord, yCoord, orientation};
return configuration;
} | {
"domain": "codereview.stackexchange",
"id": 43951,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "random, graphics, asymptote",
"url": null
} |
random, graphics, asymptote
Here is a plotter. The image shape is first scaled, and then rotated according to the orientation of its configuration.
void plot(real[] configuration)
{
label(rotate(configuration[2], base)*graphic("shape.png","scale=0.03"), (configuration[0], configuration[1]));
}
Finally, the wrapper below manages the whole process for a given radial range.
void process(pair migrationCenter, real marginalPopulation, real smallerRadius, real largerRadius)
{
for (int i = 1; i < marginalPopulation + 1; ++i)
{
real randomRadius = getRandomRadius(smallerRadius, largerRadius, i);
real randomTheta = getRandomTheta(i);
real[] configuration = computeConfiguration(migrationCenter, randomRadius, randomTheta, i);
plot(configuration);
}
}
Operations:
In the end, we call as many process({arguments}) functions as the number of radial ranges. sleep() functions are embedded to assure that the seed points generated by srand functions are different.
path preMostOuterCircle = circle(preMigrationCenter, mostOuterRadius);
draw(preMostOuterCircle, red+dashed);
process(preMigrationCenter, mostInnerPopulation, 0, mostInnerRadius);
sleep(1);
process(preMigrationCenter, innerPopulation, mostInnerRadius, innerRadius);
sleep(2);
process(preMigrationCenter, outerPopulation, innerRadius, outerRadius);
sleep(1);
process(preMigrationCenter, mostOuterPopulation, outerRadius, mostOuterRadius);
Execution:
Gluing all snippets above together in <file_name>.asy,
/////////////////////////// General specifications /////////////////////////
settings.tex="pdflatex";
unitsize(1mm);
pair page_min = (0, 0);
pair page_max = (500, 250);
clip(box(page_min, page_max));
fixedscaling(page_min, page_max);
///////////////////////////// Hyperparameters /////////////////////////////
real totalRadius = 150;
real mostInnerRadius = totalRadius*0.1;
real innerRadius = totalRadius*0.2;
real outerRadius = totalRadius*0.3;
real mostOuterRadius = totalRadius*0.4; | {
"domain": "codereview.stackexchange",
"id": 43951,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "random, graphics, asymptote",
"url": null
} |
random, graphics, asymptote
real mostInnerPopulation = 30;
real innerPopulation = 25;
real outerPopulation = 20;
real mostOuterPopulation = 15;
pair base = (0,0);
pair preMigrationCenter = (150, 125);
//////////////////////////// Utility functions ///////////////////////////
real getRandomRadius(real lowerBound, real upperBound, int i)
{
srand(seconds()+i);
real randomRadius = (upperBound - lowerBound)*unitrand() + lowerBound;
return randomRadius;
}
real getRandomTheta(int i)
{
srand(seconds()+11*(i+3));
real randomTheta = 360*unitrand();
return randomTheta;
}
real[] computeConfiguration(pair migrationCenter, real randomRadius, real randomTheta, int i)
{
srand(seconds()+i*19);
real xCoord = migrationCenter.x + randomRadius*Cos(randomTheta);
real yCoord = migrationCenter.y + randomRadius*Sin(randomTheta);
real orientation = unitrand()*360;
real[] configuration = {xCoord, yCoord, orientation};
return configuration;
}
void plot(real[] configuration)
{
label(rotate(configuration[2], base)*graphic("ant.png","scale=0.03"), (configuration[0], configuration[1]));
}
void process(pair migrationCenter, real marginalPopulation, real smallerRadius, real largerRadius)
{
for (int i = 1; i < marginalPopulation + 1; ++i)
{
real randomRadius = getRandomRadius(smallerRadius, largerRadius, i);
real randomTheta = getRandomTheta(i);
real[] configuration = computeConfiguration(migrationCenter, randomRadius, randomTheta, i);
plot(configuration);
}
}
/////////////////////////////// Operations ///////////////////////////////
path preMostOuterCircle = circle(preMigrationCenter, mostOuterRadius);
draw(preMostOuterCircle, red+dashed); | {
"domain": "codereview.stackexchange",
"id": 43951,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "random, graphics, asymptote",
"url": null
} |
random, graphics, asymptote
process(preMigrationCenter, mostInnerPopulation, 0, mostInnerRadius);
sleep(1);
process(preMigrationCenter, innerPopulation, mostInnerRadius, innerRadius);
sleep(2);
process(preMigrationCenter, outerPopulation, innerRadius, outerRadius);
sleep(1);
process(preMigrationCenter, mostOuterPopulation, outerRadius, mostOuterRadius);
one may execute
asy.exe -f pdf <file_name>.asy
to get something like
Any comments on the code quality, readibility, and performance, especially the way I have managed the random generations using multiple srand() calls, is appreciated.
Answer:
srand(seconds()+i);
srand(seconds()+11*(i+3));
srand(seconds()+i*19);
The way that pseudorandom generators normally work is that you seed them (sometimes implicitly) and then they produce a predictable but changing sequence.
Here though, if you call these functions with the same value of i and have not crossed a second boundary, you will get the same "random" value. Presumably that's why you added the extra stuff like +11*(i+3) so as to at least get three different values.
A better approach (although still not cryptographically secure) is to call srand once. I would put it at the beginning of the section that you call "Operations". A simple
srand(seconds());
path preMostOuterCircle = circle(preMigrationCenter, mostOuterRadius); | {
"domain": "codereview.stackexchange",
"id": 43951,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "random, graphics, asymptote",
"url": null
} |
random, graphics, asymptote
The second line is unchanged from your original code and only included for context.
Then you can get rid of the rest of the srand calls and the sleep calls.
A more complicated solution would define some kind of flag variable globally as false. Then each of these functions could check if the flag is true. If not, they could call srand(seconds()); and set the flag to true. It might perhaps be possible to do that in an Asymptote package that would include the random functions (getRandomRadius, getRandomTheta, and computeConfiguration).
It might also be possible to call srand automatically when a package is imported. That would be both simple and robust if you only call rand/unitrand from one package.
Whether you do it by manually invoking srand as part of your operations or automatically in a package, what's important is that you call it once per program invocation before ever calling unitrand (or rand). Note that you can define the functions first. What's important is when it is invoked for the first time. It doesn't matter when the function is defined; it does matter when it is called.
If you want to avoid being able to invoke the code twice quickly with the same results, you might consider instead using srand(cputime().change.clock));. But still call it once per program invocation.
I'm not seeing documentation of how Asymptote implements srand. So I'm guessing that it basically calls the C or C++ srand. It seems to be implemented in C++ (GitHub) | {
"domain": "codereview.stackexchange",
"id": 43951,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "random, graphics, asymptote",
"url": null
} |
python, python-3.x
Title: how to simplify conditional code in python
Question: I am a student I am new to python, This is my first code, any one help me to simplify this code.
A=[5,"c","d"]
total=0
for item in A:
if (item == 5):
total= item
if (item == "c"):
total= total-1
if (item == "d"):
total= total*2
print("total",total)
my requirement:
when the array loop is run, if the loop find the 'c' charactor it should reduce the previous value. incase there is a 'd' in loop, it should double the previous value. for me I am getting result as 8. it fine. looking for clean and simple way to get the same as learning.
Answer: Without knowing what the code is supposed to do this looks straight forward enough. You do, however, probably have a bug in where your print function is placed - I think you want it one or two levels dedented, so it either prints the current total or else prints the final total.
You can improve both performance and readability somewhat by using elif over if for the second and third conditional check, and you can use operators like -= and *= to shorten the code somewhat.
All in all:
arr = [5, "c", "d"]
total = 0
for item in arr:
if (item == 5):
total = item
elif (item == "c"):
total -= 1
elif (item == "d"):
total *= 2
print(total) | {
"domain": "codereview.stackexchange",
"id": 43952,
"lm_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",
"url": null
} |
python, web-scraping, pandas, beautifulsoup
Title: Web scraper for data sources from Statistics Canada
Question: I've written a parser to scrape data from Canadian Statistics Bureau.
import re
import pandas as pd
import requests
from bs4 import BeautifulSoup
def get_number_of_sources() -> int:
'''
Retrieves Number of STATCAN Sources
Returns
-------
int
Number of STATCAN Sources.
'''
URL = 'https://www150.statcan.gc.ca/n1/en/type/data'
page = requests.get(URL)
soup = BeautifulSoup(page.text, 'lxml')
result = re.search(r'\((.*?)\)', soup.summary.get_text()).group(1)
return int(result.replace(',', ''))
def main():
'''
Builds Resulting DataFrame and Dumps It To Excel File
Returns
-------
None.
'''
FILE_NAME = 'stat_can_all.xlsx'
number_of_sources = get_number_of_sources()
data_list = []
for _ in range(1 + number_of_sources // 100):
GENERIC_URL = 'https://www150.statcan.gc.ca/n1/en/type/data?count=100&p={}-All#all'
page = requests.get(GENERIC_URL.format(_))
print(f'Parsing Page {1+_:3} Out of {1+number_of_sources // 100}')
soup = BeautifulSoup(page.text, 'lxml')
details_soup = soup.find('details', id='all')
items = details_soup.find_all('li', {'class': 'ndm-item'})
for item in items:
tag_description = item.find('div', class_='ndm-result-description')
tag_former_id = item.find('div', class_='ndm-result-formerid')
tag_frequency = item.find('div', class_='ndm-result-freq')
tag_geo = item.find('div', class_='ndm-result-geo') | {
"domain": "codereview.stackexchange",
"id": 43953,
"lm_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, web-scraping, pandas, beautifulsoup",
"url": null
} |
python, web-scraping, pandas, beautifulsoup
data_list.append(
{
'title': item.find('div', class_='ndm-result-title').get_text(),
'product_id': item.find('div', class_='ndm-result-productid').get_text(),
'former_id': None if tag_former_id is None else tag_former_id.get_text(),
'geo': None if tag_geo is None else tag_geo.get_text(),
'frequency': None if tag_frequency is None else tag_frequency.get_text(),
'description': None if tag_description is None else tag_description.get_text(),
'release_date': item.find('span', class_='ndm-result-date').get_text(),
'type': item.find(
'div',
class_='ndm-result-productid'
).get_text().split(':')[0],
'ref': item.a.get('href'),
}
)
data = pd.DataFrame.from_dict(data_list)
data[['id', 'title_only']] = data.iloc[:, 0].str.split(
pat='. ',
n=1,
expand=True
)
data['id'] = pd.to_numeric(data['id'].str.replace(',', ''))
data.fillna('None').to_excel(FILE_NAME, index=False)
if __name__ == '__main__':
main()
Was wondering if there is a way to rephrase the following and alike lines of code representing ternary operator:
'former_id': None if tag_former_id is None else tag_former_id.get_text()
to have it more elegant and concise.
You can see that if tag_former_id is an instance of class bs4.element.Tag, one can use .get_text() method to retrieve str.
Otherwise, tag_former_id may be None and no further action is required.
Please could you review this piece and point at departures from the best practices?
Any other suggestions for improvements are also quite welcome, e.g. to bring more functional approach into the code etc. | {
"domain": "codereview.stackexchange",
"id": 43953,
"lm_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, web-scraping, pandas, beautifulsoup",
"url": null
} |
python, web-scraping, pandas, beautifulsoup
Answer: For your particular question about the ternary operator, you can use and:
'former_id': tag_former_id and tag_former_id.get_text(),
I don't think it's super pretty/obvious, but it's more compact than the full ternary operator.
Instead of CONSTANT variables, e.g. FILE_NAME. I'd say to replace these with parameters with defaults:
def main(
file_name='stat_can_all.xlsx',
...
):
Docstrings should use """ instead of '''. Also, while your format is very pretty, you'll have better luck (better IDE integration, parsing by Sphinx, etc.) if you use a standard format. The Google Style is a very popular format to use. | {
"domain": "codereview.stackexchange",
"id": 43953,
"lm_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, web-scraping, pandas, beautifulsoup",
"url": null
} |
performance, python-3.x, programming-challenge, comparative-review, dart
Title: LeetCode#494 target sum (dart is slower than python)
Question: I'm trying to solve a LeetCode problem target-sum, in two languages: Python & Dart. The difference of time taken is shocking for me"
Python took ~70ms while Dart took ~900ms !! Why does Dart take so long? screenshot
What should I do to improve Dart performance?
Solution in two different languages are as follows (same approach):
Python:
class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
dp = {}
def calculate(i, total):
if(i == len(nums)):
return 1 if (total == target) else 0
if((i, total) in dp):
return dp[(i, total)]
dp[(i, total)] = calculate(i+1, total + nums[i]) + calculate(i+1, total - nums[i])
return dp[(i, total)]
return calculate(0, 0)
Dart
class Solution {
int findTargetSumWays(List<int> nums, int target) {
Map<MapEntry<int, int>, int> dp = {};
int calculate(int i, int sum) {
if (i == nums.length) {
return sum == target ? 1 : 0;
}
final pair = MapEntry(i, sum);
return dp[pair] ??
(dp[pair] = calculate(i + 1, sum + nums[i]) +
calculate(i + 1, sum - nums[i]));
}
return calculate(0, 0);
}
}
Is Dart map causing this delay? If so what operations should I use?
Answer: Use hashable types as hashtable keys
An important requirement of hashtables is that they keys must be hashable:
has a .hashCode implementation that returns the same value for two objects that are equal
has a .equals implementation that returns true for two objects that are equal
Looking at the documentation of MapEntry,
it looks like it inherits the hashCode and equals implementations from Object,
which means it's not hashable.
The problem is that these objects are not equal:
MapEntry x = MapEntry(a, b);
MapEntry y = MapEntry(a, b); | {
"domain": "codereview.stackexchange",
"id": 43954,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, python-3.x, programming-challenge, comparative-review, dart",
"url": null
} |
performance, python-3.x, programming-challenge, comparative-review, dart
This breaks the caching mechanism of the code,
everything is recomputed.
You could implement a Pair with suitable hashCode and equals:
class Pair {
final int first, second;
Pair(this.first, this.second);
bool operator==(Object other) =>
other is Pair && first == other.first && second == other.second;
int get hashCode => Object.hash(first, second);
}
Alternatively, you could compute a key to use with the cache,
given the range of inputs in the problem description:
class Solution {
int findTargetSumWays(List<int> nums, int target) {
Map<int, int> dp = {};
int calculate(int i, int sum) {
if (i == nums.length) {
return sum == target ? 1 : 0;
}
final k = key(i, sum);
return dp[k] ??
(dp[k] = calculate(i + 1, sum + nums[i]) +
calculate(i + 1, sum - nums[i]));
}
return calculate(0, 0);
}
int key(int index, int sum) {
return sum * 1001 + index;
}
}
Using this key function saves the overhead of object creation.
Programming challenge sites are not benchmarking tools
These sites are not proper benchmarking tools,
and there are far too many unknowns an outsider simply cannot know:
how efficiently are the program executors implemented for each language
do the programs run on the same hardware
do the programs run on the same network (same latency)
To name just a few.
Don't read too much meaning into the timing results on these sites.
They are just good enough to decide if your solution has the target time and space complexity.
Improve the Python code
There are many redundant parentheses:
if(i == len(nums)):
return 1 if (total == target) else 0
if((i, total) in dp):
return dp[(i, total)]
These could be:
if i == len(nums):
return 1 if (total == target) else 0
if (i, total) in dp:
return dp[i, total] | {
"domain": "codereview.stackexchange",
"id": 43954,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, python-3.x, programming-challenge, comparative-review, dart",
"url": null
} |
performance, python-3.x, programming-challenge, comparative-review, dart
if (i, total) in dp:
return dp[i, total]
You can also take advantage that False is 0 in integer context,
and True is 1, simplifying the first conditional:
if i == len(nums):
return total == target
Lastly, instead of using dict as the cache,
you can benefit from @cache in functools (implicitly imported on leetcode).
Putting it together:
class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
@cache
def calculate(i, total):
if i == len(nums):
return total == target
return calculate(i+1, total + nums[i]) + calculate(i+1, total - nums[i])
return calculate(0, 0) | {
"domain": "codereview.stackexchange",
"id": 43954,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, python-3.x, programming-challenge, comparative-review, dart",
"url": null
} |
linux, portability, posix, sh, color
Title: *nix, *bsd, etc basic `tput` color setup
Question: My goal with the below piece of POSIX shell code was to address the more platforms the better with shell tput colors. With this code, I now start all of my scripts, and so it's time to review it for some things I overlooked, did not think of too well, and such. Note: I start my scripts with set -u, which is why I set all empty in unspecified cases. Thanks.
#!/bin/sh
set -u
if tput setaf > /dev/null 2>&1; then
# Linux-like
tput_number_of_colors=$(tput colors 2> /dev/null)
tput_bold=$(tput bold 2> /dev/null)
tput_reset=$(tput sgr0 2> /dev/null)
tput_cmd_set_fg_color='tput setaf'
elif tput AF > /dev/null 2>&1; then
# BSD-like
tput_number_of_colors=$(tput Co 2> /dev/null)
tput_bold=$(tput md 2> /dev/null)
tput_reset=$(tput me 2> /dev/null)
tput_cmd_set_fg_color='tput AF'
else
# Console-like
tput_number_of_colors=2
tput_cmd_set_fg_color=
tput_bold=
tput_reset=
fi
tput_test ()
{
[ -n "$tput_number_of_colors" ] && [ -n "$tput_bold" ] && [ -n "$tput_reset" ] &&
{ [ "$tput_number_of_colors" -ge 8 ] && printf '%s' "$tput_bold" && $tput_cmd_set_fg_color 1; } > /dev/null 2>&1
}
if tput_test; then
color_red=$tput_bold$($tput_cmd_set_fg_color 1)
color_green=$tput_bold$($tput_cmd_set_fg_color 2)
color_yellow=$tput_bold$($tput_cmd_set_fg_color 3)
color_blue=$tput_bold$($tput_cmd_set_fg_color 4)
color_magenta=$tput_bold$($tput_cmd_set_fg_color 5)
color_cyan=$tput_bold$($tput_cmd_set_fg_color 6)
color_white=$tput_bold$($tput_cmd_set_fg_color 7)
else
color_red=; color_green=; color_yellow=; color_blue=; color_magenta=; color_cyan=; color_white=
fi
Answer: Self-review
Since no one replied thus far, I decided to re-think and re-write the code myself this morning. | {
"domain": "codereview.stackexchange",
"id": 43955,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, portability, posix, sh, color",
"url": null
} |
linux, portability, posix, sh, color
terminfo (*nix) vs termcap (*bsd)
I never really thought about how important to make note of this actually is. For searching info online, one needs to know these keywords. So, I added them as comments.
Structure into functions
I believe this code should be structured into suitable functions where available.
Find a way for an exit code from those functions
It's needed to simply chain (&&) the commands like tput_bold=$(tput bold 2> /dev/null) && tput_reset=$(tput sgr0 2> /dev/null) in order for the imagined functions to return a reliable exit code.
The most basic test missing
command -v tput was missing in my code, which is remedied now.
No unset variables
Since I use set -u in my scripts, it's necessary to set variables empty in case of failure. This feature has been enhanced.
Modified code
#!/bin/sh
set -u
tput_setup_nix ()
{
# terminfo
tput_cmd_set_fg_color='tput setaf'
tput_number_of_colors=$(tput colors 2> /dev/null) &&
tput_bold=$(tput bold 2> /dev/null) &&
tput_reset=$(tput sgr0 2> /dev/null)
}
tput_setup_bsd ()
{
# termcap
tput_cmd_set_fg_color='tput AF'
tput_number_of_colors=$(tput Co 2> /dev/null) &&
tput_bold=$(tput md 2> /dev/null) &&
tput_reset=$(tput me 2> /dev/null)
}
tput_setup_none ()
{
# no unset variables
tput_cmd_set_fg_color=
tput_number_of_colors=
tput_bold=
tput_reset=
}
if command -v tput > /dev/null 2>&1; then
if tput setaf > /dev/null 2>&1; then
if ! tput_setup_nix; then tput_setup_none; fi
elif tput AF > /dev/null 2>&1; then
if ! tput_setup_bsd; then tput_setup_none; fi
else
tput_setup_none
fi
else
tput_setup_none
fi
tput_capability_test ()
{
[ -n "$tput_cmd_set_fg_color" ] && [ -n "$tput_number_of_colors" ] && [ -n "$tput_bold" ] && [ -n "$tput_reset" ] &&
[ "$tput_number_of_colors" -ge 8 ] && { $tput_cmd_set_fg_color 1 && printf '%s' "$tput_bold$tput_reset"; } > /dev/null 2>&1
} | {
"domain": "codereview.stackexchange",
"id": 43955,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, portability, posix, sh, color",
"url": null
} |
linux, portability, posix, sh, color
}
if tput_capability_test; then
color_red=$tput_bold$($tput_cmd_set_fg_color 1)
color_green=$tput_bold$($tput_cmd_set_fg_color 2)
color_yellow=$tput_bold$($tput_cmd_set_fg_color 3)
color_blue=$tput_bold$($tput_cmd_set_fg_color 4)
color_magenta=$tput_bold$($tput_cmd_set_fg_color 5)
color_cyan=$tput_bold$($tput_cmd_set_fg_color 6)
color_white=$tput_bold$($tput_cmd_set_fg_color 7)
else
color_red=
color_green=
color_yellow=
color_blue=
color_magenta=
color_cyan=
color_white=
fi | {
"domain": "codereview.stackexchange",
"id": 43955,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, portability, posix, sh, color",
"url": null
} |
c#, javascript, object-oriented, jquery
Title: Creating object in JS that is passed into IHttpHandler
Question: I am working on a web page where I am creating a JS object using {} and []. This object is passed into a handler
I wanted to see if there is any more way to write this method. Its a lot of code and just wanted to make sure there is no better way to do this?
My logic
Is to build the object is JS and then pass it into the Handler to be Deserialize and then saved into the db.
function saveLongAnswerText() {
console.log('%c saveLongAnswerText ', 'background: #222; color: #bada55');
if ($("#form1").valid()) {
MeetingPollingQuestion = {};
MeetingPollingQuestion.MeetingPollingId = $("#hfMeetingPollingId").val();
MeetingPollingQuestion.MeetingPollingQuestionType = "LongAnswerText";
MeetingPollingQuestion.SequenceOrder = 2;
MeetingPollingQuestion.MeetingPollingParts = [];
MeetingPollingParts = {};
MeetingPollingParts.Type = "Question";
MeetingPollingParts.MeetingPollingPartsValues = [];
MeetingPollingPartsValues = {};
MeetingPollingPartsValues.Type = "Question";
MeetingPollingPartsValues.QuestionValue = $("#editorLongAnswerText").data("kendoEditor").value();
MeetingPollingParts.MeetingPollingPartsValues.push(MeetingPollingPartsValues);
MeetingPollingQuestion.MeetingPollingParts.push(MeetingPollingParts);
console.log(MeetingPollingQuestion);
Metronic.blockUI({ boxed: true, message: "Saving Question.." });
$.ajax({
type: 'POST',
url: 'ManagePolling.ashx',
data: { "PollingQuestion": JSON.stringify(MeetingPollingQuestion), "Action": "SaveQuestion" },
datatype: "JSON",
success: function (data) {
if (data.resultStatus.ResultCode == "1") {
toastr.success("Saved successfully", "Success"); | {
"domain": "codereview.stackexchange",
"id": 43956,
"lm_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#, javascript, object-oriented, jquery",
"url": null
} |
c#, javascript, object-oriented, jquery
}
if (data.resultStatus.ResultCode == "2")
toastr.warning(data.resultStatus.Message, "Warning");
if (data.resultStatus.ResultCode == "3")
toastr.warning(data.resultStatus.Message, "Error");
Metronic.unblockUI();
},
error: function (data) {
toastr.error('An error has occured! \n' + data.resultStatus.Message);
Metronic.unblockUI();
}
});
}
}
Handler
string jsonData = context.Request.Form["PollingQuestion"];
var MeetingPollingQuestion = new Model.MeetingPollingQuestion();
var MeetingPollingParts = new List<Model.MeetingPollingParts>();
var MeetingPollingPartsValues = new List<Model.MeetingPollingPartsValues>();
MeetingPollingQuestion.MeetingPollingParts = MeetingPollingParts;
MeetingPollingQuestion = Deserialize<Model.MeetingPollingQuestion>(jsonData);
Answer: Client-side
Prefer fail fast
Rather than guarding the whole object creation and the ajax communication logic with a condition if ($("#form1").valid()) please prefer early exit
if (!$("#form1").valid()) return;
Prefer object and collection initializer
Rather than using value assignment you can use object initializer to avoid repetitive code
const MeetingPollingQuestion = {
MeetingPollingId: $("#hfMeetingPollingId").val(),
MeetingPollingQuestionType: "LongAnswerText",
SequenceOrder: 2,
MeetingPollingParts: [
{
Type: "Question",
MeetingPollingPartsValues: [
{
Type: "Question",
QuestionValue: $("#editorLongAnswerText").data("kendoEditor").value()
}
]
}
]
};
Try to avoid mixing stringify and object initializer
This line seems really odd to me
data: { "PollingQuestion": JSON.stringify(MeetingPollingQuestion), "Action": "SaveQuestion" } | {
"domain": "codereview.stackexchange",
"id": 43956,
"lm_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#, javascript, object-oriented, jquery",
"url": null
} |
c#, javascript, object-oriented, jquery
data: { "PollingQuestion": JSON.stringify(MeetingPollingQuestion), "Action": "SaveQuestion" }
I would suggest to use object initializer first and then stringify it
data: JSON.stringify({ PollingQuestion: MeetingPollingQuestion, Action: "SaveQuestion" })
Naming
I would suggest to consolidate your naming strategy because even in a simple line you have Pascal and camel Casing as well
data.resultStatus.ResultCode
It is minor but please also try to consolidate the usage of ' and "
Please prefer switch
Rather than having 3 if branches (.ResultCode == "1" ... .ResultCode == "3") please prefer to use switch
switch (data.resultStatus.ResultCode) {
case "1": toastr.success("Saved successfully", "Success"); break;
case "2": toastr.warning(data.resultStatus.Message, "Warning"); break;
case "3": toastr.warning(data.resultStatus.Message, "Error"); break;
}
Server-side
The MeetingPollingPartsValues variable is not used
I think the MeetingPollingParts variable is not needed because you overwrite the entire MeetingPollingQuestion object
So, the entire method could be simplified for the following line
var meetingPollingQuestion = Deserialize<Model.MeetingPollingQuestion>(context.Request.Form["PollingQuestion"]); | {
"domain": "codereview.stackexchange",
"id": 43956,
"lm_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#, javascript, object-oriented, jquery",
"url": null
} |
python, beginner, programming-challenge
Title: Creating Phone Number challenge from Code Wars
Question: I solved a question on Codewars about creating a phone number:
Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.
Example
createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) // => returns "(123) 456-7890"
The returned format must be correct in order to complete this challenge.
Don't forget the space after the closing parentheses!
Here's my solution how to improve i struggled with this solution to came up a lot but at the end i completed it i have some problems when i try to iterate through each integer because code makes duplicates but i fixed it with slicing and code works , for example where i've had a problem:
My Solution--->(111) 1111-1111
Solution how should look like--->(111) 111-1111
But i figured it out for better solutions and tell me if its code it's good or i should change something!
def create_phone_number(n):
res = "("
x_string = "".join([str(x) for x in n])
x_new_string = "".join(x_string)
for i in range(len(n)):
if i == 2:
res += x_new_string[i] + ") "
if i == 5:
res += x_new_string[i] + "-"
else:
res += x_new_string[i]
return res[0:5] + " " + res[7:]
Answer: Loop like a native
You are using range(len(n)) to iterate over n using an index. This is similar to how iterations are handled in most languages but in Python, there is almost always a better way to write this. I highly recommend the talk "Look like a native" which explains this in details.
In you particular case, using enumerate makes things much cleaner, faster and more Pythonic:
def create_phone_number2(n):
res = "("
for i, c in enumerate([str(x) for x in n]):
if i == 2:
res += c + ") "
if i == 5:
res += c + "-"
else:
res += c
return res[0:5] + " " + res[7:] | {
"domain": "codereview.stackexchange",
"id": 43957,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, programming-challenge",
"url": null
} |
python, beginner, programming-challenge
I took this chance to remove the call to join as per ades' answer.
String handling
It seems weird to have some logic to format res and yet have some more code to reformat res at the end by selecting the relevant parts of the string.
At the end of the day, it looks like this last step is just a workaround for a bug in a different part of the code: a character is introduced twice in the res and must we removed.
The issue is that when i == 2, we add the character twice:
first with res += x_new_string[i] + ") "
then with res += x_new_string[i]
Using elif makes things cleaner and solves the issue:
def create_phone_number2(n):
res = "("
for i, c in enumerate([str(x) for x in n]):
if i == 2:
res += c + ") "
elif i == 5:
res += c + "-"
else:
res += c
return res
More simplification
Adding c could be done in a single place. Also, this could be the place where we convert to string.
def create_phone_number2(n):
res = "("
for i, c in enumerate(n):
res += str(c)
if i == 2:
res += ") "
elif i == 5:
res += "-"
return res
Other options
Instead of messing with indices, an alternative could be to rely on the features from Python such as string formatting. For instance, one could write:
def create_phone_number3(n):
return "(%d%d%d) %d%d%d-%d%d%d%d" % (n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[8], n[9])
This can probably be improved further for instance, using Greedo's suggestion:
def create_phone_number3(n):
return "({}{}{}) - {}{}{} {}{}{}{}".format(*n) | {
"domain": "codereview.stackexchange",
"id": 43957,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, programming-challenge",
"url": null
} |
java, programming-challenge, strings, cryptography, genetic-algorithm
Title: An evolutionary algorithm written in Java to crack an XOR cipher
Question: Alright. So TryHackme is a website that tries to teach hacking with hands on labs. They have a room called JVM Reverse Engineering where the user gets to reverse engineer Java apps, and in particular the code that I am asking you to review is for task #5.
Task #5 challenges the user to crack a password encrypted with a simple XOR cipher. You can reverse engineer the app yourself, but here are the important bits:
Firstly, their xor cipher is defined as the following String:
// Decompiled from the task #5 challenge.
private static String xor(String var0) {
char[] var1 = var0.toCharArray();
char[] var2 = new char[var1.length];
for(int var3 = 0; var3 < var2.length; ++var3) {
char var4 = var1[var3];
var2[var3] = (char)(var4 ^ var3 % 3);
}
return new String(var2);
}
Secondly, the password is correct if the XOR of the inputted password is equal to the xor of the correctPassword, which is a string equal to aRa2lPT6A6gIqm4RE.
My solution is to use my own modified and applied version of Dawkins' weasel to "evolve," for lack of a better term, a solution to what the "password" might be. When looking at my code, I would like feedback as to make it better. Here are some things to consider in your feedback:
Can I adopt better a coding style?
Can I make my code smaller without compromising its ease of reading?
Can I optimise my code to make it run quicker? | {
"domain": "codereview.stackexchange",
"id": 43958,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, programming-challenge, strings, cryptography, genetic-algorithm",
"url": null
} |
java, programming-challenge, strings, cryptography, genetic-algorithm
The following is my code:
/*
* An application to crack an XOR cipher using Dawkins' weasel
* By A. S. "Aleksey" Ahmann <hackermaneia@riseup.net>
* - Githubs: https://github.com/Alekseyyy
* - TryHackMe: https://tryhackme.com/p/EntropyThot
*
* Note that some parts of this programme are borrowed from o-
* -ther sources. Most notably, the "xor" function that retur-
* -ns a String is the result of decompiling the .class file
* of TryHackMe's problem. P1's random string generator is ba-
* -sed off of the following website:
* - https://www.baeldung.com/java-random-string
*/
import java.io.*;
import java.util.*;
public class Dawkins {
private static final String correctPassword = "aRa2lPT6A6gIqm4RE";
public static void main(String[] args) {
Random random = new Random();
int counter = 1;
char[] target = correctPassword.toCharArray();
char[] solution = new char[target.length];
System.out.println("==========================================================");
System.out.println("= A crude, amateurish implementation of Dawkins' ");
System.out.println("= weasel to crack the TryHackMe XOR cipher ");
System.out.println("= By A. S. \"Aleksey\" Ahmann <hackermaneia@riseup.net> ");
System.out.println("= - https://github.com/Alekseyyy ");
System.out.println("= - https://tryhackme.com/p/EntropyThot ");
System.out.println("==========================================================\n"); | {
"domain": "codereview.stackexchange",
"id": 43958,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, programming-challenge, strings, cryptography, genetic-algorithm",
"url": null
} |
java, programming-challenge, strings, cryptography, genetic-algorithm
boolean done = false;
while (!done) {
// [P1] Generate random string (of course the length of random string should = correctPassword)
// - this "seed" is based off of the following: https://www.baeldung.com/java-random-string
char[] seed = random.ints(48, 123)
.filter(k -> (k <= 57 || k >= 65) && (k <= 90 || k >= 97))
.limit(target.length)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString().toCharArray();
// [P2] Put the random string through the xor cipher, and split it into char array of course
char[] nextGen = xor(new String(seed)).toCharArray();
// [P3] Save the matching characters as "offspring"
boolean emptySlots = false;
for (int k = 0; k < solution.length; k++) {
if (solution[k] != Character.MIN_VALUE) {
continue;
}
else {
emptySlots = true;
if (nextGen[k] == target[k]) {
solution[k] = seed[k];
}
}
}
System.out.printf("Generation %d: %s\n", counter, new String(solution));
counter++;
if (!emptySlots) {
done = true;
}
}
System.out.printf("Solution: %s\n", new String(solution));
}
// From the decompile dump of "BasicStringObfuscation.class"
private static String xor(String var0) {
char[] var1 = var0.toCharArray();
char[] var2 = new char[var1.length];
for(int var3 = 0; var3 < var2.length; ++var3) {
char var4 = var1[var3];
var2[var3] = (char)(var4 ^ var3 % 3);
}
return new String(var2);
}
}
``` | {
"domain": "codereview.stackexchange",
"id": 43958,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, programming-challenge, strings, cryptography, genetic-algorithm",
"url": null
} |
java, programming-challenge, strings, cryptography, genetic-algorithm
return new String(var2);
}
}
```
Answer: Disclaimer: I'm no Java expert and I may have missed some of the point of the code.
Last iteration
When iterating the characters of solution to check whether it is valid, we rely on its previous value instead of the one we may possible give it.
Hence, we go through an additional iteration even though we could stop directly.
Here is my suggestion
// [P3] Save the matching characters as "offspring"
boolean solutionIsValid = true;
for (int i = 0; i < solution.length; i++) {
if (solution[i] == Character.MIN_VALUE) {
if (cipheredSeed[i] == target[i]) {
solution[i] = seed[i];
} else {
solutionIsValid = false;
}
}
}
I took this chance to:
get rid of continue
rename a few things
Principle
A lot of time is spent generating random values, ciphering them and checking the ciphered value but most of the characters ciphered and wrong and/or unused.
Because each character is ciphered independenly (otherwise, the whole logic here would fail), it may be faster to progress character by character.
This gives something like:
/*
* An application to crack an XOR cipher using Dawkins' weasel
* By A. S. "Aleksey" Ahmann <hackermaneia@riseup.net>
* - Githubs: https://github.com/Alekseyyy
* - TryHackMe: https://tryhackme.com/p/EntropyThot
*
* Note that some parts of this programme are borrowed from o-
* -ther sources. Most notably, the "xor_str" function that retur-
* -ns a String is the result of decompiling the .class file
* of TryHackMe's problem. P1's random string generator is ba-
* -sed off of the following website:
* - https://www.baeldung.com/java-random-string
*/
import java.io.*;
import java.util.*;
public class Dawkins {
private static final String correctPassword = "aRa2lPT6A6gIqm4RE"; | {
"domain": "codereview.stackexchange",
"id": 43958,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, programming-challenge, strings, cryptography, genetic-algorithm",
"url": null
} |
java, programming-challenge, strings, cryptography, genetic-algorithm
public class Dawkins {
private static final String correctPassword = "aRa2lPT6A6gIqm4RE";
public static void main(String[] args) {
char[] target = correctPassword.toCharArray();
char[] solution = new char[target.length];
System.out.println("==========================================================");
System.out.println("= A crude, amateurish implementation of Dawkins' ");
System.out.println("= weasel to crack the TryHackMe XOR cipher ");
System.out.println("= By A. S. \"Aleksey\" Ahmann <hackermaneia@riseup.net> ");
System.out.println("= - https://github.com/Alekseyyy ");
System.out.println("= - https://tryhackme.com/p/EntropyThot ");
System.out.println("==========================================================\n");
for (int i = 0; i < solution.length; i++) {
// Loop over candidates
for (char c = 48; c <= 123; c++) {
if ((c <= 57 || c >= 65) && (c <= 90 || c >= 97)) {
// Check if valid
if (xor_c(c, i) == target[i]) {
solution[i] = c;
}
}
}
}
// TODO: Handle cases when 0 or many characters are found
System.out.printf("Solution: %s\n", new String(solution));
}
// From the decompile dump of "BasicStringObfuscation.class" and then refactored
private static char xor_c(char c, int index) {
return (char)(c ^ index % 3);
}
private static String xor_str(String s) {
char[] input = s.toCharArray();
char[] output = new char[input.length];
for(int i = 0; i < output.length; ++i) {
output[i] = xor_c(input[i], i);
}
return new String(output);
}
} | {
"domain": "codereview.stackexchange",
"id": 43958,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, programming-challenge, strings, cryptography, genetic-algorithm",
"url": null
} |
java, programming-challenge, strings, cryptography, genetic-algorithm
Then, if we are ready to take into the actual logic in xor_c, we could compute the solution value directly by performing the opposite of the operations. In this particular case, the function to decipher is actually the one used to cipher as well. This idea does not generalize to an arbitrary cipher function. | {
"domain": "codereview.stackexchange",
"id": 43958,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, programming-challenge, strings, cryptography, genetic-algorithm",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.