text
stringlengths
1
2.12k
source
dict
python, python-3.x def change_structure(current_folder: str) -> None: parent_dir = Path.cwd() / current_folder for folder in parent_dir.iterdir(): if not folder.is_dir(): continue for child in folder.iterdir(): if not child.name.startswith('.'): child.rename(parent_dir / child.name) shutil.rmtree(folder) print("All folders removed") if __name__ == '__main__': change_structure(sys.argv[1])
{ "domain": "codereview.stackexchange", "id": 43085, "lm_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 }
performance, python-3.x Title: Ising Model simulation in Numpy Question: I've written this code to simulate the Ising Model. The idea is a system represented as a matrix with each element having value 1 or -1. The input is an initial matrix of 1 and -1; it is then being subjected to this algorithm: Pick a random element of the matrix calculate the energy change of the system if that element is flipped (turn 1 to -1 vice versa) if the flipping reduces total energy (after/before < 0): do it, else: flip it with probability $$ P = \exp(-\text{constant}*\text{energy difference}) $$ $$0 \le P \le 1$$ (I added an extra term in the code to modify its dynamics.) Energy is calculated by observing the spin of an element with its neighbor, so I use two matrices for this calculation: the main matrix (the one subjected to the function), an adjacency matrix (representing connection between each elements from the main matrix: 1 if connected, else 0). The idea is to multiply the row from the adjacency matrix to all elements of the main matrix. The code works but since I have to apply the function for thousands of times and it uses two (rather large) matrices, the calculation takes a lot of time. Perhaps ideas for speed-ups (or just for writing a better code in general) and possibility to use numba which currently gives me complicated error messages. import numpy as np n = 64 n2 = n**2 main_matrix = 2*np.random.randint(2, size=(n, n))-1 adj_matrix = np.random.randint(2, size=(n2, n2)) # Assume random network is used def mcmove(beta): a = np.random.randint(0, n) b = np.random.randint(0, n) s = main_matrix[a, b] energy_difference = np.sum(np.multiply(adj_matrix[a*n + b], main_matrix.reshape(1,-1)[0]))/np.sum(adj_matrix[a*n + b]) cost = 2*s*(energy_difference - s*abs(np.sum(main_matrix))/n2) if cost < 0: s *= -1 elif np.random.rand() < np.exp(-cost*beta): s *= -1 main_matrix[a, b] = s return main_matrix # How this function is used total_spin = []
{ "domain": "codereview.stackexchange", "id": 43086, "lm_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", "url": null }
performance, python-3.x # How this function is used total_spin = [] for i in range(1000): for i in range(n2): mcmove(0.001*i) total_spin.append(np.sum(main_matrix)) # sum all spins total_spin Answer: Stop using np.random.randint and family; they're deprecated in favour of the new generators. You can assign a and b in one go by generating an integer array of length 2. Add PEP484 type hints. Don't np.multiply; in this case use np.dot since effectively you are calculating a dot product. Don't reshape; your reshape is equivalent to a flatten(). Use np.abs instead of abs. Don't elif; this is equivalent to an or sub-expression. Don't return main_matrix; that's ignored and you're mutating in-place. Use a different letter for your inner for i iteration, probably j. Rather than 0.001 * i, find this value directly by iterating over a call to np.linspace. Rather than total_spin.append, pre-allocate a properly typed, empty numpy array. Other than the above there isn't much you can improve in terms of performance since the iterations are not independent: an evolved main_matrix depends on the value of main_matrix from the previous iteration. At that point you would drop down to a better language like C and calls to cblas or equivalent. Suggested import numpy as np n = 64 n2 = n**2 rand = np.random.default_rng(seed=0) main_matrix = rand.choice((-1, 1), size=(n, n)) adj_matrix = rand.integers(2, size=(n2, n2)) # Assume random network is used def mcmove(beta: float) -> None: a, b = rand.integers(low=0, high=n, size=2) s = main_matrix[a, b] adj_row = adj_matrix[a*n + b, :] energy_difference = np.dot(adj_row, main_matrix.flatten()) / adj_row.sum() cost = 2 * s * (energy_difference - s * np.abs(main_matrix.sum()) / n2) if cost < 0 or rand.random() < np.exp(-cost * beta): main_matrix[a, b] = -s def main() -> None: # How this function is used N = 1000 total_spin = np.empty(shape=N, dtype=int)
{ "domain": "codereview.stackexchange", "id": 43086, "lm_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", "url": null }
performance, python-3.x for i in range(N): for j in np.linspace(0, (n2 - 1)/N, n2): mcmove(j) total_spin[i] = main_matrix.sum() # sum all spins print(total_spin) if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 43086, "lm_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", "url": null }
performance, c, strings, lua, ffi Title: Trailing delimiter string splicing, implemented for Lua in C Question: I've been writing with C for a couple days, so this is a relatively advanced function compared to the simple things I've been doing previously. It's written for the Lua API, but it's still C. #include "lua.h" #include "lauxlib.h" #include <stdlib.h> #include <string.h> static int l_rtrim(lua_State *L) { luaL_checktype(L, 1, LUA_TSTRING); luaL_checktype(L, 2, LUA_TSTRING); const char *string = lua_tostring(L, 1); const char *delimiter = lua_tostring(L, 2); if (*string == '\0') { lua_rotate(L, -2, 1); return 1; } size_t len = strlen(string); size_t dlCnt = 0; size_t tmpLen = len - 1; if (tmpLen <= 0) { lua_rotate(L, -2, 1); return 1; } char *copy = malloc(len + 1); if (copy == NULL) { lua_pushstring(L, "out of memory"); lua_error(L); return 1; } memcpy(copy, string, len + 1); while (copy[tmpLen--] == *delimiter) dlCnt++; if (dlCnt > 0) { size_t location = len - dlCnt; if (location > 0) { copy[location] = '\0'; lua_pushstring(L, copy); } else { /* the entire string is composed of the delimiter */ lua_pushliteral(L, ""); } } free(copy); return 1; } static const struct luaL_Reg exports[] = { {"rtrim", l_rtrim}, {NULL, NULL} }; extern __declspec(dllexport) int luaopen_MyModule(lua_State *L) { luaL_newlib(L, exports); return 1; }
{ "domain": "codereview.stackexchange", "id": 43087, "lm_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, strings, lua, ffi", "url": null }
performance, c, strings, lua, ffi My function counts how many delimiters trail on the right side, so I can insert a null-terminator before any of those delimiters arrive. It's very inefficient (2.5x slower) compared to my implementation of left-trimming (leading spaces) because in that, I just perform a pointer increment. My main interest is avoiding UB (because I'm not familiar for when it's invoked) and if there's a method I can use to avoid creating a new string & performing so many allocations & copying during benchmarking. I played around a lot with pointer decrementing but it's not working the way I hoped. Some example inputs and outputs: ("??hello world??", "?") -> "??hello world" (" hello world ", " ") -> " hello world" Answer: Unexpected output Your code returns the original string if it consists of a single delimiter character: rtrim(".", ".") --> "." I find that illogical. If it is the wanted behavior then it should probably be documented. Otherwise remove the size_t tmpLen = len - 1; if (tmpLen <= 0) { lua_rotate(L, -2, 1); return 1; } part. Undefined behavior while (copy[tmpLen--] == *delimiter) dlCnt++; may access memory “before” the start of the string if the string consists only of the delimiter character. I would always enclose if/while/for blocks in curly parentheses, even if they consist of a single statement. A bug If the string does not end with the delimiter character then the delimiter is returned instead of the original string: rtrim("abc", ".") --> "." The reason is that if dlCnt == 0 then no result string is pushed onto the stack. Embedded zeros Lua strings can contain arbitrary bytes, including the null byte. But size_t len = strlen(string); treats the null byte as a delimiter, as it would be appropriate for C strings: rtrim("abc.def.\0def...", ".") --> "abc.def" The fix is to use size_t len = lua_rawlen(L, 1); instead, or size_t len; const char *string = lua_tolstring(L, 1, &len);
{ "domain": "codereview.stackexchange", "id": 43087, "lm_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, strings, lua, ffi", "url": null }
performance, c, strings, lua, ffi instead, or size_t len; const char *string = lua_tolstring(L, 1, &len); Return the original string if possible Your code returns the original string if that is empty, thereby avoiding the copy and possible allocation in lua_pushstring(): if (*string == '\0') { lua_rotate(L, -2, 1); return 1; } Well, I had to think twice in order to understand how it works, I would perhaps write it as if (*string == '\0') { // Pop delimiter from stack and return original string: lua_pop(L, 1); return 1; } In addition, the same logic could be applied not only for empty string, but generally if the string does not end with the delimiter string. Avoiding the copy Pushing the truncated string onto the stack does not require null termination if one uses lua_pushlstring instead, so that the source string need not be copied and modified. Putting it all together ... we get the following function, which is simpler, less memory-consuming, and does not suffer from the mentioned bugs: static int l_rtrim(lua_State *L) { luaL_checktype(L, 1, LUA_TSTRING); luaL_checktype(L, 2, LUA_TSTRING); size_t len; const char *string = lua_tolstring(L, 1, &len); const char *delimiter = lua_tostring(L, 2); size_t trimmed_len = len; while (trimmed_len > 0 && string[trimmed_len - 1] == *delimiter) { trimmed_len--; } if (trimmed_len < len) { // Push and return trimmed string: lua_pushlstring(L, string, len); } else { // Pop delimiter from stack and return original string: lua_pop(L, 1); } return 1; }
{ "domain": "codereview.stackexchange", "id": 43087, "lm_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, strings, lua, ffi", "url": null }
strings, formatting, vb.net Title: Parse floats to a custom numeric format string Question: I'm working to implement a custom string format. These are the float values to convert into a string: 1,02458 0,4145805 0,06231292 0,04362812 1,16458 1,172608 0,06011338 0,05324263 0,0653288 0,0285034 0,0992517 0,0861678 This is the output I'm getting: 1.02458f .4145805f 6.231292E-02f 4.362812E-02f 1.16458f 1.172608f 6.011338E-02f 5.324263E-02f .0653288f .0285034f .0992517f .0861678f The idea is, if the decimal places are greater than 8, use the scientific notation. If not, remove the left zeros. Now I'm using this code, but I would like to know if there's another more efficient way of doing this but always getting the same output: Dim numericProvider As New NumberFormatInfo With { .NumberDecimalSeparator = "." } 'Get the number of decimal places Dim stringNum As String = waveDuration.ToString(numericProvider) Dim decimalPlaces As Integer = 0 If InStr(1, stringNum, ".", CompareMethod.Binary) Then decimalPlaces = stringNum.Substring(stringNum.IndexOf(".")).Length End If 'Format String Dim waveDurationFormat As String If decimalPlaces > 8 Then waveDurationFormat = waveDuration.ToString("0.######E+00", numericProvider) Else waveDurationFormat = waveDuration.ToString(".#######", numericProvider) End If ListBox3.Items.Add(waveDurationFormat)
{ "domain": "codereview.stackexchange", "id": 43088, "lm_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, formatting, vb.net", "url": null }
strings, formatting, vb.net ListBox3.Items.Add(waveDurationFormat) Answer: Welcome to Code Review! Nice first question. Instead of using Instr() to check if stringNum contains a . you can just use String.IndexOf() and check if the result is > -1 which means the string representation of waveDuration contains a .. If IndexOf() returns a value greater than -1 we can just check if stringNum.Length - stringNum.IndexOf(".") > 8. This has the advantage that the code won't create a new string each time it is called because we don't need to call Substring() anymore. I would place this whole stuff inside an Extension method having an optional parameter stating the numbers of decimalplaces like so Imports System.Globalization Imports System.Runtime.CompilerServices Module StringExtensions Dim numericProvider As New NumberFormatInfo With {.NumberDecimalSeparator = "."} <Extension()> Public Function ToCustomString(ByVal value As Single, Optional scientificNotationDecimalPlaces As Integer = 8) As String If scientificNotationDecimalPlaces < 0 Then Throw New ArgumentOutOfRangeException(NameOf(scientificNotationDecimalPlaces)) End If Dim stringValue As String = value.ToString(numericProvider) Dim decimalPointIndex As Integer = stringValue.IndexOf(".") If decimalPointIndex > -1 AndAlso stringValue.Length - decimalPointIndex > scientificNotationDecimalPlaces Then Return value.ToString("0.######E+00", numericProvider) End If Return value.ToString(".#######", numericProvider) End Function End Module You could then call it like so ListBox3.Items.Add(waveDuration.ToCustomString()) or e.g if you want to have the sientific notation only if the decimal places are greater than 5 like so ListBox3.Items.Add(waveDuration.ToCustomString(5))
{ "domain": "codereview.stackexchange", "id": 43088, "lm_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, formatting, vb.net", "url": null }
java, game, homework Title: Java implementation of Yahtzee Question: I'm trying to implement the game of Yahtzee in java. This is for a project at my university so I tried to be as clean and to use the best code practices as possible. The part in particular that I would like some suggestion on is the one dedicated on keeping the scores (ScoreCategory, ScoreTable and their implementation). I found myself stuck using lots of magic numbers for indexing the table and also this is not convenient when testing/playing the game. Can you help me figure out a good way to refactor this? This is the interface for each score category: public interface ScoreCategory { /** * @return The name of the category. */ String getName(); /** * This function will calculate the score of the category based on an array of dices values. * @param dicesValues The value of the dices. * @return The score of the dice values in this category. */ default int calculateScore(int[] dicesValues) { return 0; }; /** * This function will calculate the score of the category. It will be used for categories where score * does not depend on the value of the dices. * @return The score of this category. */ default int calculateScore() { return 0; }; /** * Score the category with the dices values provided. * @param dicesValues The value of the dices. */ default void score(int[] dicesValues) {}; /** * Score the category. This is to be used when category score does not depend on the dices values. */ default void score() {}; /** * @return The current score in this category. */ int getScore(); /** * @return True if the category has already been scored once. Otherwise, False. * If the category can't be manually scored then this should always return true. */ boolean isScored(); }
{ "domain": "codereview.stackexchange", "id": 43089, "lm_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, game, homework", "url": null }
java, game, homework And here is how I implemented the table: public class DefaultScoringTable implements ScoringTable { private static final int CATEGORYCOUNT = 17; ScoreCategory[] scoringArray = new ScoreCategory[CATEGORYCOUNT]; public DefaultScoringTable(){ //0: # of 1 scoringArray[0] = new GeneralCategory("# of 1", DefaultScoringFunctions.SUM1); //1: # of 2 scoringArray[1] = new GeneralCategory("# of 2", DefaultScoringFunctions.SUM2); //2: # of 3 scoringArray[2] = new GeneralCategory("# of 3", DefaultScoringFunctions.SUM3); //3: # of 4 scoringArray[3] = new GeneralCategory("# of 4", DefaultScoringFunctions.SUM4); //4: # of 5 scoringArray[4] = new GeneralCategory("# of 5", DefaultScoringFunctions.SUM5); //5: # of 6 scoringArray[5] = new GeneralCategory("# of 6", DefaultScoringFunctions.SUM6); //6: Sum of above scoringArray[6] = new SumOfUpperCategory("Sum of upper", this); //7: Bonus scoringArray[7] = new BonusCategory("Bonus", this);
{ "domain": "codereview.stackexchange", "id": 43089, "lm_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, game, homework", "url": null }
java, game, homework //8: Couple scoringArray[8] = new GeneralCategory("Couple", DefaultScoringFunctions.COUPLE); //9: Double couple scoringArray[9] = new GeneralCategory("Double couple", DefaultScoringFunctions.DOUBLECOUPLE); //10: Tris scoringArray[10] = new GeneralCategory("Tris", DefaultScoringFunctions.TRIS); //11: Poker scoringArray[11] = new GeneralCategory("Poker", DefaultScoringFunctions.POKER); //12: Small scale scoringArray[12] = new GeneralCategory("Small scale", DefaultScoringFunctions.SMALL); //13: Big scale scoringArray[13] = new GeneralCategory("Big scale", DefaultScoringFunctions.BIG); //14: Full scoringArray[14] = new GeneralCategory("Full", DefaultScoringFunctions.FULL); //15: Sum scoringArray[15] = new GeneralCategory("Sum", DefaultScoringFunctions.SUM); //16: Yahtzee scoringArray[16] = new GeneralCategory("Yahtzee", DefaultScoringFunctions.YAHTZEE); } @Override public int getTotalScore() { return Arrays.stream(scoringArray).mapToInt(ScoreCategory::getScore).sum() - scoringArray[6].getScore(); } @Override public ScoreCategory getScoringCategory(int index) { return scoringArray[index]; } @Override public void score(int index, int[] dicesValues) { scoringArray[index].score(dicesValues); } @Override public boolean isComplete() { for (var category: scoringArray) { if (!category.isScored()) return false; } return true; } @Override public int getCategoryCount() { return CATEGORYCOUNT; } } If you need to look at other parts of the code here is the github repository. Let me know what you think!
{ "domain": "codereview.stackexchange", "id": 43089, "lm_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, game, homework", "url": null }
java, game, homework Answer: Interface default methods An interface is meant to define an interface, a list of methods that the implementing class has to provide. Putting implementation into the interface definition (using default methods) violates that concept, so there has to be a good reason to do so, which I don't see in your case. Even if there's a valid reason for using default methods, then they should do real useful work that (at least potentially) applies to all implementing classes. Your default methods do nothing. Scoring Array Make that a List instead of an array. Then you get rid of the ugly CATEGORYCOUNT constant and the indexing during the initialization, by using e.g. scoringArray.add(new GeneralCategory("# of 1", DefaultScoringFunctions.SUM1)); ScoreCategory Well in line with the Yahtzee rules, you have different classes implementing this interface (for a more useful review, you should have shown us these classes as well). An interface is meant to decsribe functionality that is present in all implementing classes, so that user code can treat all ScoreCategory versions the same. So, e.g. /** * Score the category. This is to be used when category score does not depend on the dices values. */ default void score() {}; should not be part of the interface, as (according to your documentation) it is only meaningful for some specific categories, forcing the caller to decide whether to use tha method or not. What's common to scoring categories is that (in isolation) they return a score for a given roll (int[] dicesValues). That should be the core scoring method in the interface: /** * Score the category with the dices values provided. * @param dicesValues The value of the dices. */ void score(int[] dicesValues);
{ "domain": "codereview.stackexchange", "id": 43089, "lm_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, game, homework", "url": null }
java, game, homework Callers should only use that method, and let the implementing class decide what to do with or without the dicesValues. Around that, Yahtzee allows the player to use some categories only once, or to modify the result on the second or third application. I'd build that logic around the ScoreCategory implementations, not into it. But your isScored() methods implies that you want to integrate this logic into the categories. If we want to go that way, I'd revise the scoring method then: the score not only depends on the current roll, but also on the categories that have been used for scoring so far: /** * Score the category, based on the current situation * (current roll and categories used so far). * @param dicesValues The value of the dices. * @param categoriesUsedSoFar The categories that have been used so far. */ void score(int[] dicesValues, Collection<ScoreCategory> categoriesUsedSoFar); If I understand the Yahtzee rules correctly, depending on the roll and the scoring done so far, there are situations where you cannot score a given category (e.g. has already been used), can score it (e.g. has not been used), can score it in addition to another category (a second Yahtzee), must score it (the matching SUMx category in some second-Yahtzee situations). I'd cover that applicability with an enum enum ScoreApplicability { CANNOT, CAN, ADDITION, MUST } and an interface method /** * Return the applicability mode of this category in the currect situation. * @param dicesValues The value of the dices. * @param categoriesUsedSoFar The categories that have been used so far. * @return applicability */ ScoreApplicability applicability(int[] dicesValues, Collection<ScoreCategory> categoriesUsedSoFar);
{ "domain": "codereview.stackexchange", "id": 43089, "lm_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, game, homework", "url": null }
javascript, datetime Title: Creating an array with quarter hour times Question: There is no need for me to use 50 lines of code here, but how can I populate this array in a loop without using date/time methods. var timeoptions = ["00:00", "00:15", "00:30", "00:45", "01:00", "01:15", "01:30", "01:45", "02:00", "02:15", "02:30", "02:45", "03:00", "03:15", "03:30", "03:45", "04:00", "04:15", "04:30", "04:45", "05:00", "05:15", "05:30", "05:45", "06:00", "06:15", "06:30", "06:45", "07:00", "07:15", "07:30", "07:45", "08:00", "08:15", "08:30", "08:45", "09:00", "09:15", "09:30", "09:45", "10:00", "10:15", "10:30", "10:45", "11:00", "11:15", "11:30", "11:45", "12:00", "12:15", "12:30", "12:45", "13:00", "13:15", "13:30", "13:45", "14:00", "14:15", "14:30", "14:45", "15:00", "15:15", "15:30", "15:45", "16:00", "16:15", "16:30", "16:45", "17:00", "17:15", "17:30", "17:45", "18:00", "18:15", "18:30", "18:45", "19:00", "19:15", "19:30", "19:45", "20:00", "20:15", "20:30", "20:45", "21:00", "21:15", "21:30", "21:45", "22:00", "22:15", "22:30", "22:45", "23:00", "23:15", "23:30", "23:45" ]; Answer: var quarterHours = ["00", "15", "30", "45"]; var times = []; for(var i = 0; i < 24; i++){ for(var j = 0; j < 4; j++){ times.push(i + ":" + quarterHours[j]); } }
{ "domain": "codereview.stackexchange", "id": 43090, "lm_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, datetime", "url": null }
javascript, datetime That's the really quick way without thinking. There might be better ways, but this is what I come up with in 2 minutes. After testing, you'll find out that it doesn't have a 0 prefix for hours 1 through 9. They show up as "9:45". You could either add a check for that, like so: var quarterHours = ["00", "15", "30", "45"]; var times = []; for(var i = 0; i < 24; i++){ for(var j = 0; j < 4; j++){ if(i < 10){ times.push("0" + i + ":" + quarterHours[j]); } else { times.push(i + ":" + quarterHours[j]); } } } Some more minor cleanup... var quarterHours = ["00", "15", "30", "45"]; var times = []; for(var i = 0; i < 24; i++){ for(var j = 0; j < 4; j++){ var time = i + ":" + quarterHours[j]; if(i < 10){ time = "0" + time; } times.push(time); } } Or declare another array with "00", "01", "02"... "23". Basically what you end up doing is creating every combination of hours and 15 minutes to recreate that big array of yours.
{ "domain": "codereview.stackexchange", "id": 43090, "lm_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, datetime", "url": null }
python, python-3.x Title: Function that checks Fermat’s Theorem for a set of values Question: This is a challenge from Think Python 2nd Edition: Fermat’s Last Theorem says that there are no positive integers a, b, and c such that aⁿ + bⁿ = cⁿ. for any values of n greater than 2. Write a function named check_fermat that takes four parameters; a, b, c and n. And that checks to see if Fermat’s theorem holds. If n is greater than 2 and it turns out to be true that aⁿ + bⁿ = cⁿ the program should print, “Holy smokes, Fermat was wrong!” Otherwise the program should print, “No, that doesn’t work.” Write a function that prompts the user to input values for a, b, c and n, converts them to integers, and uses check_fermat to check whether they violate Fermat’s theorem. That's what I've done so far. Are there any improvements I should make? And are there any 'best practices' among programmers that I'm missing? I'm just starting out and I'd like to avoid bad habits. def check_fermat(a, b, c, n): if n > 2 and a**n + b**n == c**n: print("Holy smokes! Fermat was wrong!") elif n <= 2: print("The exponent should be grater than '2'") else: print("No, that doesn't work.") def check_numbers(): a = int(input("Choose a number for 'a': ")) b = int(input("Choose a number for 'b': ")) c = int(input("Choose a number for 'c': ")) n = int(input("Choose a number for 'n' that's greater than '2': ")) check_fermat(a, b, c, n) check_numbers()
{ "domain": "codereview.stackexchange", "id": 43091, "lm_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, python-3.x check_numbers() Answer: Scripts should use a main guard. This supports the ability to cleanly import the code defined in the script and therefore supports testing, debugging, and development. Validate input. People make data-entry mistakes, and computers should accomodate humans -- not the other way around. The simplest, most flexible technique is a while-true loop: get the input; if it can be converted and is valid, return the value; otherwise stay in the loop. Collections are often more powerful than discrete variables.. In your main function, the separate variables (a, b, etc) aren't doing much for you, other than playing a minor documentation role. It might be overkill for an assignment this basic, but if you're trying to be extra diligent, you could take a more data-centric approach: define the input prompts as data and then use that data to drive the collection of the needed integers. This type of data-centric thinking is one of the keys to developing real skill at writing code. A mathematical function should be data-oriented. Your current check_fermat() is a mathematical function that prints. That's the wrong approach -- at least if we're striving for best-practice coding. A function like this should return a boolean or raise on exception for invalid inputs. Leave the printing to another part of the program -- the one handling input/output for the user. More data-oriented thinking. Continuing with the theme, one could define the messages to be printed for the user in a collection, allowing us to select the right message based on the return behavior of check_fermat(). Again, well-chosen data can drive the logic and, quite often, reduce, simplify, and clarify the algorithmic code. PROMPTS = ( "Choose a number for 'a'", "Choose a number for 'b'", "Choose a number for 'c'", "Choose a number for 'n' that's greater than '2'", )
{ "domain": "codereview.stackexchange", "id": 43091, "lm_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, python-3.x MESSAGES = { True: "No, that doesn't work.", False: "Holy smokes! Fermat was wrong!", 'LOW': "The exponent should be greater than '2'", } def main(): args = [get_int(p) for p in PROMPTS] try: print(MESSAGES[check_fermat(*args)]) except ValueError as e: print(e) def get_int(prompt): while True: try: return int(input(prompt + ': ')) except ValueError: print('Invalid input: try again') def check_fermat(a, b, c, n): if n > 2: return a**n + b**n != c**n else: raise ValueError(MESSAGES['LOW']) if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 43091, "lm_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 }
javascript, algorithm, machine-learning, neural-network Title: Unsupervised competitive learning algorithm from scratch in javascript Question: I'm a mathematician who is new to programming and I'm currently reading the book "Theory of Neural Networks" by Rojas. To become better, I try to program every algorithm that is described in the book using javascript (to be precise: the p5js editor). Let \$X=\{x_{1},\ldots,x_{N}\}\subset\mathbb{R}^{n}\$ be a set of points viewed as vectors. Let's assume I want to find \$ k\$ clusters in the set \$X\$. The algorithm goes as follows: start: Initialize a set of \$k\$ normalized random vectors \$\{w_{1},\ldots,w_{k}\}\$, called weight vectors. test: Select \$x_{j}\in X\$ randomly and compute the dotproduct \$x_{j}\cdot w_{i}\,\forall\,i\in\{1,\ldots,k\}\$. Find \$m\in\{1,\ldots,k\}\$ such that \$x_{j}\cdot w_{m}\geq x_{j}\cdot w_{i}\,\,\forall\,i\in\{1,\ldots,k\}\$. corrcet: Substitute \$w_{m}\$ by \$w_{m}+x_{j}\$ and normalize. Then go back to test. Here is my code: let off = 20; // offset to not touch boundary class Point { constructor() { this.x = random(-width/2 + off , width / 2 - off); this.y = random(-height / 2 + off, height / 2 - off); } show() { stroke(239, 12, 12); strokeWeight(4); point(this.x, this.y); } } // function for initializing random weight vectors function setWeights(l) { let weights = []; let v; for (let i = 0; i < l; i++) { v = createVector( random(-width / 2 , width / 2 ), random(-height / 2 , height / 2 ) ); weights.push(p5.Vector.mult(v, 1 / v.mag())); } return weights; }
{ "domain": "codereview.stackexchange", "id": 43092, "lm_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, algorithm, machine-learning, neural-network", "url": null }
javascript, algorithm, machine-learning, neural-network // k = # of weight vectors, N = # of learningsessions function computeClusters(inpts, k, N) { let w = setWeights(k); let erg, dotprods, ind, e, m, maxIndex; for (let j = 0; j < N; j++) { dotprods = []; ind = floor(random(0, inpts.length)); e = inpts[ind]; for (let i = 0; i < w.length; i++) { dotprods.push(e.dot(w[i])); } m = max(dotprods); maxIndex = 0; for (let i = 0; i < dotprods.length; i++) { if (dotprods[i] == m) { maxIndex = i; } } erg = e.add(w[maxIndex]); w[maxIndex] = erg.mult(100/erg.mag()); } return w; } // function for displaying vector in an "appropriate" way function drawVector(vec, mycolor) { let arrowSize = vec.mag() / 10; push(); stroke(mycolor); strokeWeight(1.5); fill(mycolor); line(0, 0, vec.x, vec.y); rotate(vec.heading()); translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 4, 0, -arrowSize / 4, arrowSize, 0); pop(); } let points = []; let vectors = []; let w = []; function setup() { createCanvas(400, 400); for (let i = 0; i < 10; i++) { let p = new Point(); points.push(p); vectors.push(createVector(p.x, p.y)); } w = computeClusters(vectors, 3, 10); } function draw() { background(165, 195, 239); translate(width / 2, height / 2); scale(1, -1); push(); strokeWeight(0.5); stroke(125); line(-width / 2, 0, width / 2, 0); line(0, -height / 2, 0, height / 2); pop(); for (var i = 0; i < points.length; i++) { points[i].show(); } push(); for (let j = 0; j < w.length; j++) { drawVector(w[j], color(50, 175, 150)); } pop(); }
{ "domain": "codereview.stackexchange", "id": 43092, "lm_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, algorithm, machine-learning, neural-network", "url": null }
javascript, algorithm, machine-learning, neural-network Now, the algorithm seems to performe quite well, see the attached pictures. The only problem I have is: why does my code sometimes produce two and sometimes produce three weight vecotrs, although I declared to create three: see w = computeClusters(vectors, 3, 10);? Thanks in advance for your help. If you have any general suggestions regarding my code, feel free to give me some input. :) Answer: In some cases where it seems that it only produces two weight vectors instead of three, the x and y Vector properties are less than 1. I played around with your code to be able to provide a visual of this effect, such as using different colors for each weight vector and showing the values of the x and y properties in a table. If you are not seeing one of the weights, check the values in the table. let off = 20; // offset to not touch boundary var vectorColors = []; // added for clean output details function output(obj) { let [w1, w2, w3] = obj; vector1x.textContent = String(w1.x.toPrecision(4)); vector1y.textContent = String(w1.y.toPrecision(4)); vector2x.textContent = String(w2.x.toPrecision(4)); vector2y.textContent = String(w2.y.toPrecision(4)); vector3x.textContent = String(w3.x.toPrecision(4)); vector3y.textContent = String(w3.y.toPrecision(4)); } class Point { constructor() { this.x = random(-width / 2 + off, width / 2 - off); this.y = random(-height / 2 + off, height / 2 - off); } show() { stroke(239, 12, 12); strokeWeight(4); point(this.x, this.y); } } // function for initializing random weight vectors function setWeights(l) { let weights = []; let v; for (let i = 0; i < l; i++) { v = createVector( random(-width / 2, width / 2), random(-height / 2, height / 2) ); weights.push(p5.Vector.mult(v, 1 / v.mag())); } return weights; }
{ "domain": "codereview.stackexchange", "id": 43092, "lm_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, algorithm, machine-learning, neural-network", "url": null }
javascript, algorithm, machine-learning, neural-network // k = # of weight vectors, N = # of learningsessions function computeClusters(inpts, k, N) { let w = setWeights(k); let erg, dotprods, ind, e, m, maxIndex; for (let j = 0; j < N; j++) { dotprods = []; ind = floor(random(0, inpts.length)); e = inpts[ind]; for (let i = 0; i < w.length; i++) { dotprods.push(e.dot(w[i])); } m = max(dotprods); maxIndex = 0; for (let i = 0; i < dotprods.length; i++) { if (dotprods[i] == m) { maxIndex = i; } } erg = e.add(w[maxIndex]); w[maxIndex] = erg.mult(100 / erg.mag()); } output(w); return w; } // function for displaying vector in an "appropriate" way function drawVector(vec, mycolor) { let arrowSize = vec.mag() / 10; push(); stroke(mycolor); strokeWeight(1.5); fill(mycolor); line(0, 0, vec.x, vec.y); rotate(vec.heading()); translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 4, 0, -arrowSize / 4, arrowSize, 0); pop(); } let points = []; let vectors = []; let w = []; function setup() { createCanvas(400, 400); for (let i = 0; i < 10; i++) { let p = new Point(); points.push(p); vectors.push(createVector(p.x, p.y)); } w = computeClusters(vectors, 3, 10); vectorColors.push(color(255, 0, 0), color(0, 255, 0), color(0, 0, 255)); } function draw() { background(165, 195, 239); translate(width / 2, height / 2); scale(1, -1); push(); strokeWeight(0.5); stroke(125); line(-width / 2, 0, width / 2, 0); line(0, -height / 2, 0, height / 2); pop(); for (var i = 0; i < points.length; i++) { points[i].show(); } push(); for (let j = 0; j < w.length; j++) { drawVector(w[j], vectorColors[j]); } pop(); } table { float: right; width: 40%; } td { border: 1px solid black; font-family: monospace; text-align: center; white-space: pre; width: 50%; } [id^=vector1] { background-color: pink; } [id^=vector2] { background-color: lightgreen; }
{ "domain": "codereview.stackexchange", "id": 43092, "lm_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, algorithm, machine-learning, neural-network", "url": null }
javascript, algorithm, machine-learning, neural-network [id^=vector1] { background-color: pink; } [id^=vector2] { background-color: lightgreen; } [id^=vector3] { background-color: lightblue; } <script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.min.js"></script> <table> <thead> <tr> <th>x</th> <th>y</th> </tr> </thead> <tbody> <tr> <td id="vector1x"></td> <td id="vector1y"></td> </tr> <tr> <td id="vector2x"></td> <td id="vector2y"></td> </tr> <tr> <td id="vector3x"></td> <td id="vector3y"></td> </tr> </tbody> </table> Now, as for adjusting for this, we just need to calculate the weights and be sure that they are at least |1| for both x and y properties. This requires separating out the step of setting the length then negating randomly. // Using width/4 and height/4 since the total span is width/2 and height/2 let vx = random(width / 4) + 1; let vy = random(height / 4) + 1; // Randomly negate the x- and y-value vx = random() < 0.5 ? vx * -1 : vx; vy = random() < 0.5 ? vy * -1 : vy; v = createVector(vx, vy); It's up to you if you wanted to implement this part, but the following code is an example of guaranteeing minimum |1| for each property: let off = 20; // offset to not touch boundary // added for clean output details function output(obj) { let [w1, w2, w3] = obj; vector1x.textContent = String(w1.x.toPrecision(4)); vector1y.textContent = String(w1.y.toPrecision(4)); vector2x.textContent = String(w2.x.toPrecision(4)); vector2y.textContent = String(w2.y.toPrecision(4)); vector3x.textContent = String(w3.x.toPrecision(4)); vector3y.textContent = String(w3.y.toPrecision(4)); } class Point { constructor() { this.x = random(-width / 2 + off, width / 2 - off); this.y = random(-height / 2 + off, height / 2 - off); } show() { stroke(239, 12, 12); strokeWeight(4); point(this.x, this.y); } }
{ "domain": "codereview.stackexchange", "id": 43092, "lm_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, algorithm, machine-learning, neural-network", "url": null }
javascript, algorithm, machine-learning, neural-network // function for initializing random weight vectors function setWeights(l) { let weights = []; let v; for (let i = 0; i < l; i++) { // Using width/4 and height/4 since the total span is width/2 and height/2 let vx = random(width / 4) + 1; let vy = random(height / 4) + 1; vx = random() < 0.5 ? vx * -1 : vx; vy = random() < 0.5 ? vy * -1 : vy; v = createVector(vx, vy); weights.push(v); } return weights; } // k = # of weight vectors, N = # of learningsessions function computeClusters(inpts, k, N) { let w = setWeights(k); let erg, dotprods, ind, e, m, maxIndex; for (let j = 0; j < N; j++) { dotprods = []; ind = floor(random(0, inpts.length)); e = inpts[ind]; for (let i = 0; i < w.length; i++) { dotprods.push(e.dot(w[i])); } m = max(dotprods); maxIndex = 0; for (let i = 0; i < dotprods.length; i++) { if (dotprods[i] == m) { maxIndex = i; } } erg = e.add(w[maxIndex]); w[maxIndex] = erg.mult(100 / erg.mag()); } output(w); return w; } // function for displaying vector in an "appropriate" way function drawVector(vec, mycolor) { let arrowSize = vec.mag() / 10; push(); stroke(mycolor); strokeWeight(1.5); fill(mycolor); line(0, 0, vec.x, vec.y); rotate(vec.heading()); translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 4, 0, -arrowSize / 4, arrowSize, 0); pop(); } let points = []; let vectors = []; let w = []; function setup() { createCanvas(400, 400); for (let i = 0; i < 10; i++) { let p = new Point(); points.push(p); vectors.push(createVector(p.x, p.y)); } w = computeClusters(vectors, 3, 10); }
{ "domain": "codereview.stackexchange", "id": 43092, "lm_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, algorithm, machine-learning, neural-network", "url": null }
javascript, algorithm, machine-learning, neural-network function draw() { background(165, 195, 239); translate(width / 2, height / 2); scale(1, -1); push(); strokeWeight(0.5); stroke(125); line(-width / 2, 0, width / 2, 0); line(0, -height / 2, 0, height / 2); pop(); for (var i = 0; i < points.length; i++) { points[i].show(); } push(); for (let j = 0; j < w.length; j++) { drawVector(w[j], color(50, 175, 150)); } pop(); } table { float: right; width: 40%; } td { border: 1px solid black; font-family: monospace; text-align: center; white-space: pre; width: 50%; } <script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.min.js"></script> <table> <thead> <tr> <th>x</th> <th>y</th> </tr> </thead> <tbody> <tr> <td id="vector1x"></td> <td id="vector1y"></td> </tr> <tr> <td id="vector2x"></td> <td id="vector2y"></td> </tr> <tr> <td id="vector3x"></td> <td id="vector3y"></td> </tr> </tbody> </table>
{ "domain": "codereview.stackexchange", "id": 43092, "lm_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, algorithm, machine-learning, neural-network", "url": null }
c, strings, collections, c-preprocessor Title: C smart string implementation using preprocessor Question: I have wrote a smart string container implementation for use in my application, but as I'am not such professional C programmer I have doubts about is I'am did it right and is there ways how to improve it and make it better? #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <wchar.h> #define DEFAULT_CAPACITY 16 #define pntstrt_deftypeutil_strlen(T, fn) size_t (* pntstrt_typeutil_strlen$$##T)(const T*) = fn; #define pntstrt_deftypeutil_strcpy(T, fn) T* (* pntstrt_typeutil_strcpy$$##T)(T*, const T*) = fn;
{ "domain": "codereview.stackexchange", "id": 43093, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, strings, collections, c-preprocessor", "url": null }
c, strings, collections, c-preprocessor #define PNTSTRT_DECLARE_TYPE(T) \ typedef struct __pntstrt$$##T pntstrt$$##T; \ struct __pntstrt$$##T { \ T *data; \ size_t capacity; \ size_t length; \ }; \ void pntstrt_init$$##T(pntstrt$$##T *str) \ { \ str->data = calloc(DEFAULT_CAPACITY, sizeof(T)); \ *str->data = (T)0; \ str->capacity = DEFAULT_CAPACITY; \ str->length = 0; \ } \ pntstrt$$##T pntstrt_initrv$$##T() \ { \ pntstrt$$##T str; \ pntstrt_init$$##T(&str); \ return str; \ } \ void pntstrt_make$$##T(pntstrt$$##T *str, T *buf) \ { \ size_t len = pntstrt_typeutil_strlen$$##T(buf); \ size_t newcap = ((len + 1) / DEFAULT_CAPACITY + 1) * DEFAULT_CAPACITY; \ if (newcap != str->capacity) { \ T *pData = realloc(str->data, newcap * sizeof(T)); \ if (!pData) { \ assert(0); \ return; \ } \ str->data = pData; \ str->capacity = newcap; \ } \ pntstrt_typeutil_strcpy$$##T(str->data, buf); \ str->data[len] = (T)0; \ str->length = len; \ } \ pntstrt$$##T pntstrt_makerv$$##T(T *buf) \ { \ pntstrt$$##T str; \ pntstrt_init$$##T(&str); \ pntstrt_make$$##T(&str, buf); \ return str; \ } \ void pntstrt_append$$##T(pntstrt$$##T *str1, T *str2) \ { \ size_t newlen = str1->length + pntstrt_typeutil_strlen$$##T(str2); \ size_t newcap = ((newlen + 1) / DEFAULT_CAPACITY + 1) * DEFAULT_CAPACITY; \ if (newcap != str1->capacity) { \ T *pData = realloc(str1->data, newcap * sizeof(T)); \ if (!pData) { \ assert(0); \ return; \ } \ str1->data = pData; \ str1->capacity = newcap; \ } \ pntstrt_typeutil_strcpy$$##T(&str1->data[str1->length], str2); \ str1->data[newlen] = (T)0; \ str1->length = newlen; \ } \ void pntstrt_concat$$##T(pntstrt$$##T *str1, pntstrt$$##T *str2) \ { \ pntstrt_append$$##T(str1, str2->data); \ } \ const T* pntstrt_cstr$$##T(pntstrt$$##T *str) \ { \ return str->data; \ } \ size_t pntstrt_len$$##T(pntstrt$$##T *str) \ { \ return str->length; \ } \ void pntstrt_destroy$$##T(pntstrt$$##T *str) \ { \
{ "domain": "codereview.stackexchange", "id": 43093, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, strings, collections, c-preprocessor", "url": null }
c, strings, collections, c-preprocessor { \ return str->length; \ } \ void pntstrt_destroy$$##T(pntstrt$$##T *str) \ { \ free(str->data); \ str->data = NULL; \ str->length = 0; \ }
{ "domain": "codereview.stackexchange", "id": 43093, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, strings, collections, c-preprocessor", "url": null }
c, strings, collections, c-preprocessor #define PNTPATHUTIL_DECLARE_TYPE(T) \ void pntpathutil_add_separator$$##T(pntstrt$$##T *str) \ { \ if (str->length && str->data[str->length-1] == (T)'\\') { \ return; \ } \ pntstrt_append$$##T(str, (T[]){(T)'\\', (T)0}); \ } \ #define pntstrt(T) pntstrt$$##T #define pntstrt_init(T) pntstrt_init$$##T #define pntstrt_initrv(T) pntstrt_initrv$$##T #define pntstrt_make(T) pntstrt_make$$##T #define pntstrt_set(T) pntstrt_make$$##T #define pntstrt_makerv(T) pntstrt_makerv$$##T #define pntstrt_append(T) pntstrt_append$$##T #define pntstrt_concat(T) pntstrt_concat$$##T #define pntstrt_cstr(T) pntstrt_cstr$$##T #define pntstrt_len(T) pntstrt_len$$##T #define pntstrt_destroy(T) pntstrt_destroy$$##T pntstrt_deftypeutil_strlen(char, strlen) pntstrt_deftypeutil_strcpy(char, strcpy) PNTSTRT_DECLARE_TYPE(char) pntstrt_deftypeutil_strlen(wchar_t, wcslen) pntstrt_deftypeutil_strcpy(wchar_t, wcscpy) PNTSTRT_DECLARE_TYPE(wchar_t) #define pntstr pntstrt(char) #define pntstr_init pntstrt_init(char) #define pntstr_initrv pntstrt_initrv(char) #define pntstr_make pntstrt_make(char) #define pntstr_makerv pntstrt_makerv(char) #define pntstr_append pntstrt_append(char) #define pntstr_concat pntstrt_concat(char) #define pntstr_cstr pntstrt_cstr(char) #define pntstr_len pntstrt_len(char) #define pntstr_destroy pntstrt_destroy(char) #define pntstrw pntstrt(wchar_t) #define pntstrw_init pntstrt_init(wchar_t) #define pntstrw_initrv pntstrt_initrv(wchar_t) #define pntstrw_make pntstrt_make(wchar_t) #define pntstrw_makerv pntstrt_makerv(wchar_t) #define pntstrw_append pntstrt_append(wchar_t) #define pntstrw_concat pntstrt_concat(wchar_t) #define pntstrw_cstr pntstrt_cstr(wchar_t) #define pntstrw_len pntstrt_len(wchar_t) #define pntstrw_destroy pntstrt_destroy(wchar_t) #define pntpathutil_add_separator(T) pntpathutil_add_separator$$##T PNTPATHUTIL_DECLARE_TYPE(char) PNTPATHUTIL_DECLARE_TYPE(wchar_t)
{ "domain": "codereview.stackexchange", "id": 43093, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, strings, collections, c-preprocessor", "url": null }
c, strings, collections, c-preprocessor PNTPATHUTIL_DECLARE_TYPE(char) PNTPATHUTIL_DECLARE_TYPE(wchar_t) #define pathutil_add_separator pntpathutil_add_separator(char) #define pathutilw_add_separator pntpathutil_add_separator(wchar_t) int main(void) { pntstrw str1; pntstrw str2; pntstrw_init(&str1); pntstrw_init(&str2); pntstrw_make(&str1, L"Hello"); pntstrw_make(&str2, L", World!"); pntstrw_concat(&str1, &str2); pntstrw_append(&str1, L" ghi"); pathutilw_add_separator(&str1); pntstrw_append(&str1, L" jklm"); pathutilw_add_separator(&str1); wprintf(L"str1.len: %ld, str2.len: %ld\n", pntstrw_len(&str1), pntstrw_len(&str2)); wprintf(L"str1.cap: %ld, str2.cap: %ld\n", str1.capacity, str2.capacity); wprintf(pntstrw_cstr(&str1)); pntstrw_destroy(&str1); pntstrw_destroy(&str2); return 0; } ``` Answer: Lack of documentation Code deserve comments explaining what this code set does. Allow initialization at defintion time Consider another form for pntstrw_init(): // pntstrw str1; // pntstrw_init(&str1); pntstrw str1 = pntstrw_init(); Design I am not much of a fan of huge .h files implementing code and would rather use a tidy .h file and accompanying .c file - but to each his own. Growth It looks like memory growth is linear. I recommend some closer to exponential like doubling to avoid slowness. Name pollution DEFAULT_CAPACITY is a surprising name to find in amongst pntstrt_ code and thus a collision candidate with other code. Perhaps pntstrt_DEFAULT_CAPACITY or the like. Separate into a .h file Put the pntstrt_ code in its own file and main() in another to show how to use this code in larger applications. Double a string? Consider pntstrw_concat(&str1, &str1); (str1 used 2x). To support this, pntstrt_append() should not reallocate before the concatenating is made. Instead: Allocate for new space. Copy str1 and str2 into it. Then free str1 former buffer.
{ "domain": "codereview.stackexchange", "id": 43093, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, strings, collections, c-preprocessor", "url": null }
c, strings, collections, c-preprocessor Allocate for new space. Copy str1 and str2 into it. Then free str1 former buffer. Code after pntstrw_destroy() I'd expect .capacity to be set to 0 in pntstrw_destroy(). Consider the effect of calling functions after pntstrw_destroy(). Do you want undefined or well defined behavior? Many functions presently incur UB with str->data == NULL. If UB is OK, no need for str->data = NULL; str->length = 0;. Mis-matched printf() specifier/type "%ld" is for long. "%zu" is for size_t. // %zu size_t wprintf(L"str1.len: %ld, str2.len: %ld\n", pntstrw_len(&str1), ... Why \\? pntpathutil_add_separator() uses '\\' for a path separator. The best separator is usually OS dependent. More likely '/' is a better choice if fixed. Missing use of const Select functions deserve const like pntstrt_cstr. // const T* pntstrt_cstr$$##T(pntstrt$$##T *str) const T* pntstrt_cstr$$##T(const pntstrt$$##T *str) Default size Rather than DEFAULT_CAPACITY as 16, consider 1. I plan for large uses of objects and then in that case, many are empty and default of 16 is wasteful. It comes down to Time vs. Memory. One of those is finite. A default of 16 makes sense after some thing more than the initial amount is needed.
{ "domain": "codereview.stackexchange", "id": 43093, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, strings, collections, c-preprocessor", "url": null }
python, python-3.x, programming-challenge, reinventing-the-wheel, socket Title: Programming Challenge: Python 3 DNS query resolver using socket Question: This is a DNS query resolver written in Python 3 using socket, I wrote it entirely by myself, it supports 8 primary DNS query types: A, NS, CNAME, SOA, PTR, MX, TXT, AAAA, and it is working correctly. Albeit the code is a little bit ugly. Sample output: In [22]: print(json.dumps(dns_query('deviantart.com', '8.8.8.8', 'SOA'), indent=4)) { "Question": { "ID": "0425", "Flags": { "Hexadecimal": "8180", "Binary": "1000000110000000", "Breakdown": { "Response": true, "Operation Code": "Query", "Authoritative Answer": false, "Truncated": false, "Recursion Desired": true, "Recursion Available": true, "Reserved": 0, "Authenticated Answer": false, "Non-authenticated Answer": "Unacceptable", "Error Code": "NoError" } }, "Questions": 1, "Answers": 1, "Authorative Answers": 0, "Additional Resources": 0, "Name": "deviantart.com", "Type": "SOA", "Class": "INTERNET" }, "Answers": [ { "QName": "deviantart.com", "QType": "A", "QClass": "INTERNET", "Time-to-live": 232, "Data length": 4, "RData": "50.117.117.42" } ] }
{ "domain": "codereview.stackexchange", "id": 43094, "lm_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, programming-challenge, reinventing-the-wheel, socket", "url": null }
python, python-3.x, programming-challenge, reinventing-the-wheel, socket In [23]: print(json.dumps(dns_query('deviantart.com', '8.8.8.8', 'SOA'), indent=4)) { "Question": { "ID": "e52f", "Flags": { "Hexadecimal": "8180", "Binary": "1000000110000000", "Breakdown": { "Response": true, "Operation Code": "Query", "Authoritative Answer": false, "Truncated": false, "Recursion Desired": true, "Recursion Available": true, "Reserved": 0, "Authenticated Answer": false, "Non-authenticated Answer": "Unacceptable", "Error Code": "NoError" } }, "Questions": 1, "Answers": 1, "Authorative Answers": 0, "Additional Resources": 0, "Name": "deviantart.com", "Type": "SOA", "Class": "INTERNET" }, "Answers": [ { "QName": "deviantart.com", "QType": "A", "QClass": "INTERNET", "Time-to-live": 176, "Data length": 4, "RData": "103.97.3.19" } ] }
{ "domain": "codereview.stackexchange", "id": 43094, "lm_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, programming-challenge, reinventing-the-wheel, socket", "url": null }
python, python-3.x, programming-challenge, reinventing-the-wheel, socket In [24]: print(json.dumps(dns_query('google.com', '8.8.8.8', 'SOA'), indent=4)) { "Question": { "ID": "3d0a", "Flags": { "Hexadecimal": "85b0", "Binary": "1000010110110000", "Breakdown": { "Response": true, "Operation Code": "Query", "Authoritative Answer": true, "Truncated": false, "Recursion Desired": true, "Recursion Available": true, "Reserved": 0, "Authenticated Answer": true, "Non-authenticated Answer": "Acceptable", "Error Code": "NoError" } }, "Questions": 1, "Answers": 1, "Authorative Answers": 0, "Additional Resources": 0, "Name": "google.com", "Type": "SOA", "Class": "INTERNET" }, "Answers": [ { "QName": "google.com", "QType": "A", "QClass": "INTERNET", "Time-to-live": 60, "Data length": 4, "RData": "59.24.3.174" } ] }
{ "domain": "codereview.stackexchange", "id": 43094, "lm_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, programming-challenge, reinventing-the-wheel, socket", "url": null }
python, python-3.x, programming-challenge, reinventing-the-wheel, socket In [25]: print(json.dumps(dns_query('baidu.com', '8.8.8.8', 'SOA'), indent=4)) { "Question": { "ID": "9a50", "Flags": { "Hexadecimal": "8180", "Binary": "1000000110000000", "Breakdown": { "Response": true, "Operation Code": "Query", "Authoritative Answer": false, "Truncated": false, "Recursion Desired": true, "Recursion Available": true, "Reserved": 0, "Authenticated Answer": false, "Non-authenticated Answer": "Unacceptable", "Error Code": "NoError" } }, "Questions": 1, "Answers": 1, "Authorative Answers": 0, "Additional Resources": 0, "Name": "baidu.com", "Type": "SOA", "Class": "INTERNET" }, "Answers": [], "Authorative Answers": [ { "QName": "baidu.com", "QType": "SOA", "QClass": "INTERNET", "Time-to-live": 7200, "Data length": 31, "RData": { "Primary Name Server": "dns.baidu.com", "Responsible Authority's Mailbox": "sa.baidu.com", "Serial Number": 2012145250, "Refresh Interval": 300, "Retry Interval": 300, "Expire Limit": 2592000, "Minimum TTL": 7200 } } ] } Code import ipaddress import publicsuffix2 as psl import random import socket import validators from collections import defaultdict QTYPE = { 1: 'A', 2: 'NS', 5: 'CNAME', 6: 'SOA', 12: 'PTR', 15: 'MX', 16: 'TXT', 28: 'AAAA', 'A': 1, 'NS': 2, 'CNAME': 5, 'SOA': 6, 'PTR': 12, 'MX': 15, 'TXT': 16, 'AAAA': 28 }
{ "domain": "codereview.stackexchange", "id": 43094, "lm_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, programming-challenge, reinventing-the-wheel, socket", "url": null }
python, python-3.x, programming-challenge, reinventing-the-wheel, socket OPCODE = { 0: 'Query', 1: 'IQuery', 2: 'Status', 4: 'Notify', 5: 'Update', 6: 'DSO' } RCODE = { 0: 'NoError', 1: 'FormErr', 2: 'ServFail', 3: 'NXDomain', 4: 'NotImp', 5: 'Refused', 6: 'YXDomain', 7: 'YXRRSet', 8: 'NXRRSet', 9: 'NotAuth', 10: 'NotZone', 11: 'DSOTYPENI' } def byte2int(by: bytes) -> int: if not isinstance(by, bytes): raise TypeError() return int.from_bytes(by, 'big') def byte2hex(by: bytes) -> str: if not isinstance(by, bytes): raise TypeError() return by.hex() def dns_opcode(n: int): if not isinstance(n, int): raise TypeError() if n not in OPCODE: raise ValueError() return OPCODE[n] def dns_rcode(n: int): if not isinstance(n, int): raise TypeError() if n not in RCODE: raise ValueError() return RCODE[n] def dns_cd(n: int): if n not in (0, 1): raise ValueError() return ['Unacceptable', 'Acceptable'][n] def dns_qclass(n: int): if n == 1: return 'INTERNET' else: raise ValueError('Invalid QCLASS value received') DECODE_HEADER = [byte2hex, byte2hex, byte2int, byte2int, byte2int, byte2int] FLAG_LENGTH = [1, 4, 1, 1, 1, 1, 1, 1, 1, 4] HEADERS = ['ID', 'Flags', 'Questions', 'Answers', 'Authorative Answers', 'Additional Resources'] FLAGS = [ 'Response', 'Operation Code', 'Authoritative Answer', 'Truncated', 'Recursion Desired', 'Recursion Available', 'Reserved', 'Authenticated Answer', 'Non-authenticated Answer', 'Error Code' ] SOA_NUMBERS = ['Serial Number', 'Refresh Interval', 'Retry Interval', 'Expire Limit', 'Minimum TTL'] DECODE_FLAG = [bool, dns_opcode, bool, bool, bool, bool, int, bool, dns_cd, dns_rcode]
{ "domain": "codereview.stackexchange", "id": 43094, "lm_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, programming-challenge, reinventing-the-wheel, socket", "url": null }
python, python-3.x, programming-challenge, reinventing-the-wheel, socket DECODE_FLAG = [bool, dns_opcode, bool, bool, bool, bool, int, bool, dns_cd, dns_rcode] def decode_flags(flag: str) -> dict: if not isinstance(flag, str): raise TypeError() if not (len(flag) == 4 and all(i in '0123456789abcdef' for i in flag)): raise ValueError() flag = '{:016b}'.format(int(flag, 16)) index = 0 flags = [] for i, f in zip(FLAG_LENGTH, DECODE_FLAG): flags.append(f(int(flag[index:index+i], 2))) index += i return dict(zip(FLAGS, flags)) def decode_response(fields: bytes) -> dict: if not isinstance(fields, bytes): raise TypeError() if len(fields) != 10: raise ValueError() qtype = QTYPE[byte2int(fields[:2])] qclass = dns_qclass(byte2int(fields[2:4])) ttl = byte2int(fields[4:8]) length = byte2int(fields[8:10]) return { 'QType': qtype, 'QClass': qclass, 'Time-to-live': ttl, 'Data length': length } def valid_domain(domain): return (validators.domain(domain) and psl.get_sld(domain, strict=True))
{ "domain": "codereview.stackexchange", "id": 43094, "lm_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, programming-challenge, reinventing-the-wheel, socket", "url": null }
python, python-3.x, programming-challenge, reinventing-the-wheel, socket def make_query(query, qtype): if not (isinstance(query, str) and isinstance(qtype, str)): raise TypeError('Parameters must be instances of `str`') qtype = QTYPE.get(qtype.upper(), None) if not qtype: raise ValueError('QTYPE is invalid or unsupported') if qtype == 12: if validators.ipv4(query): query = ipaddress.IPv4Address(query).reverse_pointer elif validators.ipv6(query): query = ipaddress.IPv6Address(query).reverse_pointer else: raise ValueError('QUERY is not a valid IPv4 or IPv6 address') else: if not (validators.domain(query) and (sld := psl.get_sld(query, strict=True))): raise ValueError('QUERY is not a valid web domain') if qtype in (2, 15, 16): query = sld return b''.join([ random.randbytes(2), b'\1\0\0\1\0\0\0\0\0\0', ''.join(chr(len(i)) + i for i in query.split('.')).encode('utf8'), b'\0', qtype.to_bytes(2, 'big'), b'\0\1' ])
{ "domain": "codereview.stackexchange", "id": 43094, "lm_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, programming-challenge, reinventing-the-wheel, socket", "url": null }
python, python-3.x, programming-challenge, reinventing-the-wheel, socket class DNS_Parser: def __init__(self, response: bytes) -> None: if not isinstance(response, bytes): raise TypeError('Argument must be an instance of `bytes`') self.response = response self.names = dict() self.question = dict() self.answers = [] self.soa = [] self.position = 0 self.raw = dict() self.simple = dict() def check_bounds(self, pos: int): if not isinstance(pos, int): raise TypeError('Argument must be an instance of `int`') if pos >= len(self.response): raise IndexError('Index exceeds the maximum possible value') def read_stream(self, pos: int, recur: bool=False, length: int=0) -> str: self.check_bounds(pos) chunks = [] count = 0 while True: hint = self.response[pos] if hint == 0: if not recur: self.position = pos break elif hint == 192: index = self.response[pos+1] self.position = pos+1 if index in self.names: name = self.names[index] else: name = self.read_stream(index, True) self.names[index] = name chunks.append(name) pos += 2 count += 2 if not length or count == length: break else: continue pos += 1 count += 1 chunk = self.response[pos:pos+hint].decode('utf8') chunks.append(chunk) pos += hint count += hint return '.'.join(chunks) def parse_dns_query(self): pos = self.response[12:].index(0) query = self.response[:pos+17] headers = [f(query[:12][i:i+2]) for f, i in zip(DECODE_HEADER, range(0, 12, 2))]
{ "domain": "codereview.stackexchange", "id": 43094, "lm_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, programming-challenge, reinventing-the-wheel, socket", "url": null }
python, python-3.x, programming-challenge, reinventing-the-wheel, socket headers = [f(query[:12][i:i+2]) for f, i in zip(DECODE_HEADER, range(0, 12, 2))] self.question = dict(zip(HEADERS, headers)) flags = self.question['Flags'] self.question['Flags'] = { 'Hexadecimal': flags, 'Binary': f'{int(flags, 16):016b}', 'Breakdown': decode_flags(flags) } name = self.read_stream(12) self.names[12] = name qtype = QTYPE[byte2int(query[pos+13:pos+15])] self.position = pos + 16 self.question.update({ 'Name': name, 'Type': qtype, 'Class': dns_qclass(byte2int(query[-2:])) }) def rdata_ipv4(self, pos: int) -> str: self.check_bounds(pos+3) return '.'.join([str(i) for i in self.response[pos:pos+4]]) def rdata_ipv6(self, pos: int) -> str: self.check_bounds(pos+15) return str(ipaddress.IPv6Address(self.response[pos:pos+16])) def rdata_txt(self, pos: int, length: int) -> dict: self.check_bounds(pos+length-1) return {'Text length': self.response[pos], 'Text': self.response[pos+1:pos+length+1].decode('utf8')} def rdata_mx(self, pos: int, length: int) -> dict: return {'Preference': byte2int(self.response[pos:pos+2]), 'Mail Exchange': self.read_stream(pos+2, length-2)} def rdata_soa(self, pos: int) -> dict: pns = self.read_stream(pos) ramx = self.read_stream(self.position+1) fields = self.response[self.position+1:self.position+21] soa = [byte2int(fields[i:i+4]) for i in range(0, 20, 4)] soa = dict(zip(SOA_NUMBERS, soa)) rdata = {'Primary Name Server': pns, "Responsible Authority's Mailbox": ramx} rdata.update(soa) self.position += 20 return rdata def parse_dns_answer(self): qname = self.read_stream(self.position+1) headers = decode_response(self.response[self.position+1:self.position+11]) answer = {'QName': qname}
{ "domain": "codereview.stackexchange", "id": 43094, "lm_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, programming-challenge, reinventing-the-wheel, socket", "url": null }
python, python-3.x, programming-challenge, reinventing-the-wheel, socket answer = {'QName': qname} answer.update(headers) qtype = headers['QType'] length = headers['Data length'] if length == 0: raise ValueError('DNS message is malformed or invalid') if qtype == 'A': if length != 4: raise ValueError('DNS message is malformed or invalid') rdata = self.rdata_ipv4(self.position+11) self.position += 14 elif qtype == 'AAAA': if length != 16: raise ValueError('DNS message is malformed or invalid') rdata = self.rdata_ipv6(self.position+11) self.position += 26 elif qtype == 'TXT': rdata = self.rdata_txt(self.position+11, length) if length - rdata['Text length'] != 1: raise ValueError('DNS message is malformed or invalid') self.position += (10 + length) elif qtype in ('CNAME', 'NS', 'PTR'): rdata = self.read_stream(self.position+11, length) if not valid_domain(rdata): raise ValueError('DNS message is malformed or invalid') elif qtype == 'MX': if length == 3 and self.response[self.position+13] == 0: prefs = byte2int(self.response[self.position+11:self.position+13]) rdata = {'Preference': prefs, 'Mail Exchange': '<Root>'} self.position += 13 else: rdata = self.rdata_mx(self.position+11, length) mx = rdata['Mail Exchange'] if not valid_domain(mx): raise ValueError('DNS message is malformed or invalid') elif qtype == 'SOA': rdata = self.rdata_soa(self.position+11) pns, ramx = rdata['Primary Name Server'], rdata["Responsible Authority's Mailbox"] if not (valid_domain(pns) and valid_domain(ramx)): raise ValueError('DNS message is malformed or invalid')
{ "domain": "codereview.stackexchange", "id": 43094, "lm_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, programming-challenge, reinventing-the-wheel, socket", "url": null }
python, python-3.x, programming-challenge, reinventing-the-wheel, socket raise ValueError('DNS message is malformed or invalid') answer['RData'] = rdata self.answers.append(answer) if qtype != 'SOA' else self.soa.append(answer) def parse_dns_response(self): self.parse_dns_query() total = sum(( self.question['Answers'], self.question['Authorative Answers'], self.question['Additional Resources'] )) count = 0 while count < total: self.parse_dns_answer() count += 1 self.raw['Question'] = self.question self.raw['Answers'] = self.answers if self.soa: self.raw['Authorative Answers'] = self.soa
{ "domain": "codereview.stackexchange", "id": 43094, "lm_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, programming-challenge, reinventing-the-wheel, socket", "url": null }
python, python-3.x, programming-challenge, reinventing-the-wheel, socket def dns_query(query, address, qtype): request = make_query(query, qtype) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.settimeout(2) try: sock.sendto(request, (address, 53)) response = sock.recv(8192) except Exception as e: print(e) return finally: sock.close() parser = DNS_Parser(response) parser.parse_dns_response() return parser.raw It isn't complete yet, but it is indeed working properly and there are no bugs. How can I improve its performance, refactor the code, improve readability, make it more structured, group the functions into classes, reduce code duplication and increase reuse rate, etc? Well, I think I need to make something clear. Obviously this project wasn't done for practicality, I am not some sort of egomaniac arrogant enough to think my code is better than library code written by experienced professionals; This project was done in the name of learning only, it was a self-imposed challenge, I only did it to learn, in the hopes of improving my skills. This script is poorly written and hacked together, but I really did learn a lot from the experience, I aimed for the process, not the result; So if you don't like it and don't want to help me to improve, that's fine, just don't try to discourage me or say the script should be deleted. Well I have found a bug in the code, but since there are answers I can't edit the code. The length parameter in read_stream is useless, remove that. There is no check against recursion after the pointer jumped back, so the position indicator (self.position) might be falsely decremented, thus breaking the code. The solution is to put the indicator change inside if not recur: block.
{ "domain": "codereview.stackexchange", "id": 43094, "lm_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, programming-challenge, reinventing-the-wheel, socket", "url": null }
python, python-3.x, programming-challenge, reinventing-the-wheel, socket Unfortunately fixing the previously mentioned bug introduces yet another bug, I have only encountered the bug just now. Trying to query anything with TXT as QTYPE will raise the following: In [164]: dns_query('example.com', '114.114.114.114', 'TXT').raw --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) ... <ipython-input-161-6d0c784748c1> in rdata_txt(self, pos, length) 198 199 def rdata_txt(self, pos: int, length: int) -> dict: --> 200 return {'Length': self.response[pos], 'Text': self.response[pos+1:pos+length+1].decode('utf8')} 201 202 def rdata_mx(self, pos: int) -> dict: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 11: invalid start byte It can be fixed by simply removing +1 after length. The error wasn't there before. Anyways I have obtained something like this: In [178]: print(json.dumps(multi_query('en.wikipedia.org', '8.8.8.8', 'SOA'), indent=4)) { "Question": { "Name": "en.wikipedia.org", "Type": "SOA", "Class": "INTERNET" }, "Answers": { "A": [ "202.160.128.210", "173.252.105.21" ], "CNAME": [ "dyna.wikimedia.org" ] }, "Authority": { "SOA": [ { "MNAME": "ns0.wikimedia.org", "RNAME": "hostmaster.wikimedia.org", "Serial": 2022031717 } ] } } It combines information from multiple responses to one single query into a single dictionary: Answer: Don't repeat yourself You currently store the reverse mappings explicitly in QTYPE: QTYPE = { 1: 'A', 2: 'NS', 5: 'CNAME', 6: 'SOA', 12: 'PTR', 15: 'MX', 16: 'TXT', 28: 'AAAA', 'A': 1, 'NS': 2, 'CNAME': 5, 'SOA': 6, 'PTR': 12, 'MX': 15, 'TXT': 16, 'AAAA': 28 }
{ "domain": "codereview.stackexchange", "id": 43094, "lm_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, programming-challenge, reinventing-the-wheel, socket", "url": null }
python, python-3.x, programming-challenge, reinventing-the-wheel, socket Maybe just do it once and add then reverse dict programmatically: QTYPE = { 1: 'A', 2: 'NS', 5: 'CNAME', 6: 'SOA', 12: 'PTR', 15: 'MX', 16: 'TXT', 28: 'AAAA' } QTYPE = {**QTYPE, **{value: key for key, value in QTYPE.items()}} Runtime type checks Remove runtime type checks and with them the useless conversion functions. Python is a dynamically typed language. The parser will complain if an object does not support a certain method via an AttributeError. Also they are unnecessarily costly. Don't micromanage types (again) Consider: def dns_opcode(n: int): if not isinstance(n, int): raise TypeError() if n not in OPCODE: raise ValueError() return OPCODE[n] vs. def dns_opcode(n: int): return OPCODE[n] # Will throw a KeyError on invalid opcodes And with this the function becomes virtually useless, since you can call OPCODE[n] at the given time directly. Avoid magic numbers I have no idea what b'\1\0\0\1\0\0\0\0\0\0' is. Put it into a global variable with a descriptive name. Divide and conquer Some functions are currently pretty long. Especially read_stream() and parse_dns_answer(). Consider splitting them into smaller functions dealing with a part of the problem. Since the latter has a long if/else block, it should be a good candidate to split the parser into functions for each response type.
{ "domain": "codereview.stackexchange", "id": 43094, "lm_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, programming-challenge, reinventing-the-wheel, socket", "url": null }
multithreading, go Title: Re-usable worker pool classes Question: I am trying to read multiple files in parallel in such a way so that each go routine that is reading a file write its data to that channel, then have a single go-routine that listens to that channel and adds the data to the map. Here is my play. This handles error and if there are any errors reading the file then it cancels other go-routines as well waiting to read the file. Below is my worker pool implementation which works fine: package main import ( "context" "encoding/json" "fmt" "os" "golang.org/x/sync/errgroup" ) func main() { var myFiles = []string{"file1", "file2", "file3", "file4", "file5", "file6"} fileChan := make(chan string) dataChan := make(chan fileData) g, ctx := errgroup.WithContext(context.Background()) for i := 0; i < 3; i++ { worker_num := i g.Go(func() error { for file := range fileChan { if err := getBytesFromFile(file, dataChan); err != nil { fmt.Println("worker", worker_num, "failed to process", file, ":", err.Error()) return err } else if err := ctx.Err(); err != nil { fmt.Println("worker", worker_num, "context error in worker:", err.Error()) return err } } fmt.Println("worker", worker_num, "processed all work on channel") return nil
{ "domain": "codereview.stackexchange", "id": 43095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "multithreading, go", "url": null }
multithreading, go }) } // dispatch files g.Go(func() error { defer close(fileChan) done := ctx.Done() for _, file := range myFiles { if err := ctx.Err(); err != nil { return err } select { case fileChan <- file: continue case <-done: break } } return ctx.Err() }) var err error go func() { err = g.Wait() close(dataChan) }() var myMap = make(map[string]string) for data := range dataChan { myMap[data.name] = data.bytes } if err != nil { fmt.Println("errgroup Error:", err.Error()) } enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") if err := enc.Encode(myMap); err != nil { panic(err) } } type fileData struct { name, bytes string } func getBytesFromFile(file string, dataChan chan fileData) error { bytes, err := openFileAndGetBytes(file) if err == nil { dataChan <- fileData{name: file, bytes: bytes} } return err } func openFileAndGetBytes(file string) (string, error) { if file == "file2" { return "", fmt.Errorf("%s cannot be read", file) } return fmt.Sprintf("these are some bytes for file %s", file), nil } Problem Statement I am working with Go 1.17. As of now everything is tied to my main method. I want to take out worker pool implementation inside my main method in it's own classes so that it can be reused by multiple pieces in my application efficiently. I have few other code where I can use this worker pool implementation which works fine for my this particular usecase. Opting for codereview to see if there is any improvement I can do in my above code and also move this out into its own class and structs so that it can be reuse by other pieces of code. Answer: Your code is very clear and simple. I have a few suggestions. One small suggestion:
{ "domain": "codereview.stackexchange", "id": 43095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "multithreading, go", "url": null }
multithreading, go Answer: Your code is very clear and simple. I have a few suggestions. One small suggestion: This is subjective, but I find Printf to be much more readable than Println because the format string shows you what the result will look like. Compare fmt.Println("worker", worker_num, "failed to process", file, ":", err.Error()) with fmt.Printf("worker %d failed to process %s: %s\n", worker_num, file, err) And I have one comment about the concurrency strategy used. This next comment comes from the rethinking concurrency presentation so I would recommend reading through that as it has a lot of other great concurrency patterns for go. The principle to keep in mind is "start goroutines when you have concurrent work". Using worker threads that each read from a channel can have some disadvantages: if fileChan has no data, then all of the workers are sitting idle waiting for data to be available. Instead, I would recommend to start one goroutine per file to be processed, and limit the number of simultaneously active goroutines by using a semaphore. The worker goroutines will be replaced by something like this: // sem acts as a semaphore to limit the // number of concurrent goroutines. sem := chan(struct{}, 3) for _, file := range myFiles { // Use a select so that if ctx is cancelled early // we exit immediately. select { case <-ctx.Done(): break case sem <- struct{}{}: } // Get a local copy of file for the goroutine. // https://go.dev/doc/faq#closures_and_goroutines file := file // Start a goroutine when you have concurrent work. g.Go(func() error { defer func() { <-sem }() // Process file as normal. return getBytesFromFile(file, dataChan) }) } This would also eliminate the need to dispatch the list of files into a channel in a separate goroutine.
{ "domain": "codereview.stackexchange", "id": 43095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "multithreading, go", "url": null }
python, numpy Title: Making a list of shades and styles for plots Question: For a section of a much larger program that generates plots, I am creating a list of styles that I can pull from to create a consistent format from plot-to-plot. It works as follows I have a list of colors shade = ['k','m'] and a list of styles style = ['--', ':','-','.'] that I am concatenating to get the desired list Colors= [['k--', 'k:', 'k-', 'k.'], ['m--', 'm:', 'm-', 'm.']]. I am achieving this with the following nested loop (t and phi are not always necessarily the same size but for example sake they are here) import numpy as np t = np.linspace(0,1,24) phi = np.linspace(0,1,24) shade = ['k','m'] style = ['--', ':','-','.'] Colors = [] for i in shade: cs = [] for j in style: for k in range(int(len(t)/len(phi))): cs.append(i+j) Colors.append(cs) print(Colors) This is fine and works, plus it is a small operation so I'm not worried about the run-time of it, I am just tired of looking at such a big loop that could probably be written in one line. Answer: The inner for loop over the range is virtually useless, since it only ever executes once. Hence it can be dropped and your code can be condensed to one nested list comprehension. shades = ['k','m'] styles = ['--', ':','-','.'] colors = [[shade+style for style in styles] for shade in shades] print(colors)
{ "domain": "codereview.stackexchange", "id": 43096, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy", "url": null }
python, python-3.x, programming-challenge Title: Programming Challenge - Game Scoring Question: Can this solution be made more efficient? game_scoring.py """ Game Scoring Imagine a game where the player can score 1, 2, or 3 points depending on the move they make. Write a function or functions, that for a given final score computes every combination of points that a player could score to achieve the specified score in the game. Signature int[][] gameScoring(int score) Input Integer score representing the desired score Output Array of sorted integer arrays demonstrating the combinations of points that can sum to the target score Example 1: Input: score = 4 Output: [ [ 1, 1, 1, 1 ], [ 1, 1, 2 ], [ 1, 2, 1 ], [ 1, 3 ], [ 2, 1, 1 ], [ 2, 2 ], [ 3, 1 ] ] Example 2: Input: score = 5 Output: [ [ 1, 1, 1, 1, 1 ], [1, 1, 1, 2 ], [ 1, 1, 2, 1 ], [ 1, 1, 3 ], [ 1, 2, 1, 1 ], [ 1, 2, 2 ], [ 1, 3, 1 ], [ 2, 1, 1, 1 ], [ 2, 1, 2 ], [ 2, 2, 1 ], [ 2, 3 ], [ 3, 1, 1 ], [ 3, 2 ] ] """ from itertools import combinations_with_replacement, product import sys sys.dont_write_bytecode = True def gameScoring(score): points = [1,2,3] combos = list() for L in range(1,score+1): combos += list(combinations_with_replacement(points, L)) for M in range(len(combos)): combos += list(product(combos[M], repeat=len(combos[M])-1)) for i,combo in enumerate(combos): if sum(combo) != score: combos[i] = None output = sorted(list(set(combo for combo in combos if combo is not None))) return [list(out) for out in output] # These are the tests we use to determine if the solution is correct. # You can add your own at the bottom. test_case_number = 1
{ "domain": "codereview.stackexchange", "id": 43097, "lm_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, programming-challenge", "url": null }
python, python-3.x, programming-challenge test_case_number = 1 def check(expected, output): global test_case_number result = True if len(expected) == len(output): for score in expected: result = result & (score in output) for score in output: result = result & (score in expected) else: result = False rightTick = '\u2713' wrongTick = '\u2717' if result: print(rightTick, ' Test #', test_case_number, sep='') else: print(wrongTick, ' Test #', test_case_number, ': Expected ', sep='', end='') print(expected) print(' Your output: ', end='') print(output) print() test_case_number += 1 if __name__ == "__main__": test_1 = 4 expected_1 = [ [1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 3], [2, 1, 1], [2, 2], [3, 1] ] output_1 = gameScoring(test_1) check(expected_1, output_1) test_2 = 5 expected_2 = [ [1, 1, 1, 1, 1], [1, 1, 1, 2], [1, 1, 2, 1], [1, 1, 3], [1, 2, 1, 1], [1, 2, 2], [1, 3, 1], [2, 1, 1, 1], [2, 1, 2], [2, 2, 1], [2, 3], [3, 1, 1], [3, 2], ] output_2 = gameScoring(test_2) check(expected_2, output_2) # Add your own test cases here Answer: You've chosen a deeply inefficient algorithm. Your strategy is basically "throw a million darts at random and check which ones land on the board". You can do better. Improvement one is to recognise that you're really only generating permutations of combinations: def score_permute(score: int) -> Iterator[tuple[int, ...]]: points = range(1, N + 1) for L in range(1, score + 1): combos = combinations_with_replacement(points, L) for combo in combos: if sum(combo) == score: yield from permutations(combo) But much more importantly, you can directly generate these combinations with the correct sum as a given, something like: def score_direct(score: int) -> Iterator[tuple[int, ...]]: scores = [1] * score while True: yield tuple(scores)
{ "domain": "codereview.stackexchange", "id": 43097, "lm_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, programming-challenge", "url": null }
python, python-3.x, programming-challenge while True: yield tuple(scores) new_ones = 0 while True: new_ones += scores.pop() if len(scores) == 0: return if scores[-1] < N: break scores[-1] += 1 new_ones -= 1 scores.extend((1,) * new_ones) The test code is kind of bad, and bare assert will be preferable. Suggested """ Game Scoring Imagine a game where the player can score 1, 2, or 3 points depending on the move they make. Write a function or functions, that for a given final score computes every combination of points that a player could score to achieve the specified score in the game. Signature int[][] gameScoring(int score) Input Integer score representing the desired score Output Array of sorted integer arrays demonstrating the combinations of points that can sum to the target score Example 1: Input: score = 4 Output: [ [ 1, 1, 1, 1 ], [ 1, 1, 2 ], [ 1, 2, 1 ], [ 1, 3 ], [ 2, 1, 1 ], [ 2, 2 ], [ 3, 1 ] ] Example 2: Input: score = 5 Output: [ [ 1, 1, 1, 1, 1 ], [1, 1, 1, 2 ], [ 1, 1, 2, 1 ], [ 1, 1, 3 ], [ 1, 2, 1, 1 ], [ 1, 2, 2 ], [ 1, 3, 1 ], [ 2, 1, 1, 1 ], [ 2, 1, 2 ], [ 2, 2, 1 ], [ 2, 3 ], [ 3, 1, 1 ], [ 3, 2 ] ] """ from itertools import combinations_with_replacement, permutations, product from timeit import timeit from typing import Iterator N = 3 def score_orig(score: int) -> Iterator[tuple[int, ...]]: points = [1, 2, 3] combos = list() for L in range(1, score + 1): combos += list(combinations_with_replacement(points, L)) for M in range(len(combos)): combos += list(product(combos[M], repeat=len(combos[M]) - 1)) for i, combo in enumerate(combos): if sum(combo) != score: combos[i] = None output = sorted(list(set(combo for combo in combos if combo is not None))) return [list(out) for out in output]
{ "domain": "codereview.stackexchange", "id": 43097, "lm_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, programming-challenge", "url": null }
python, python-3.x, programming-challenge def score_permute(score: int) -> Iterator[tuple[int, ...]]: points = range(1, N + 1) for L in range(1, score + 1): combos = combinations_with_replacement(points, L) for combo in combos: if sum(combo) == score: yield from permutations(combo) def score_direct(score: int) -> Iterator[tuple[int, ...]]: scores = [1] * score while True: yield tuple(scores) new_ones = 0 while True: new_ones += scores.pop() if len(scores) == 0: return if scores[-1] < N: break scores[-1] += 1 new_ones -= 1 scores.extend((1,) * new_ones) METHODS = (score_orig, score_permute, score_direct) def test() -> None: test_1 = ( 4, { (1, 1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 3), (2, 1, 1), (2, 2), (3, 1), } ) test_2 = ( 5, { (1, 1, 1, 1, 1), (1, 1, 1, 2), (1, 1, 2, 1), (1, 1, 3), (1, 2, 1, 1), (1, 2, 2), (1, 3, 1), (2, 1, 1, 1), (2, 1, 2), (2, 2, 1), (2, 3), (3, 1, 1), (3, 2), } ) for method in METHODS: for score, expected in (test_1, test_2): output = {tuple(s) for s in method(score)} assert output == expected def compare() -> None: for n, method in zip( (7, 10, 25), METHODS, ): def with_arg(): tuple(method(n)) t = timeit(with_arg, number=1) print(f'{method.__name__} n={n} in {t:.3f} s') if __name__ == "__main__": test() compare() Output score_orig n=7 in 1.171 s score_permute n=10 in 0.503 s score_direct n=25 in 1.084 s
{ "domain": "codereview.stackexchange", "id": 43097, "lm_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, programming-challenge", "url": null }
c++, beginner, programming-challenge, array, time-limit-exceeded Title: Array rotation in C++ Question: I am completely new to data structures and algorithms. I tried this problem on hackerank. I got the desired output but my code wasn't efficient enough to execute in the given time limit. How can I optimise my code? Is it proper way to solve this problem? Question: A left rotation operation on an array of size shifts each of the array's elements unit 1 to the left. Given an integer,d, rotate the array that many steps left and return the result. The first line contains two space-separated integers that denote n, the number of integers, and d, the number of left rotations to perform. The second line contains n space-separated integers that describe the array My code: #include<iostream> #include<vector> #include<algorithm> //function to rotate an array to the left void rotate_left(std::vector<int> &arr) { int next = arr.back(), temp; arr.back() = arr[0]; for (int i = (int)arr.size() - 2; i >= 0; i--)//for the last but one { temp = arr[i];//storing the value of current variable arr[i] = next;//taking the next element i.e i+1 next = temp; } } int main() { int n,d, input; if (std::cin >> n >> d) { } else { std::cerr << "failed to read input "<<"\n"; return EXIT_FAILURE; } std::vector<int> a; for (int i = 0; i < n; i++) { if (std::cin >> input) { a.push_back(input); } else { std::cerr << "failed to read input " << "\n"; return EXIT_FAILURE; } } //calling the function for (int i = 0; i < d; i++) { rotate_left(a); } for (auto output : a) { std::cout << output <<" "; } return 0; }
{ "domain": "codereview.stackexchange", "id": 43098, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, programming-challenge, array, time-limit-exceeded", "url": null }
c++, beginner, programming-challenge, array, time-limit-exceeded Answer: Simplify the code Your code is more complex than necessary for just rotating an array by one element. You don't have to special-case swapping the first and last elements, and I would also use std::swap(): void rotate_left(std::vector<int> &arr) { for (std::size_t i = 0; i < arr.size() - 1; ++i) { std::swap(arr[i], arr[i + 1]); } } Of course, you could also just use std::rotate() to rotate the array for you. Optimizing the code If you need to rotate by more than 1 position, then calling rotate_left() multiple times is going to be slow, especially for large values of d. The best way is to try to move each element into the right place in one go. One way to do move elements in the range [d, arr.size()) to the start of the array, and then move [0, d) to the end. You need to first make a copy of the range [0, d), otherwise it will be overwritten by the first move. So: void rotate_left_by(std::vector<int> &arr, std::size_t d) { std::vector<int> head(arr.begin(), arr.begin() + d); auto tail_begin = std::copy(arr.begin() + d, arr.end(), arr.begin()); std::copy(head.begin(), head.end(), tail_begin); }
{ "domain": "codereview.stackexchange", "id": 43098, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, programming-challenge, array, time-limit-exceeded", "url": null }
c++, beginner, programming-challenge, array, time-limit-exceeded Here I used the constructor of std::vector to make a copy of the head of the original input, then I use std::copy() to move the tail of the original input to the front of the array. The return value of std::copy() is the iterator right past the end of the copied area, so you can use that to copy the original head to the tail without having to do any further iterator arithmetic. Note the similarity in structure to how you swapped elements in your for-loop. As vnp mentioned in the comments, it is also be possible to do an arbitrary rotation without needing a temporary vector to store elements. Such an algorithm can be useful if you have a limited amount of memory. Also, when reading the elements of the array from standard input, you know the number of elements you want to read. It's then good practice to call reserve() on the vector you are going to push_back() to, in order to avoid unnecessary memory reallocations. But as D. Jurcau mentioned, even better is not having to manipulate the array itself, just store it and then print it out in a rotated order. Actually, you don't need to store the whole array to begin with, you just need to store d elements in a std::vector: first read d elements into that vector, then for the rest of the input just copy it straight to the output. After finishing processing the input, just print the contents of the vector. Use std::size_t for sizes, counters and indices An int might not be big enough to be able to represent all sizes and all possible indices into containters. The right type to use is std::size_t. Do this consistently, this way you also avoid having to cast things to int just to prevent compiler warnings. Error handling There are some issues with your code when it comes to error handling. What if the input array has length 0? Also, my example rotate_left_by() function will probably crash if the input array is shorter than d. It's always good to check if your code handles all the edge cases correctly.
{ "domain": "codereview.stackexchange", "id": 43098, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, programming-challenge, array, time-limit-exceeded", "url": null }
c++, beginner, programming-challenge, array, time-limit-exceeded You are checking whether reading from std::cin succeeded, which is great! However, if you really want to be correct, you might also want to check that writing to std::cout also succeeded, and if not return EXIT_FAILURE. This is especially important for programs that are running unattended, or are part of a pipeline, as the output might not be visible, and the exit code is the only thing able to signal that things went wrong. Make it more generic Your code works only on std::vector<int>. It would be nice to have a function that can rotate arbitrary containers. It might be good practice to try to implement std::rotate() yourself, and make it work not only for random access containers like std::vector, but also for things like std::list.
{ "domain": "codereview.stackexchange", "id": 43098, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, programming-challenge, array, time-limit-exceeded", "url": null }
c#, array, converting, byte Title: Best way to convert the string with Byte sequence to Byte Array Question: We had a string with byte array (hexadecimal) sequence, like: "0x65,0x31,0xb6,0x9e,0xaf,0xd2,0x39,0xc9,0xad,0x07,0x78,0x99,0x73,0x52,0x91,0xf5,0x93,0x1a,0x49,0xc6" and we need to recovery this sequence to byte array again. We are using the following approach: string byteSequence = "0x65,0x31,0xb6,0x9e,0xaf,0xd2,0x39,0xc9,0xad,0x07,0x78,0x99,0x73,0x52,0x91,0xf5,0x93,0x1a,0x49,0xc6"; byte[] myBytes = stringByteSequence.Split(',').Select(s => Convert.ToByte(s, 16)).ToArray(); This hash sequence it been generated by this sample: string password = "<your password here>"; using (var cryptoProvider = System.Security.Cryptography.SHA1.Create()) { byte[] passwordHash = cryptoProvider.ComputeHash(Encoding.UTF8.GetBytes(password)); string result = "new byte[] { " + String.Join(",", passwordHash.Select(x => "0x" + x.ToString("x2")).ToArray()) + " } "; //... // result = "new byte[] { 0x65,0x31,0xb6,0x9e,0xaf,0xd2,0x39,0xc9,0xad,0x07,0x78,0x99,0x73,0x52,0x91,0xf5,0x93,0x1a,0x49,0xc6 }" //... } Is there a "cleaner" way to do this conversion? Illustrative code, like: byte[] myBytes = byteSequence.Which.Method.I.Can.Use.To.Convert.It.To.Byte.Array.Again?(); Original sample (referenced link above): new BasicAuthAuthorizationUser { Login = "Administrator-2", // Password as SHA1 hash Password = new byte[]{0xa9, 0x4a, 0x8f, 0xe5, 0xcc, 0xb1, 0x9b, 0xa6, 0x1c, 0x4c, 0x08, 0x73, 0xd3, 0x91, 0xe9, 0x87, 0x98, 0x2f, 0xbb, 0xd3} } Our main idea: new BasicAuthAuthorizationUser { Login = "Administrator-2", // Password as SHA1 hash Password = configuration["MY_ENV_VAR_NAME"].Split(',').Select(s => Convert.ToByte(s, 16)).ToArray(); }
{ "domain": "codereview.stackexchange", "id": 43099, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, array, converting, byte", "url": null }
c#, array, converting, byte } Answer: Not sure why are you storing the hexadecimal hash like that, if you can just use plain hexadecimal it would be more readable and would prevent from adding unnecessary work. For your current work, you can use extension methods to convert from hexadecimal string to bytes, and vise versa. public static class Extensions { public static string ToHexadecimalSeparatedString(this byte[] bytes) => bytes != null ? string.Join(",", bytes.Select(x => $"0x{x:X2}")) : null; public static byte[] FromHexadecimalSeparatedString(this string hexadecimal) { if (string.IsNullOrWhiteSpace(hexadecimal)) return null; return hexadecimal.Split(',').Select(x=> Convert.ToByte(x, 16)).ToArray(); } } usage : string byteSequence = "0x65,0x31,0xb6,0x9e,0xaf,0xd2,0x39,0xc9,0xad,0x07,0x78,0x99,0x73,0x52,0x91,0xf5,0x93,0x1a,0x49,0xc6"; byte[] bytes = byteSequence.FromHexadecimalSeparatedString(); string hexadecimal = bytes.ToHexadecimalSeparatedString(); so in your sample would be : new BasicAuthAuthorizationUser { Login = "Administrator-2", // Password as SHA1 hash Password = configuration["MY_ENV_VAR_NAME"].FromHexadecimalSeparatedString() } Although, I'm still not convinced of the way that hexadecimal is stored, if you planning to revert it to plain hexadecimal (no separators, and no hexadecimal prefix) then you might be interested in using the following extensions : public static class Extensions { public static string ToHexadecimal(this byte[] bytes) => bytes != null ? string.Concat(bytes.Select(x => $"{x:X2}")) : null; public static byte[] FromHexadecimal(this string hexadecimal, string separater = null) { if(string.IsNullOrWhiteSpace(hexadecimal)) return null; if(!string.IsNullOrWhiteSpace(separater)) { hexadecimal = hexadecimal.Replace(separater, string.Empty); } var temp = hexadecimal.Replace("0x", string.Empty);
{ "domain": "codereview.stackexchange", "id": 43099, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, array, converting, byte", "url": null }
c#, array, converting, byte var temp = hexadecimal.Replace("0x", string.Empty); byte[] bytes = new byte[temp.Length / 2]; for (int i = 0; i < bytes.Length; i++) { bytes[i] = Convert.ToByte(temp.Substring(i * 2, 2), 16); } return bytes; } } the following part is just for backward compatibility, to support the hashes that were already stored with separators. If all stored hashes are plain (no separators, no hexadecimal prefix) then, you can drop that part. if(!string.IsNullOrWhiteSpace(separater)) { hexadecimal = hexadecimal.Replace(separater, string.Empty); } var temp = hexadecimal.Replace("0x", string.Empty);
{ "domain": "codereview.stackexchange", "id": 43099, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, array, converting, byte", "url": null }
go Title: Parse data into struct efficiently by reducing memory footprint Question: I have a simple program where I am deserializing my bytes byteSlice into a ClientProduct array struct. And then I iterate over that ClientProduct array and construct definitions.CustomerProduct struct for each ClientProduct. Below is my struct details: type ProductInfo struct { Name map[Locale]map[int]string } type Locale string type CustomerProduct struct { Prs string ProductId int64 Catalogs []int32 Categories []int BaseProductId *int64 StatusCode int IsActive bool Common } type ValueMetrics struct { Value string ClientId int64 } type Common struct { Leagues []ValueMetrics Teams []ValueMetrics ProductInfo } Here is the code which deserializes byteSlice into ClientProduct array struct by using Convert and few other helper methods. var productRows []ClientProduct err = json.Unmarshal(byteSlice, &productRows) if err != nil { return errs.Wrap(err) } for i := range productRows { var flatProduct definitions.CustomerProduct err = r.Convert(spn, &productRows[i], &flatProduct) if err != nil { return errs.Wrap(err) } if flatProduct.StatusCode == definitions.DONE { continue } // populate map here from each "flatProduct" } Here is my Convert method which populates my CustomerProduct struct. And few other helper methods which help to populate CustomerProduct struct func (r *clientRepo) Convert(span log.Span, in *ClientProduct, out *definitions.CustomerProduct) error { commons, err := r.getCommonStruct(span, in) if err != nil { return errs.Wrap(err) } out.Common = commons out.Catalogs = r.convertParquetIntSliceToInt32Slice(in.Catalogs) out.Categories = in.Categories out.ProductId = in.Id out.IsActive = in.IsActive out.Prs = in.PRS out.StatusCode = in.StatusCode return nil }
{ "domain": "codereview.stackexchange", "id": 43100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go", "url": null }
go return nil } func (r *clientRepo) getCommonStruct(span log.Span, in *ClientProduct) (definitions.Common, error) { out := definitions.Common{} for _, pv := range in.PropertyValues { switch pv.Name { case "ABC": out.Leagues = r.concatStringSlice(pv, out.Leagues) case "DEF": out.Teams = r.concatStringSlice(pv, out.Teams) } } for _, opv := range in.OverriddenPropertyValues { switch opv.Name { case "CustomerName": if opv.Locale == "" { // log error } else { out.Name = r.attach(definitions.Locale(opv.Locale), opv, out.Name) } } } return out, nil } func (r *clientRepo) concatStringSlice(pv PropertyValue, list []definitions.ValueMetrics) []definitions.ValueMetrics { treeValue := definitions.ValueMetrics{Value: pv.Value, ClientId: pv.ClientId} if list == nil { return []definitions.ValueMetrics{treeValue} } return append(list, treeValue) } func (r *clientRepo) attach(locale definitions.Locale, opv OverriddenPropertyValue, m map[definitions.Locale]map[int]string) map[definitions.Locale]map[int]string { if m == nil { om := map[int]string{ opv.GroupId: opv.Value, } return map[definitions.Locale]map[int]string{ locale: om, } } os, ok := m[locale] if ok { os[opv.GroupId] = opv.Value m[locale] = os } else { m[locale] = map[int]string{ opv.GroupId: opv.Value, } } return m } func (r *clientRepo) convertParquetIntSliceToInt32Slice(catalogs []int) []int32 { var out []int32 for _, catalog := range catalogs { out = append(out, int32(catalog)) } return out }
{ "domain": "codereview.stackexchange", "id": 43100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go", "url": null }
go Problem Statement Above code works fine. Basically looking for code review on the way I am populating "CustomerProduct" using all these helper methods. Anything that can be improved? I am looking for inputs or ideas where I can improve the way I am populating CustomerProduct struct by using all those helper methods I have starting with Convert method. Also is there anything that can be improved in above code which can help in our memory footprint? Like using pointer's or passing reference of it instead of direct passing. I am seeing some memory fluctuating a lot whenever this deserialization happens and CustomerProduct struct is populated from all those helper methods. Any guidance will be greatly appreciated. Answer: It's important to have a benchmark before you start trying to optimize the code. That being said, I can think of a few general recommendations. The ProductInfo.Name field is a nested map, this will require a lot of maps to be allocated. Instead of nested maps, consider defining a struct key type, something like type NameKey struct { Locale Locale GroupID int } type ProductInfo struct { Name map[NameKey]string } Then getCommonStruct might look like func (r *clientRepo) getCommonStruct(span log.Span, in ClientProduct) (definitions.Common, error) { out := definitions.Common{ // Initialize Name ahead of time. ProductInfo: definitions.ProductInfo { Name: make(map[definitions.NameKey]string), }, } for _, pv := range in.PropertyValues { // This part is the same. ... } for _, opv := range in.OverriddenPropertyValues { switch opv.Name { case "CustomerName": if opv.Locale == "" { ... continue } // Just set the value in the map. out.Name[NameKey{Locale: definitions.Locale(opv.Locale), GroupID: opv.GroupID}] = opv.Value } } return out, nil }
{ "domain": "codereview.stackexchange", "id": 43100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go", "url": null }
go return out, nil } In general prefer passing values instead of pointers. This tends to produce code that is easier to read and reason about. Computers are really fast at copying memory :) Of course, if your benchmark tells you a pointer is faster somewhere, feel free to use that. The Convert method can return a CustomerProduct instead of using an out parameter. I would also recommend taking the ClientProduct by value since it isn't modified. The concatStringSlice helper can be simplified, append works just fine on nil: func (r *clientRepo) concatStringSlice(pv PropertyValue, list []definitions.ValueMetrics) []definitions.ValueMetrics { return append(list, definitions.ValueMetrics{Value: pv.Value, ClientId: pv.ClientId}) } In convertParquetIntSliceToInt32Slice, out can be pre-allocated to the right size: func (r *clientRepo) convertParquetIntSliceToInt32Slice(catalogs []int) []int32 { out := make([]int32, 0, len(catalogs)) for _, catalog := range catalogs { out = append(out, int32(catalog)) } return out } Sorry for the typos it's late :)
{ "domain": "codereview.stackexchange", "id": 43100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go", "url": null }
c++, beginner, array, set Title: How many times element of one array occurs in another array?( HackerRank sparse arrays problem) Question: with basic knowledge of multiset and vectors in c++ I solved the following problem. How can I improve my code and also handle any input errors? Problem statement: There is a collection of input strings and a collection of query strings. For each query string, print how many times it occurs in the list of input strings. Input Format The first line contains an integer n, the input strings Each of the next n lines contains a string . The next line contains q, the size of . query strings Each of the q next lines contains a string . My code: #include<iostream> #include<vector> #include<algorithm> #include<set> #include<string> int main() { std::multiset<std::string> strings; std::vector<std::string> queries; size_t n,q;//size of the set, no of queries if (std::cin >> n){} else return EXIT_FAILURE; std::cin.ignore(1000, '\n'); for (size_t i = 0; i < n; i++) { std::string input; getline(std::cin, input); strings.insert(input); } if (std::cin >> q) {} else return EXIT_FAILURE; std::cin.ignore(100, '\n'); for (size_t i = 0; i < q; i++) { std::string input; getline(std::cin, input); queries.push_back(input); } //calling the function for (auto temp : queries) { if (strings.find(temp) != strings.end())//if the element exist int the set std::cout << strings.count(temp) << "\n"; else std::cout << "0" << "\n"; } return 0; }
{ "domain": "codereview.stackexchange", "id": 43101, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, array, set", "url": null }
c++, beginner, array, set Answer: The only advice I can give you is to use a std::unordered_map<std::string, size_t> counter_map. Then, you iterate over the input strings (call each string input_string, for example) and do counter_map[input_string]++;. Further on, when your query strings are read from the console, do something like for (const auto& query_string : queries) { std::cout << counter_map[query_string] << "\n"; } In some sense, you could say that the solution I am providing runs in \$\Theta(q + n)\$, whereas your solution runs in \$\Theta(qn)\$. ("In some sense" since I am not taking into account the number of characters in each query/input string.)
{ "domain": "codereview.stackexchange", "id": 43101, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, array, set", "url": null }
c#, linq Title: Checking a value in a string array in C# Question: I want to see if there is a cleaner way to do this logic. I have a working sample: Same fiddle.net public static Boolean passwordchecker(string userName) { string[] group = new string[] { "a", "b" }; if (group[0] == userName || group[1] == userName) { return true; } else { return false; } } Answer: Your code has three issues: The name passwordchecker: good method names are almost always a verb because they do things. I’d use CheckPassword (the capitalisation follows standard C# naming conventions). And, while we’re talking about names: the variable name group does not describe what the variable does, and, as a consequence, it took me unnecessary time to understand what your code is supposed to do. And, lastly, the parameter you call userName isn’t a user name; it’s a password, isn’t it? If so, you need to fix it. If it’s correct, you need to fix your method name because apparently it checks user names, not passwords. The code uses the anti-pattern if (expr) return true; else return false;. This simply never makes sense, and it never makes for clearer code when compared to the alternative: return expr;. In fact, outside of direct variable initialisation, there’s virtually no use for the literals true and false.
{ "domain": "codereview.stackexchange", "id": 43102, "lm_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#, linq", "url": null }
c#, linq There’s an array, but the code uses its values separately. As it stands, there is no reason for this to be an array (rather than separate variables), and it’s (very slightly) error-prone since a future maintainer might be tempted to extend the array, but forget to adjust its usage. AlanT’s answer shows one way of checking whether a value can be found inside an array. Personally, I’d be tempted to use the System.Linq.Enumerable.Contains method instead, because it doesn’t require using a predicate: public static bool CheckPassword(string password) { var passwords = new[] { "a", "b" }; return passwords.Contains(password); } This requires using System.Linq;. Without that, you’ll have to cast the array explicitly to IList<string> because arrays only implement the IList<T> interface privately. Furthermore, as shown in AlanT’s answer, I’d be tempted to make passwords a private readonly static variable rather than a local variable.
{ "domain": "codereview.stackexchange", "id": 43102, "lm_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#, linq", "url": null }
python, python-3.x, csv Title: Create csv file for each id value and write all data rows to csv with same id Question: I have a text file which is tab delimited: 1 324 2344 1 8372 1234 2 62 12 2 872 12111 2 1211 28736 3 87636 198272 The first "column" contains the id value and the rest containing data. I would like a csv file to be created for each id value so in this example, there would be 3 csv files. And for each csv file, I would like it to contain all rows of data with the same id. So when id = 1, the csv file will contain the 2 rows of data; when id = 2, the csv file will contain 3 rows etc. I have a script which achieves this but I don't think it's very efficient as it stores all unique id values in a list, iterates through this list, for each iteration it reads the text file line by line and if the first element in the line matches the id value, it creates a csv and writes all rows of data with the same id. But if there's 20 id values in the list, it will read the text file 20 times. For small text files, it's not a problem but for larger files, I'm wondering if it would be more efficient to only read the text file once and then create the relevant csv files according to id. So could this script be improved? import csv id_list = [] mylines = [] source_file = 'path/to/source_file.txt' target_directory = 'save/to/target_directory/' with open (source_file, 'rt') as myfile: # Get and store ids for line in myfile: data = line.split() if data[0] in id_list: pass else: id_list.append(data[0])
{ "domain": "codereview.stackexchange", "id": 43103, "lm_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, csv", "url": null }
python, python-3.x, csv for ids in id_list: with open(target_directory + ids + '.csv', 'w', newline='', encoding='utf-8') as csvfile: fieldnames = ['id', 'data_column_1', 'data_column_2'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() with open (source_file, 'rt') as myfile: for line in myfile: data = line.split() if data[0] == ids: writer.writerow({'id': data[0], \ 'data_column_1': data[1], \ 'data_column_2': data[2]}) Answer: Maintain a collection of writers. In a situation like this, the basic strategy to avoid the scaling problem mentioned in your question is the following: (1) process the input file line by line; (2) if we see a new row ID, create a CSV writer; and (3) store that writer in a dict mapping each row ID to its writer. Closing output files. One slightly tricky/annoying detail is to ensure that the output files are closed at the end, which we can do via a contextlib.ExitStack. Don't hardcode the dict given to the CSV writer. Instead, zip the field names and cells together to create the dict. Avoid hardcoded paths. In data processing scripts, it's often a good idea to take input/output paths on the command-line rather than hardcoding them (a variation on that idea is to use default paths if no command-line arguments are supplied). There are many benefits to that approach, but one of the most direct is the ability to run the code against alternative (often smaller) inputs/outputs while you are developing the script. Another is the ability to easily run your code on different computers (for example, your computer and the computer of someone on the internet giving you advice). Even in small scripts, put code in functions. Again, there are many benefits. import csv import sys import os from contextlib import ExitStack FIELD_NAMES = ['id', 'data_column_1', 'data_column_2']
{ "domain": "codereview.stackexchange", "id": 43103, "lm_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, csv", "url": null }
python, python-3.x, csv FIELD_NAMES = ['id', 'data_column_1', 'data_column_2'] def main(args): input_path, output_dir = args writers = {} with ExitStack() as stack: input_file = stack.enter_context(open(input_path, 'rt')) for line in input_file: cells = line.split() row_id = cells[0] if row_id not in writers: writers[row_id] = get_writer(output_dir, row_id, stack) writers[row_id].writerow(dict(zip(FIELD_NAMES, cells))) def get_writer(output_dir, row_id, stack): path = os.path.join(output_dir, row_id + '.csv') file = open(path, 'w', newline = '', encoding = 'utf-8') stack.enter_context(file) writer = csv.DictWriter(file, fieldnames = FIELD_NAMES) writer.writeheader() return writer if __name__ == '__main__': main(sys.argv[1:])
{ "domain": "codereview.stackexchange", "id": 43103, "lm_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, csv", "url": null }
javascript, node.js, file-system, portability Title: Safely renaming/moving files in Node (cross platform) Question: My goal is to create a function that safely renames files by adding numeric increments if the file is found at the destination, without using a third party library. Having a source file foo.bar and an existing destination foo.bar the function would rename using foo (1).bar, foo (2).bar, foo (3).bar, etc. I have to fs.lstat() first because relying on fs.rename() failing only works on win32 since linux, darwin will follow the posix conventions and blindly overwrite destination files. I realize there is a non-zero chance that the file could be moved before the rename, unfortunately, I haven't found an asynchronous friendly way to do it. So this is what I came up with, and it may be rather unconventional because I'm relying on a catch() block to do the work. While this works, I'm leaning on your experience to point out any pitfalls and looking for a better, more syntactically clear way to handle this, advice appreciated! const fs = require('fs') const path = require('path') const safe = async (src,dst) => { let x = 1 let target = dst let renamed = false while(x < 32) { await fs.promises.lstat(target) .then(() => target = path.join( path.dirname(dst), path.basename(dst, path.extname(dst)) + ' (' + x + ')' + path.extname(dst) )) .catch(async e => { console.log(e) await fs.promises.rename(src,target) .then(() => renamed = true) .catch(e => console.log(e)) }) if(renamed === true) break x++ } } safe('/source/foo.bar','/destination/foo.bar')
{ "domain": "codereview.stackexchange", "id": 43104, "lm_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, node.js, file-system, portability", "url": null }
javascript, node.js, file-system, portability x++ } } safe('/source/foo.bar','/destination/foo.bar') Answer: On the logical side, having two different conditions to break a loop in two different places makes the code harder to follow. Without changing the flow of the current implementation, why not while (x < 32 && !renamed) {, for example? I'd generally avoid using flags at all, in favour of break and continue (but with the current mix of callbacks that's not an option) and prefer for to while where the range of values is known up-front. safe returns a promise that resolves whatever happens. Did the file get renamed? Did we run out of numerical suffixes? It's not clear, which means that any caller can't take any action based on the outcome. Perhaps most importantly it's clear from the code (and the edits to this question!) is that you don't have a solid understanding of promises. The async/await syntax and .then are interoperable, it's all just promises under the hood, but sticking to one or the other makes the code much easier to follow. When nesting promises, onePromise .then(async () => { await anotherPromise; }); .then(() => console.log("both done"); works because the .then callback returns a promise (as async functions always do) which gets resolved as part of the existing promise chain. So does: onePromise .then(() => { return anotherPromise; }); .then(() => console.log("both done"); for exactly the same reason, but this won't: onePromise .then(() => { anotherPromise; }); .then(() => console.log("both done"); because the inner promise isn't part of the outer chain. You can also use the chaining, so: onePromise .then(() => return anotherPromise.then((value) => console.log("value")); }) .then(() => { console.log("both done"); }); can be rewritten: onePromise .then(() => return anotherPromise; }) .then((value) => { console.log("value") console.log("both done"); });
{ "domain": "codereview.stackexchange", "id": 43104, "lm_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, node.js, file-system, portability", "url": null }
javascript, node.js, file-system, portability First, we can extract a function that creates a new destination based on the initial destination and the suffix to add: const addSuffix = (destination, suffix) => { const extension = path.extname(destination) const filename = path.basename(destination, extension) return path.join( path.dirname(destination), `${filname} (${suffix})${extension}` ) } Second, let's tackle the rename of a given source to a destination, without worrying about what should happen if that doesn't work out. Note that the lstat error is expected (interpreted as "that destination is available") but any error on the rename is not expected and left to the caller. This gives three outcomes: promise resolves true: file was renamed promise resolves false: destination was occupied promise rejects: something unexpected went wrong const rename = async (source, destination) => { try { await fs.promises.lstat(destination) return false } catch (err) { console.error(err) } await fs.promises.rename(source, destination) return true } Now we can rebuild a much simpler safe from these components: const safe = async (source, destination) => { let target = destination for (let index = 1; index < 32; index++) { if (await rename(source, target)) { return target } target = addSuffix(destination, index) } throw new Error('exhausted all suffixes') } This has two outcomes: promise resolves: file was (eventually) renamed promise rejects: it wasn't This lets you provide appropriate feedback to the user: safe('/source/foo.bar','/destination/foo.bar') .then((destination) => console.log(`file moved to ${destination}`)) .catch((err) => { console.error(err) process.exit(1) })
{ "domain": "codereview.stackexchange", "id": 43104, "lm_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, node.js, file-system, portability", "url": null }
java, algorithm Title: Group a list of objects by property and remove the first value from each group Question: I have a list of Students and I want group this list by the property NAME, to sort each group ASC by the property GRADE, to remove the first entry from each Group and after thatto return the proccesed list. Here is what I've done. package com.example.demo; import java.security.KeyStore.Entry; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Test { public static void main(String[] args) { Student studentA2 = new Student("A", 1); Student studentA1 = new Student("A", 2); Student studentA3 = new Student("A", 3); Student studentA4 = new Student("A", 5); Student studentA5 = new Student("A", 9); Student studentB4 = new Student("B", 0); Student studentB1 = new Student("B", 10); Student studentB2 = new Student("B", 4); Student studentB3 = new Student("B", 2); List<Student> allStudents = new LinkedList<>(); allStudents.addAll(Arrays.asList(studentA1, studentA2, studentA3, studentB1, studentB2, studentB3, studentA4, studentA5, studentB4)); List<Student> procesedList = doGroupValuesAndRemoveTheSmallestGrade(allStudents); // The entry: Student("A", 1) and new Student("B", 0) are removed; procesedList.forEach(x -> System.out.println(x.name + " " + x.grade)); } private static List<Student> doGroupValuesAndRemoveTheSmallestGrade(List<Student> allStudents) { Collections.sort(allStudents, Comparator.comparing(Student::getName).thenComparing(Student::getGrade)); Map<String, LinkedList<Student>> groupedStudents = new HashMap<>(); for (Student student : allStudents) {
{ "domain": "codereview.stackexchange", "id": 43105, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm", "url": null }
java, algorithm for (Student student : allStudents) { boolean isNewGroup = groupedStudents.get(student.getName()) == null; if (isNewGroup) { groupedStudents.put(student.getName(), new LinkedList<>()); } groupedStudents.get(student.getName()).add(student); } groupedStudents.forEach((k, v) -> v.removeFirst()); List<Student> procesedList = new ArrayList<>(); groupedStudents.forEach((k, childList) -> childList.forEach(student -> procesedList.add(student))); return procesedList; } } class Student { public String name; public int grade; public Student(String name, int grade) { super(); this.name = name; this.grade = grade; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } }
{ "domain": "codereview.stackexchange", "id": 43105, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm", "url": null }
java, algorithm public void setGrade(int grade) { this.grade = grade; } } Answer: No point in having named individual variables for your Student instances - add them to the list inline. Also, don't construct the list directly; just accept the result of asList. Make Student a record. Student is not a great name for what actually appears to be a StudentGrade. doGroupValuesAndRemoveTheSmallestGrade is a painful name. You're better off abbreviating this to something like groupAndTrim, and adding meaningful javadocs for the details. doGroupValuesAndRemoveTheSmallestGrade can be re-expressed in streams, and would then return a stream instead of a list. You should replace println with printf. Better yet, do it in memory by formatting strings and then sending them to a single print. main should go away and be replaced with an actual unit test. Suggested There are probably better places to put groupAndTrim, but those depend on the broader context of "what you're actually doing" which you have not shown. In the absence of a fully-defined data processing pipeline I have shown this as a static on StudentGrade itself. Demonstrating some of the above, package com.stackexchange.studentgroup; import java.util.Collection; import java.util.Comparator; import java.util.stream.Collectors; import java.util.stream.Stream; public record StudentGrade( String name, int grade ) { @Override public String toString() { return String.format("%s %d", name, grade); }
{ "domain": "codereview.stackexchange", "id": 43105, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm", "url": null }
java, algorithm /** * Sort by student name and then by grade. Drop each student's lowest grade. */ public static Stream<StudentGrade> groupAndTrim(Collection<StudentGrade> grades) { return grades.stream() .collect(Collectors.groupingBy( StudentGrade::name )) .values().stream() .flatMap( students -> students.stream() .sorted( Comparator.comparing(StudentGrade::grade) ) .skip(1) ); } } package com.stackexchange.studentgroup; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; public class GroupTest { @Test public void testGroupTrim() { List<StudentGrade> grades = Arrays.asList( new StudentGrade("A", 2), new StudentGrade("A", 1), new StudentGrade("A", 3), new StudentGrade("B", 10), new StudentGrade("B", 4), new StudentGrade("B", 2), new StudentGrade("A", 5), new StudentGrade("A", 9), new StudentGrade("B", 0) ); List<StudentGrade> processed = StudentGrade.groupAndTrim(grades).toList(); // The entry: Student("A", 1) and new Student("B", 0) are removed assertEquals(7, processed.size()); for (StudentGrade grade: grades) { boolean copied = processed.contains(grade); int shouldDrop = switch(grade.name()) { case "A" -> 1; case "B" -> 0; default -> throw new UnsupportedOperationException(); }; assertTrue((grade.grade() == shouldDrop) ^ copied); } } }
{ "domain": "codereview.stackexchange", "id": 43105, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm", "url": null }
c#, .net, validation Title: c# record parameter validation technique Question: This comes from an answer I provided to a question on stackoverflow here: https://stackoverflow.com/a/71482194/3258131 To make c# record parameter validation concise and maintain all the benefits of the positional record definition I created the following solution. The first part is using a "dummy" private validation field and some extension methods to facilitate the validations. I created the following validation class (removed other validations for brevity): public static class Validation { public static bool IsValid<T>(this T _) { return true; } public static T NotNull<T>(T @value, [CallerArgumentExpression("value")] string? thisExpression = default) { if (value == null) throw new ArgumentNullException(thisExpression); return value; } public static string LengthBetween(this string @value, int min, int max, [CallerArgumentExpression("value")] string? thisExpression = default) { if (value.Length < min) throw new ArgumentOutOfRangeException(thisExpression, $"Can't have less than {min} items"); if (value.Length > max) throw new ArgumentOutOfRangeException(thisExpression, $"Can't have more than {max} items"); return value; } public static IComparable<T> RangeWithin<T>(this IComparable<T> @value, T min, T max, [CallerArgumentExpression("value")] string? thisExpression = default) { if (value.CompareTo(min) < 0) throw new ArgumentOutOfRangeException(thisExpression, $"Can't have less than {min} items"); if (value.CompareTo(max) > 0) throw new ArgumentOutOfRangeException(thisExpression, $"Can't have more than {max} items"); return value; } }
{ "domain": "codereview.stackexchange", "id": 43106, "lm_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, validation", "url": null }
c#, .net, validation Then you can use it with the following: // FirstName may not be null and must be between 1 and 5 // LastName may be null, but when it is defined it must be between 3 and 10 // Age must be positive and below 200 record Person(string FirstName, string? LastName, int Age, Guid Id) { private readonly bool _valid = Validation.NotNull(FirstName).LengthBetween(1, 5).IsValid() && (LastName?.LengthBetween(2, 10).IsValid() ?? true) && Age.RangeWithin(0, 200).IsValid(); } The ?? true is VERY important, it is to ensure validation continues in case the nullable LastName was indeed null, otherwise it would short-circuit. Perhaps it would be better (safer) to use another static AllowNull method to wrap the entire validation of that variable in, like so: public static class Validation { public static bool IsValid<T>(this T _) { return true; } public static bool AllowNull<T>(T? _) { return true; } public static T NotNull<T>(T @value, [CallerArgumentExpression("value")] string? thisExpression = default) { if (value == null) throw new ArgumentNullException(thisExpression); return value; } public static string LengthBetween(this string @value, int min, int max, [CallerArgumentExpression("value")] string? thisExpression = default) { if (value.Length < min) throw new ArgumentOutOfRangeException(thisExpression, $"Can't have less than {min} items"); if (value.Length > max) throw new ArgumentOutOfRangeException(thisExpression, $"Can't have more than {max} items"); return value; }
{ "domain": "codereview.stackexchange", "id": 43106, "lm_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, validation", "url": null }
c#, .net, validation public static IComparable<T> RangeWithin<T>(this IComparable<T> @value, T min, T max, [CallerArgumentExpression("value")] string? thisExpression = default) { if (value.CompareTo(min) < 0) throw new ArgumentOutOfRangeException(thisExpression, $"Can't have less than {min} items"); if (value.CompareTo(max) > 0) throw new ArgumentOutOfRangeException(thisExpression, $"Can't have more than {max} items"); return value; } } record Person(string FirstName, string? LastName, int Age, Guid Id) { private readonly bool _valid = Validation.NotNull(FirstName).LengthBetween(1, 5).IsValid() && Validation.AllowNull(LastName?.LengthBetween(2, 10)) && Age.RangeWithin(0, 200).IsValid(); } Any comments would be appreciated. I am still not very happy with either of the options for handling the nullable properties, any advice? Answer: Let me suggest a slightly different approach public class ValidatorBuilder<T> { private List<Exception> exceptions = new(); private List<Action<T>> validators = new(); public ValidatorBuilder<T> NotNull(Expression<Func<T, object>> propertySelector) { validators.Add((T input) => NotNull(propertySelector, input)); return this; } public ValidatorBuilder<T> LengthBetween(Expression<Func<T, string>> propertySelector, int min, int max) { validators.Add((T input) => LengthBetween(propertySelector, min, max, input)); return this; } public ValidatorBuilder<T> RangeWithin<P>(Expression<Func<T, P>> propertySelector, P min, P max) where P : IComparable { validators.Add((T input) => RangeWithin(propertySelector, min, max, input)); return this; }
{ "domain": "codereview.stackexchange", "id": 43106, "lm_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, validation", "url": null }
c#, .net, validation public bool IsValid(T input, bool shouldThrowException = false) { foreach (var validator in validators) validator(input); return exceptions.Count == 0 ? true : !shouldThrowException ? false : throw new AggregateException(exceptions); } private void NotNull(Expression<Func<T, object>> propertySelector, T input) { var propertyName = ((MemberExpression)propertySelector.Body).Member.Name; if (propertySelector.Compile()(input) == null) exceptions.Add(new ArgumentNullException(propertyName)); } private void LengthBetween(Expression<Func<T, string>> propertySelector, int min, int max, T input) { var propertyName = ((MemberExpression)propertySelector.Body).Member.Name; var value = propertySelector.Compile()(input); if (value.Length < min) exceptions.Add(new ArgumentOutOfRangeException(propertyName, $"Can't have less than {min} items")); if (value.Length > max) exceptions.Add(new ArgumentOutOfRangeException(propertyName, $"Can't have more than {max} items")); } private void RangeWithin<P>(Expression<Func<T, P>> propertySelector, P min, P max, T input) where P: IComparable { var propertyName = ((MemberExpression)propertySelector.Body).Member.Name; var value = propertySelector.Compile()(input); if (value.CompareTo(min) < 0) exceptions.Add(new ArgumentOutOfRangeException(propertyName, $"Can't have less than {min} items")); if (value.CompareTo(max) > 0) exceptions.Add(new ArgumentOutOfRangeException(propertyName, $"Can't have more than {max} items")); } } This approach follows the builder pattern (For the sake of simplicity I have combined the builder and the product. If you have more validation rules than these then I suggest to separate components) The IsValid is the build method of the builder
{ "domain": "codereview.stackexchange", "id": 43106, "lm_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, validation", "url": null }
c#, .net, validation The IsValid is the build method of the builder The public methods allow you to register validation rules against any arbitrary property The validators collection contains the registered rules The private methods implements the actual validation logic If the rule is violated then we add a new exception to the exceptions collection The IsValid method receives the to be validated input and a flag whether or not should throw exception If the flag is set then it will throw an AggregateException where the InnerExceptions collection will contain all violated rules The usage looks like this: record Person(string FirstName, string? LastName, int Age, Guid Id) { private readonly bool _valid = new ValidatorBuilder<Person>() .NotNull(p => p.FirstName) .LengthBetween(p => p.FirstName, 1, 5) .RangeWithin(p => p.Age, 0, 200) .IsValid(); } UPDATE #1 Fixing IsValid As it was pointed out the IsValid has been called in my sample without passing the this (I did not try out my code, I just made it compile). Due to C# limitations this can be referenced inside properties, methods, or constructors. We can't use this inside a field initialiser. Also we can't use this inside a read-only property with initializer method. So, if you want to stick with the positional record then you have to do something like this: record Person(string FirstName, string? LastName, int Age, Guid Id) { private bool _valid => new ValidatorBuilder<Person>() .NotNull(p => p.FirstName) .LengthBetween(p => p.FirstName, 1, 5) .RangeWithin(p => p.Age, 0, 200) .IsValid(this, true); public Person(string firstName, string? lastName, int age, Guid id, object validation) : this(firstName, lastName, age, id) => _ = _valid; } _valid become a read-only property There is a new ctor (an overload) which calls the positional (generated) ctor and enforces validation
{ "domain": "codereview.stackexchange", "id": 43106, "lm_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, validation", "url": null }
c#, .net, validation The drawback of this approach is that you can not enforce the caller to call the overload new Person("John", "Doe", 1000, Guid.NewGuid(), default);
{ "domain": "codereview.stackexchange", "id": 43106, "lm_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, validation", "url": null }
python-3.x, numpy, pandas Title: pandas dataframe of temps and numpy.linalg.lstsq
{ "domain": "codereview.stackexchange", "id": 43107, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, numpy, pandas", "url": null }
python-3.x, numpy, pandas Question: The problem is this. Forecast model data indicates at 0700Z the 1000 milibar temps will be -4C°. The forecaster knows that is incorrect, so they choose to make a correction. This correction should have a diminishing affect across the axes. The forecaster can set the threshold of correction via 2 sliders. time and height axis_0_weight axis_1_weight. data temps
{ "domain": "codereview.stackexchange", "id": 43107, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, numpy, pandas", "url": null }
python-3.x, numpy, pandas data = [{'2022-02-19 06:00:00': -61, '2022-02-19 07:00:00': -61, '2022-02-19 08:00:00': -61, '2022-02-19 09:00:00': -62, '2022-02-19 10:00:00': -63, '2022-02-19 11:00:00': -63, '2022-02-19 12:00:00': -64, '2022-02-19 13:00:00': -63, '2022-02-19 14:00:00': -62, '2022-02-19 15:00:00': -63}, {'2022-02-19 06:00:00': -60, '2022-02-19 07:00:00': -60, '2022-02-19 08:00:00': -60, '2022-02-19 09:00:00': -61, '2022-02-19 10:00:00': -60, '2022-02-19 11:00:00': -61, '2022-02-19 12:00:00': -61, '2022-02-19 13:00:00': -61, '2022-02-19 14:00:00': -60, '2022-02-19 15:00:00': -60}, {'2022-02-19 06:00:00': -60, '2022-02-19 07:00:00': -60, '2022-02-19 08:00:00': -60, '2022-02-19 09:00:00': -59, '2022-02-19 10:00:00': -59, '2022-02-19 11:00:00': -60, '2022-02-19 12:00:00': -59, '2022-02-19 13:00:00': -59, '2022-02-19 14:00:00': -59, '2022-02-19 15:00:00': -58}, {'2022-02-19 06:00:00': -57, '2022-02-19 07:00:00': -57, '2022-02-19 08:00:00': -56, '2022-02-19 09:00:00': -55, '2022-02-19 10:00:00': -55, '2022-02-19 11:00:00': -55, '2022-02-19 12:00:00': -55, '2022-02-19 13:00:00': -55, '2022-02-19 14:00:00': -55, '2022-02-19 15:00:00': -55}, {'2022-02-19 06:00:00': -55, '2022-02-19 07:00:00': -54, '2022-02-19 08:00:00': -53, '2022-02-19 09:00:00': -52, '2022-02-19 10:00:00': -53, '2022-02-19 11:00:00': -52, '2022-02-19 12:00:00': -52, '2022-02-19 13:00:00': -52, '2022-02-19 14:00:00': -52, '2022-02-19 15:00:00': -52}, {'2022-02-19 06:00:00': -52, '2022-02-19 07:00:00': -52, '2022-02-19 08:00:00': -51, '2022-02-19 09:00:00': -51, '2022-02-19 10:00:00': -51, '2022-02-19 11:00:00': -50, '2022-02-19 12:00:00': -50, '2022-02-19 13:00:00': -50, '2022-02-19 14:00:00': -50, '2022-02-19 15:00:00': -49}, {'2022-02-19 06:00:00': -50, '2022-02-19 07:00:00': -50, '2022-02-19 08:00:00': -49, '2022-02-19 09:00:00': -49, '2022-02-19 10:00:00': -49, '2022-02-19 11:00:00': -49, '2022-02-19 12:00:00': -48, '2022-02-19 13:00:00': -48, '2022-02-19 14:00:00': -48, '2022-02-19 15:00:00': -47}, {'2022-02-19
{ "domain": "codereview.stackexchange", "id": 43107, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, numpy, pandas", "url": null }
python-3.x, numpy, pandas '2022-02-19 13:00:00': -48, '2022-02-19 14:00:00': -48, '2022-02-19 15:00:00': -47}, {'2022-02-19 06:00:00': -50, '2022-02-19 07:00:00': -50, '2022-02-19 08:00:00': -50, '2022-02-19 09:00:00': -50, '2022-02-19 10:00:00': -50, '2022-02-19 11:00:00': -50, '2022-02-19 12:00:00': -50, '2022-02-19 13:00:00': -49, '2022-02-19 14:00:00': -49, '2022-02-19 15:00:00': -48}, {'2022-02-19 06:00:00': -50, '2022-02-19 07:00:00': -50, '2022-02-19 08:00:00': -50, '2022-02-19 09:00:00': -51, '2022-02-19 10:00:00': -52, '2022-02-19 11:00:00': -51, '2022-02-19 12:00:00': -51, '2022-02-19 13:00:00': -50, '2022-02-19 14:00:00': -49, '2022-02-19 15:00:00': -49}, {'2022-02-19 06:00:00': -51, '2022-02-19 07:00:00': -51, '2022-02-19 08:00:00': -52, '2022-02-19 09:00:00': -53, '2022-02-19 10:00:00': -53, '2022-02-19 11:00:00': -53, '2022-02-19 12:00:00': -53, '2022-02-19 13:00:00': -52, '2022-02-19 14:00:00': -50, '2022-02-19 15:00:00': -49}, {'2022-02-19 06:00:00': -51, '2022-02-19 07:00:00': -53, '2022-02-19 08:00:00': -54, '2022-02-19 09:00:00': -55, '2022-02-19 10:00:00': -54, '2022-02-19 11:00:00': -55, '2022-02-19 12:00:00': -55, '2022-02-19 13:00:00': -54, '2022-02-19 14:00:00': -51, '2022-02-19 15:00:00': -49}, {'2022-02-19 06:00:00': -51, '2022-02-19 07:00:00': -51, '2022-02-19 08:00:00': -51, '2022-02-19 09:00:00': -51, '2022-02-19 10:00:00': -51, '2022-02-19 11:00:00': -51, '2022-02-19 12:00:00': -51, '2022-02-19 13:00:00': -50, '2022-02-19 14:00:00': -49, '2022-02-19 15:00:00': -48}, {'2022-02-19 06:00:00': -50, '2022-02-19 07:00:00': -50, '2022-02-19 08:00:00': -48, '2022-02-19 09:00:00': -48, '2022-02-19 10:00:00': -47, '2022-02-19 11:00:00': -47, '2022-02-19 12:00:00': -47, '2022-02-19 13:00:00': -47, '2022-02-19 14:00:00': -48, '2022-02-19 15:00:00': -47}, {'2022-02-19 06:00:00': -47, '2022-02-19 07:00:00': -47, '2022-02-19 08:00:00': -45, '2022-02-19 09:00:00': -44, '2022-02-19 10:00:00': -44, '2022-02-19 11:00:00': -44, '2022-02-19 12:00:00': -44, '2022-02-19 13:00:00':
{ "domain": "codereview.stackexchange", "id": 43107, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, numpy, pandas", "url": null }
python-3.x, numpy, pandas 10:00:00': -44, '2022-02-19 11:00:00': -44, '2022-02-19 12:00:00': -44, '2022-02-19 13:00:00': -44, '2022-02-19 14:00:00': -44, '2022-02-19 15:00:00': -44}, {'2022-02-19 06:00:00': -44, '2022-02-19 07:00:00': -43, '2022-02-19 08:00:00': -43, '2022-02-19 09:00:00': -41, '2022-02-19 10:00:00': -41, '2022-02-19 11:00:00': -40, '2022-02-19 12:00:00': -40, '2022-02-19 13:00:00': -41, '2022-02-19 14:00:00': -41, '2022-02-19 15:00:00': -41}, {'2022-02-19 06:00:00': -40, '2022-02-19 07:00:00': -40, '2022-02-19 08:00:00': -40, '2022-02-19 09:00:00': -39, '2022-02-19 10:00:00': -38, '2022-02-19 11:00:00': -38, '2022-02-19 12:00:00': -37, '2022-02-19 13:00:00': -37, '2022-02-19 14:00:00': -38, '2022-02-19 15:00:00': -38}, {'2022-02-19 06:00:00': -37, '2022-02-19 07:00:00': -37, '2022-02-19 08:00:00': -37, '2022-02-19 09:00:00': -36, '2022-02-19 10:00:00': -36, '2022-02-19 11:00:00': -35, '2022-02-19 12:00:00': -34, '2022-02-19 13:00:00': -34, '2022-02-19 14:00:00': -35, '2022-02-19 15:00:00': -35}, {'2022-02-19 06:00:00': -34, '2022-02-19 07:00:00': -34, '2022-02-19 08:00:00': -34, '2022-02-19 09:00:00': -34, '2022-02-19 10:00:00': -34, '2022-02-19 11:00:00': -33, '2022-02-19 12:00:00': -32, '2022-02-19 13:00:00': -32, '2022-02-19 14:00:00': -32, '2022-02-19 15:00:00': -33}, {'2022-02-19 06:00:00': -31, '2022-02-19 07:00:00': -31, '2022-02-19 08:00:00': -31, '2022-02-19 09:00:00': -31, '2022-02-19 10:00:00': -31, '2022-02-19 11:00:00': -31, '2022-02-19 12:00:00': -30, '2022-02-19 13:00:00': -29, '2022-02-19 14:00:00': -29, '2022-02-19 15:00:00': -31}, {'2022-02-19 06:00:00': -28, '2022-02-19 07:00:00': -28, '2022-02-19 08:00:00': -28, '2022-02-19 09:00:00': -28, '2022-02-19 10:00:00': -28, '2022-02-19 11:00:00': -28, '2022-02-19 12:00:00': -28, '2022-02-19 13:00:00': -27, '2022-02-19 14:00:00': -28, '2022-02-19 15:00:00': -30}, {'2022-02-19 06:00:00': -26, '2022-02-19 07:00:00': -25, '2022-02-19 08:00:00': -25, '2022-02-19 09:00:00': -26, '2022-02-19 10:00:00': -26,
{ "domain": "codereview.stackexchange", "id": 43107, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, numpy, pandas", "url": null }
python-3.x, numpy, pandas 07:00:00': -25, '2022-02-19 08:00:00': -25, '2022-02-19 09:00:00': -26, '2022-02-19 10:00:00': -26, '2022-02-19 11:00:00': -26, '2022-02-19 12:00:00': -27, '2022-02-19 13:00:00': -26, '2022-02-19 14:00:00': -27, '2022-02-19 15:00:00': -29}, {'2022-02-19 06:00:00': -23, '2022-02-19 07:00:00': -23, '2022-02-19 08:00:00': -23, '2022-02-19 09:00:00': -23, '2022-02-19 10:00:00': -23, '2022-02-19 11:00:00': -23, '2022-02-19 12:00:00': -24, '2022-02-19 13:00:00': -24, '2022-02-19 14:00:00': -27, '2022-02-19 15:00:00': -28}, {'2022-02-19 06:00:00': -21, '2022-02-19 07:00:00': -21, '2022-02-19 08:00:00': -21, '2022-02-19 09:00:00': -21, '2022-02-19 10:00:00': -21, '2022-02-19 11:00:00': -21, '2022-02-19 12:00:00': -22, '2022-02-19 13:00:00': -23, '2022-02-19 14:00:00': -27, '2022-02-19 15:00:00': -28}, {'2022-02-19 06:00:00': -19, '2022-02-19 07:00:00': -19, '2022-02-19 08:00:00': -19, '2022-02-19 09:00:00': -19, '2022-02-19 10:00:00': -19, '2022-02-19 11:00:00': -19, '2022-02-19 12:00:00': -21, '2022-02-19 13:00:00': -23, '2022-02-19 14:00:00': -26, '2022-02-19 15:00:00': -27}, {'2022-02-19 06:00:00': -17, '2022-02-19 07:00:00': -17, '2022-02-19 08:00:00': -17, '2022-02-19 09:00:00': -17, '2022-02-19 10:00:00': -17, '2022-02-19 11:00:00': -17, '2022-02-19 12:00:00': -19, '2022-02-19 13:00:00': -23, '2022-02-19 14:00:00': -25, '2022-02-19 15:00:00': -27}, {'2022-02-19 06:00:00': -16, '2022-02-19 07:00:00': -15, '2022-02-19 08:00:00': -15, '2022-02-19 09:00:00': -15, '2022-02-19 10:00:00': -15, '2022-02-19 11:00:00': -16, '2022-02-19 12:00:00': -18, '2022-02-19 13:00:00': -21, '2022-02-19 14:00:00': -23, '2022-02-19 15:00:00': -24}, {'2022-02-19 06:00:00': -15, '2022-02-19 07:00:00': -14, '2022-02-19 08:00:00': -14, '2022-02-19 09:00:00': -13, '2022-02-19 10:00:00': -13, '2022-02-19 11:00:00': -15, '2022-02-19 12:00:00': -17, '2022-02-19 13:00:00': -20, '2022-02-19 14:00:00': -21, '2022-02-19 15:00:00': -22}, {'2022-02-19 06:00:00': -14, '2022-02-19 07:00:00': -13,
{ "domain": "codereview.stackexchange", "id": 43107, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, numpy, pandas", "url": null }
python-3.x, numpy, pandas -21, '2022-02-19 15:00:00': -22}, {'2022-02-19 06:00:00': -14, '2022-02-19 07:00:00': -13, '2022-02-19 08:00:00': -13, '2022-02-19 09:00:00': -12, '2022-02-19 10:00:00': -13, '2022-02-19 11:00:00': -15, '2022-02-19 12:00:00': -17, '2022-02-19 13:00:00': -18, '2022-02-19 14:00:00': -19, '2022-02-19 15:00:00': -20}, {'2022-02-19 06:00:00': -12, '2022-02-19 07:00:00': -13, '2022-02-19 08:00:00': -12, '2022-02-19 09:00:00': -12, '2022-02-19 10:00:00': -13, '2022-02-19 11:00:00': -15, '2022-02-19 12:00:00': -16, '2022-02-19 13:00:00': -16, '2022-02-19 14:00:00': -17, '2022-02-19 15:00:00': -18}, {'2022-02-19 06:00:00': -11, '2022-02-19 07:00:00': -12, '2022-02-19 08:00:00': -12, '2022-02-19 09:00:00': -13, '2022-02-19 10:00:00': -13, '2022-02-19 11:00:00': -15, '2022-02-19 12:00:00': -14, '2022-02-19 13:00:00': -15, '2022-02-19 14:00:00': -15, '2022-02-19 15:00:00': -16}, {'2022-02-19 06:00:00': -10, '2022-02-19 07:00:00': -10, '2022-02-19 08:00:00': -12, '2022-02-19 09:00:00': -13, '2022-02-19 10:00:00': -13, '2022-02-19 11:00:00': -14, '2022-02-19 12:00:00': -13, '2022-02-19 13:00:00': -13, '2022-02-19 14:00:00': -13, '2022-02-19 15:00:00': -15}, {'2022-02-19 06:00:00': -8, '2022-02-19 07:00:00': -9, '2022-02-19 08:00:00': -11, '2022-02-19 09:00:00': -12, '2022-02-19 10:00:00': -12, '2022-02-19 11:00:00': -12, '2022-02-19 12:00:00': -12, '2022-02-19 13:00:00': -11, '2022-02-19 14:00:00': -12, '2022-02-19 15:00:00': -15}, {'2022-02-19 06:00:00': -8, '2022-02-19 07:00:00': -8, '2022-02-19 08:00:00': -9, '2022-02-19 09:00:00': -11, '2022-02-19 10:00:00': -11, '2022-02-19 11:00:00': -11, '2022-02-19 12:00:00': -10, '2022-02-19 13:00:00': -10, '2022-02-19 14:00:00': -10, '2022-02-19 15:00:00': -14}, {'2022-02-19 06:00:00': -9, '2022-02-19 07:00:00': -8, '2022-02-19 08:00:00': -7, '2022-02-19 09:00:00': -9, '2022-02-19 10:00:00': -10, '2022-02-19 11:00:00': -9, '2022-02-19 12:00:00': -9, '2022-02-19 13:00:00': -8, '2022-02-19 14:00:00': -8, '2022-02-19 15:00:00': -12},
{ "domain": "codereview.stackexchange", "id": 43107, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, numpy, pandas", "url": null }
python-3.x, numpy, pandas 12:00:00': -9, '2022-02-19 13:00:00': -8, '2022-02-19 14:00:00': -8, '2022-02-19 15:00:00': -12}, {'2022-02-19 06:00:00': -10, '2022-02-19 07:00:00': -8, '2022-02-19 08:00:00': -7, '2022-02-19 09:00:00': -7, '2022-02-19 10:00:00': -9, '2022-02-19 11:00:00': -8, '2022-02-19 12:00:00': -8, '2022-02-19 13:00:00': -7, '2022-02-19 14:00:00': -7, '2022-02-19 15:00:00': -10}, {'2022-02-19 06:00:00': -10, '2022-02-19 07:00:00': -8, '2022-02-19 08:00:00': -7, '2022-02-19 09:00:00': -6, '2022-02-19 10:00:00': -8, '2022-02-19 11:00:00': -7, '2022-02-19 12:00:00': -6, '2022-02-19 13:00:00': -6, '2022-02-19 14:00:00': -5, '2022-02-19 15:00:00': -8}, {'2022-02-19 06:00:00': -10, '2022-02-19 07:00:00': -9, '2022-02-19 08:00:00': -8, '2022-02-19 09:00:00': -6, '2022-02-19 10:00:00': -7, '2022-02-19 11:00:00': -6, '2022-02-19 12:00:00': -5, '2022-02-19 13:00:00': -4, '2022-02-19 14:00:00': -4, '2022-02-19 15:00:00': -6}, {'2022-02-19 06:00:00': -10, '2022-02-19 07:00:00': -9, '2022-02-19 08:00:00': -7, '2022-02-19 09:00:00': -6, '2022-02-19 10:00:00': -5, '2022-02-19 11:00:00': -4, '2022-02-19 12:00:00': -3, '2022-02-19 13:00:00': -3, '2022-02-19 14:00:00': -2, '2022-02-19 15:00:00': -4}, {'2022-02-19 06:00:00': -9, '2022-02-19 07:00:00': -8, '2022-02-19 08:00:00': -6, '2022-02-19 09:00:00': -5, '2022-02-19 10:00:00': -4, '2022-02-19 11:00:00': -3, '2022-02-19 12:00:00': -2, '2022-02-19 13:00:00': -1, '2022-02-19 14:00:00': -1, '2022-02-19 15:00:00': -3}]
{ "domain": "codereview.stackexchange", "id": 43107, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, numpy, pandas", "url": null }
python-3.x, numpy, pandas index index = [ '50mb', '75mb', '100mb', '125mb', '150mb', '175mb', '200mb', '225mb', '250mb', '275mb', '300mb', '325mb', '350mb', '375mb', '400mb', '425mb', '450mb', '475mb', '500mb', '525mb', '550mb', '575mb', '600mb', '625mb', '650mb', '675mb', '700mb', '725mb', '750mb', '775mb', '800mb', '825mb', '850mb', '875mb', '900mb', '925mb', '950mb', '975mb', '1000mb' ] main code import pandas as pd import numpy as np CORRECTION=+20 data=... index=... def make_matrix(df:pd.DataFrame)->np.ndarray: x,y=df.shape arr_x,arr_y= np.vstack(np.linspace(0,1,x)),np.linspace(1,0,y) matrix = (arr_x+arr_y)-1 matrix[matrix<0]=0 return matrix if __name__ == '__main__': celcius_temps = pd.DataFrame.from_records(data,index=index) celcius_temps.columns=pd.to_datetime(celcius_temps.columns) mat = make_matrix(celcius_temps) print(celcius_temps+np.around(mat*CORRECTION,2))
{ "domain": "codereview.stackexchange", "id": 43107, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, numpy, pandas", "url": null }
python-3.x, numpy, pandas Results original dataframe 2022-02-19 06:00:00 ... 50mb -61 -61 -61 -62 -63 -63 -64 -63 -62 -63 75mb -60 -60 -60 -61 -60 -61 -61 -61 -60 -60 100mb -60 -60 -60 -59 -59 -60 -59 -59 -59 -58 125mb -57 -57 -56 -55 -55 -55 -55 -55 -55 -55 150mb -55 -54 -53 -52 -53 -52 -52 -52 -52 -52 175mb -52 -52 -51 -51 -51 -50 -50 -50 -50 -49 200mb -50 -50 -49 -49 -49 -49 -48 -48 -48 -47 225mb -50 -50 -50 -50 -50 -50 -50 -49 -49 -48 250mb -50 -50 -50 -51 -52 -51 -51 -50 -49 -49 275mb -51 -51 -52 -53 -53 -53 -53 -52 -50 -49 300mb -51 -53 -54 -55 -54 -55 -55 -54 -51 -49 325mb -51 -51 -51 -51 -51 -51 -51 -50 -49 -48 350mb -50 -50 -48 -48 -47 -47 -47 -47 -48 -47 375mb -47 -47 -45 -44 -44 -44 -44 -44 -44 -44 400mb -44 -43 -43 -41 -41 -40 -40 -41 -41 -41 425mb -40 -40 -40 -39 -38 -38 -37 -37 -38 -38 450mb -37 -37 -37 -36 -36 -35 -34 -34 -35 -35 475mb -34 -34 -34 -34 -34 -33 -32 -32 -32 -33 500mb -31 -31 -31 -31 -31 -31 -30 -29 -29 -31 525mb -28 -28 -28 -28 -28 -28 -28 -27 -28 -30 550mb -26 -25 -25 -26 -26 -26 -27 -26 -27 -29 575mb -23 -23 -23 -23 -23 -23 -24 -24 -27 -28 600mb -21 -21 -21 -21 -21 -21 -22 -23 -27 -28 625mb -19 -19 -19 -19 -19 -19 -21 -23 -26 -27 650mb -17 -17 -17 -17 -17 -17 -19 -23 -25 -27 675mb -16 -15 -15 -15 -15 -16 -18 -21 -23 -24 700mb -15 -14 -14 -13 -13 -15 -17 -20 -21 -22 725mb -14 -13 -13 -12 -13 -15 -17 -18 -19 -20 750mb -12 -13 -12 -12 -13 -15 -16 -16 -17 -18 775mb -11 -12 -12 -13 -13 -15 -14 -15 -15 -16 800mb -10 -10 -12 -13 -13 -14 -13 -13 -13 -15 825mb -8 -9 -11 -12 -12 -12 -12 -11 -12 -15 850mb -8 -8 -9 -11 -11 -11 -10 -10 -10 -14 875mb -9 -8 -7 -9 -10 -9 -9 -8 -8 -12 900mb -10 -8 -7 -7 -9 -8 -8 -7 -7 -10 925mb -10 -8 -7 -6 -8 -7 -6 -6 -5 -8 950mb -10 -9 -8 -6 -7 -6 -5 -4 -4 -6 975mb -10 -9 -7 -6 -5 -4 -3 -3 -2 -4 1000mb -9 -8 -6 -5 -4 -3 -2 -1 -1 -3
{ "domain": "codereview.stackexchange", "id": 43107, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, numpy, pandas", "url": null }
python-3.x, numpy, pandas The 1000mb 2022-02-19 06:00:00 receives 100% of the correction. the 50mb row and 2022-02-19 15:00:00 column remain unchanged with broadcast diminished correction
{ "domain": "codereview.stackexchange", "id": 43107, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, numpy, pandas", "url": null }
python-3.x, numpy, pandas 2022-02-19 06:00:00 ... 50mb -61.00 -61.00 -61.00 -62.00 -63.00 -63.00 -64.00 -63.00 -62.00 -63.0 75mb -59.47 -60.00 -60.00 -61.00 -60.00 -61.00 -61.00 -61.00 -60.00 -60.0 100mb -58.95 -60.00 -60.00 -59.00 -59.00 -60.00 -59.00 -59.00 -59.00 -58.0 125mb -55.42 -57.00 -56.00 -55.00 -55.00 -55.00 -55.00 -55.00 -55.00 -55.0 150mb -52.89 -54.00 -53.00 -52.00 -53.00 -52.00 -52.00 -52.00 -52.00 -52.0 175mb -49.37 -51.59 -51.00 -51.00 -51.00 -50.00 -50.00 -50.00 -50.00 -49.0 200mb -46.84 -49.06 -49.00 -49.00 -49.00 -49.00 -48.00 -48.00 -48.00 -47.0 225mb -46.32 -48.54 -50.00 -50.00 -50.00 -50.00 -50.00 -49.00 -49.00 -48.0 250mb -45.79 -48.01 -50.00 -51.00 -52.00 -51.00 -51.00 -50.00 -49.00 -49.0 275mb -46.26 -48.49 -51.71 -53.00 -53.00 -53.00 -53.00 -52.00 -50.00 -49.0 300mb -45.74 -49.96 -53.18 -55.00 -54.00 -55.00 -55.00 -54.00 -51.00 -49.0 325mb -45.21 -47.43 -49.65 -51.00 -51.00 -51.00 -51.00 -50.00 -49.00 -48.0 350mb -43.68 -45.91 -46.13 -48.00 -47.00 -47.00 -47.00 -47.00 -48.00 -47.0 375mb -40.16 -42.38 -42.60 -43.82 -44.00 -44.00 -44.00 -44.00 -44.00 -44.0 400mb -36.63 -37.85 -40.08 -40.30 -41.00 -40.00 -40.00 -41.00 -41.00 -41.0 425mb -32.11 -34.33 -36.55 -37.77 -38.00 -38.00 -37.00 -37.00 -38.00 -38.0 450mb -28.58 -30.80 -33.02 -34.25 -36.00 -35.00 -34.00 -34.00 -35.00 -35.0 475mb -25.05 -27.27 -29.50 -31.72 -33.94 -33.00 -32.00 -32.00 -32.00 -33.0 500mb -21.53 -23.75 -25.97 -28.19 -30.42 -31.00 -30.00 -29.00 -29.00 -31.0 525mb -18.00 -20.22 -22.44 -24.67 -26.89 -28.00 -28.00 -27.00 -28.00 -30.0 550mb -15.47 -16.70 -18.92 -22.14 -24.36 -26.00 -27.00 -26.00 -27.00 -29.0 575mb -11.95 -14.17 -16.39 -18.61 -20.84 -23.00 -24.00 -24.00 -27.00 -28.0
{ "domain": "codereview.stackexchange", "id": 43107, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, numpy, pandas", "url": null }
python-3.x, numpy, pandas 575mb -11.95 -14.17 -16.39 -18.61 -20.84 -23.00 -24.00 -24.00 -27.00 -28.0 600mb -9.42 -11.64 -13.87 -16.09 -18.31 -20.53 -22.00 -23.00 -27.00 -28.0 625mb -6.89 -9.12 -11.34 -13.56 -15.78 -18.01 -21.00 -23.00 -26.00 -27.0 650mb -4.37 -6.59 -8.81 -11.04 -13.26 -15.48 -19.00 -23.00 -25.00 -27.0 675mb -2.84 -4.06 -6.29 -8.51 -10.73 -13.95 -18.00 -21.00 -23.00 -24.0 700mb -1.32 -2.54 -4.76 -5.98 -8.20 -12.43 -16.65 -20.00 -21.00 -22.0 725mb 0.21 -1.01 -3.23 -4.46 -7.68 -11.90 -16.12 -18.00 -19.00 -20.0 750mb 2.74 -0.49 -1.71 -3.93 -7.15 -11.37 -14.60 -16.00 -17.00 -18.0 775mb 4.26 1.04 -1.18 -4.40 -6.63 -10.85 -12.07 -15.00 -15.00 -16.0 800mb 5.79 3.57 -0.65 -3.88 -6.10 -9.32 -10.54 -12.77 -13.00 -15.0 825mb 8.32 5.09 0.87 -2.35 -4.57 -6.80 -9.02 -10.24 -12.00 -15.0 850mb 8.84 6.62 3.40 -0.82 -3.05 -5.27 -6.49 -8.71 -10.00 -14.0 875mb 8.37 7.15 5.92 1.70 -1.52 -2.74 -4.96 -6.19 -8.00 -12.0 900mb 7.89 7.67 6.45 4.23 0.01 -1.22 -3.44 -4.66 -6.88 -10.0 925mb 8.42 8.20 6.98 5.75 1.53 0.31 -0.91 -3.13 -4.36 -8.0 950mb 8.95 7.73 6.50 6.28 3.06 1.84 0.61 -0.61 -2.83 -6.0 975mb 9.47 8.25 8.03 6.81 5.58 4.36 3.14 0.92 -0.30 -4.0 1000mb 11.00 9.78 9.56 8.33 7.11 5.89 4.67 3.44 1.22 -3.0
{ "domain": "codereview.stackexchange", "id": 43107, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, numpy, pandas", "url": null }
python-3.x, numpy, pandas I've looked into the numpy.linalg.lstsq method but I'm not sure how to implement it. Answer: Passing df to make_matrix is not adequately loosely coupled. Instead you can just pass its size as two integers. I do not trust your use of vstack. I would sooner add a new dimension via slice. Rather than conditional zeroing of the matrix in place, you should probably use np.maximum. celcius is spelled celsius. Don't around where you've done it. If you want to round for print, there are better ways. Suggested import pandas as pd import numpy as np def make_matrix(x: int, y: int, correction: float = 20) -> np.ndarray: arr_x = np.linspace(0, correction, x)[:, np.newaxis] arr_y = np.linspace(0, -correction, y) matrix = np.maximum(arr_x + arr_y, 0) return matrix def main() -> None: celsius_temps = pd.DataFrame.from_records(data, index=index) celsius_temps.columns = pd.to_datetime(celsius_temps.columns) mat = make_matrix(*celsius_temps.shape) result = celsius_temps + mat print(result) if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 43107, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, numpy, pandas", "url": null }
html Title: Generate 's for an html table efficiently Question: I have a Django project that has an HTML page with a table on it. The table can have thousands of rows in it. The problem is that, as a customer requirement, each row has 2 <select>'s with options for the user to choose from: <table> <thead> <tr> <th>Column 1</th> <th>Column 2</th> <th>Column 3</th> <th>Column 4</th> </td> </thead> <tbody> {% for row in my_model.rows.all %} <tr> <td>{{ row.column_1 }}</td> <td>{{ row.column_2 }}</td> <td> <select autocomplete="off" data-id="{{ row.id }}"> <option value="">--------</option> {% for short_name, long_name in column_3_choices %} <option value="{{ short_name }}" {% if short_name == row.column_3 %}selected{% endif %}>{{ long_name }}</option> {% endfor %} </select> </td> <td> <select autocomplete="off" data-id="{{ row.id }}"> <option value="">--------</option> {% for short_name, long_name in column_4_choices %} <option value="{{ short_name }}" {% if short_name == row.column_4 %}selected{% endif %}>{{ long_name }}</option> {% endfor %} </select> </td> {% endfor %} </tbody> </table>
{ "domain": "codereview.stackexchange", "id": 43108, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html", "url": null }