text
stringlengths
1
2.12k
source
dict
c#, .net-core public async Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("Application starts: "); await GetData(); //Stop Application _applicationLifetime.StopApplication(); _logger.LogInformation("Application stops: "); } private async Task SendEmailAsync(string email, string serial, string pin, long id) { var emailMessage = new MimeMessage(); emailMessage.From.Add(new MailboxAddress("Test","test@gmail.com" )); emailMessage.To.Add(new MailboxAddress("", email)); emailMessage.Subject = "Test Codes"; emailMessage.Body = new TextPart("html") { Text = serial +" " + pin }; try { var client = new SmtpClient(); await client.ConnectAsync("smtp.gmail.com", 465, true); await client.AuthenticateAsync("test@gmail.com", "12345"); await client.SendAsync(emailMessage); await client.DisconnectAsync(true); //Update Table await UpdateData(id); } catch (Exception ex) { _logger.LogError("Error: {Error} ", ex.Message); throw; // Throw exception if this exception is unexpected } } private async Task GetData() { var connString = _configuration["ConnectionStrings:Development"]; await using var sqlConnection = new SqlConnection(connString); sqlConnection.Open(); await using var command = new SqlCommand {Connection = sqlConnection}; const string sql = @"Select ID, Email, Serial, Pin from Orders where status = 1"; command.CommandText = sql;
{ "domain": "codereview.stackexchange", "id": 42558, "lm_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-core", "url": null }
c#, .net-core try { await using var reader = await command.ExecuteReaderAsync(); while (reader.Read()) { _logger.LogInformation("Order {ID} , {Email}, {Serial}, {Pin} ", reader.GetInt32(0).ToString(), reader.GetString(1), reader.GetString(2), reader.GetString(3)); await SendEmailAsync(reader.GetString(1).Trim(), reader.GetString(2).Trim(), reader.GetString(3).Trim(), reader.GetInt32(0)); } } catch (SqlException exception) { _logger.LogError("Error: {Error} ", exception.Message); throw; // Throw exception if this exception is unexpected } } private async Task UpdateData(long id) { var connString = _configuration["ConnectionStrings:Development"]; await using var sqlConnection = new SqlConnection(connString); sqlConnection.Open(); await using var command = new SqlCommand {Connection = sqlConnection}; const string sql = @"Update Orders set status = 2, Date = GetDate() where id = @id"; command.CommandText = sql; command.Parameters.Add(new SqlParameter("id", id)); try { await command.ExecuteNonQueryAsync(); } catch (SqlException exception) { _logger.LogError("Error: {Error} ", exception.Message); throw; // Throw exception if this exception is unexpected } } public Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } } } Answer: Some quick remarks:
{ "domain": "codereview.stackexchange", "id": 42558, "lm_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-core", "url": null }
c#, .net-core Answer: Some quick remarks: IMHO things like sending emails or retrieving data should be their own class, not methods in a BusinessService. Per Wikipedia: "every module, class or function in a computer program should have responsibility over a single part of that program's functionality, and it should encapsulate that part. All of that module, class or function's services should be narrowly aligned with that responsibility." _logger.LogError("Error: {Error} ", ex.Message); is not sufficient when you have an InnerException. Look at something like this to get the nested messages as well. GetData() is far too generic a name. You're retrieving orders, so call your method GetOrders. Or rather: put that logic into its own class, name that class OrderService and name your method GetAll. Same for UpdateData. And if your OrderService gets too crowded, consider moving the contents of those methods to their own classed as well, e.g. OrderUpdater, OrdersRetriever,... Don't use ADO.NET, use an ORM like Dapper. Or EntityFramework. Learning to use those is a valuable skill, plus they make life much easier for you. Honestly, no ADO.NET code would pass a code review ay any place I've worked at in the past 15 years or so unless you had an extremely good reason for using it. I know that there's some guideline telling people to name their methods XxxxAsync if they're async, but IMHO that was only relevant when you had both a sync and an async version of a method. At least be consistent: SendEmailAsync vs GetData and UpdateData is not consistent.
{ "domain": "codereview.stackexchange", "id": 42558, "lm_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-core", "url": null }
java, reference Title: Referenceable: A Java Generic Class Used for Creating Objects That can be Mutated Question: public class Referenceable<T> { private T obj; private Referenceable(T t) { obj = t; } public static <U> Referenceable<U> ref(U u){ return new Referenceable<U>(u); } public T dereference() { return obj; } public T dereference(T newT) { // Should be used for reassigning underlying object return obj = newT; } } This simple class allows functions like swap or exchange to be implemented for non-primitive types generically. An example implementation of swap with Referenceable: <T> void swap(Referenceable<T> first, Referenceable<T> second){ var tmp = first.dereference(); first.dereference(second); second.dereference(tmp); } Here is example usage: Referenceable<Integer> ri1 = Referenceable.ref(new Integer(21)), ri2 = Referenceable.ref(new Integer(42)), rn = Referenceable.ref(null); // can reference null objects System.out.prinln(ri1.dereference().toString(), ri2.dereference().toString()); SomeUtilClass.swap(ri1, ri2); System.out.prinln(ri1.dereference().toString(), ri2.dereference().toString()); rn.dereference(new Integer(69)); // more efficient than rn = Referenceable.ref(new Integer(69) Integer i = rn.dereference(); Questions: Referenceable is a bit of mouthful: should I change the name? Should I directly use the constructor instead of a factory function? Could Optional replace Referenceable, making my class useless?
{ "domain": "codereview.stackexchange", "id": 42559, "lm_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, reference", "url": null }
java, reference Could Optional replace Referenceable, making my class useless? Though I doubt it, is there any way for me to make the syntax look something more like this: Referenceable<Integer> ri1 = new Integer(21), // Automatically wraps into Referenceable.ref(new Integer(21)) ri2 = new Integer(42), // ditto rn = Referenceable.ref(null); // ref required because of ambiguity System.out.prinln(ri1.dereference().toString(), ri2.dereference().toString()); //dereference required so Referenceable.toString() is not called SomeUtilClass.swap(ri1, ri2); System.out.prinln(ri1.dereference().toString(), ri2.dereference().toString()); // ditto Integer i = rn; Answer: Its a class holding a single generic field with getter (dereference()) and setter (dereference(T newT)). As you have mentioned it is very much like Optional - except for intention behind its creation. It seems to be quite meta - I would expect to see something like that in cases where we have some kind of self-building code - like specific instructions flow being decided during runtime (so not very procedural). Obviously it can be useful (as much as Optional is) - but its rather hard to judge it without specific context - like, are you sure that effort added with wrapping the objects in additional abstraction (and the added indirection layer making reasoning a little more difficult) is worth it? Maybe there are other approaches to be considered? Answering your questions to the best of my knowledge:
{ "domain": "codereview.stackexchange", "id": 42559, "lm_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, reference", "url": null }
java, reference You can probably shorten it to Ref - as it is pretty well known term in programming in general (then I'd rename factory method in style similar to optional: Ref.of(value)). Or even Reference. I'd expect able suffix to be in the interface name rather than concrete class. Shorter and such generic name might clash with other classes (in java standard lib there are already both Reference and Ref classes) - its difficult to find the right balance in terms of naming. Depends. Are you planing to publish (so that you will not have control over usages of the code) it in some kind of way (like it being part of some library)? If yes, then probably adding additional abstraction layer over creation is a good practice - so that you have extra flexibility as a library author. If usages of the class are fully controlled by you then you can simply use constructor and relay on some modern IDE to help you introducing static factory method if ever necessary (btw. book Effective Java Item 1 describes why someone could want to use static factory method - maybe there are actual use-case specific things that would make it preferable). Probably not. Optional does not have built-in swap functionality - and the value it refers to is not mutable (so you can't really implement it in the same way as in your case). It also has (probably, as I am not sure of yours) different intention behind it - it handles problem of presence of some value - likely result of some operation. I don't know any ways to do it (unless you want to init list of referencables). Also I don't think this is much of an improvement in terms of readability - personally I'd rather see wrapping being explicit and such auto-boxing/casting-ish seems magical to me and hard to explain for newcomers to the code.
{ "domain": "codereview.stackexchange", "id": 42559, "lm_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, reference", "url": null }
c++, object-oriented Title: The bulls and cows game Question: I have implemented the bulls and cows game in C++. The code: #include <cstdio> #include <cstdlib> #include <ctime> struct DigitMatches { int matches_in_right_positions; int matches_in_wrong_positions; }; void CountNumberDigits(int (&counts)[10], int n) { while (n > 0) { counts[n % 10]++; n /= 10; } } class DigitsMatchChecker { public: DigitMatches CheckMatchedDigits(int generated_number, int guess_number) { CountNumberDigits(this->generated_number_left_digits_, generated_number); CountNumberDigits(this->guess_number_left_digits_, guess_number); DigitMatches matches; matches.matches_in_right_positions = this->CountMatchesInRightPositions(generated_number, guess_number); matches.matches_in_wrong_positions = this->CountMatchesInWrongPositions(guess_number); return matches; } private: int CountMatchesInRightPositions(int generated_number, int guess_number) { int matches = 0; while (generated_number > 0 && guess_number > 0) { const int generated_number_digit = generated_number % 10; const int guess_number_digit = guess_number % 10; if (generated_number_digit == guess_number_digit) { matches++; this->guess_number_left_digits_[generated_number_digit]--; this->generated_number_left_digits_[generated_number_digit]--; } generated_number /= 10; guess_number /= 10; } return matches; } int CountMatchesInWrongPositions(int guess_number) { int matches = 0; while (guess_number > 0) { const int guess_number_digit = guess_number % 10; int &generated_number_left_digits = this->generated_number_left_digits_[guess_number_digit]; int &guess_number_left_digits = this->guess_number_left_digits_[guess_number_digit];
{ "domain": "codereview.stackexchange", "id": 42560, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented", "url": null }
c++, object-oriented if (generated_number_left_digits > 0 && guess_number_left_digits > 0) { matches++; generated_number_left_digits--; guess_number_left_digits--; } guess_number /= 10; } return matches; } private: int generated_number_left_digits_[10] = {}; int guess_number_left_digits_[10] = {}; }; void InitializeRandomNumberGenerator() { srand(time(nullptr)); } int GenerateNumber(int min, int max) { return min + (rand() % (max - min + 1)); } int InputNumber() { int n; scanf("%d", &n); return n; } int main() { InitializeRandomNumberGenerator(); const int kTotalNumberOfDigits = 4; const int generated_number = GenerateNumber(1000, 9999); int attempts = 0; while (true) { const int guess_number = InputNumber(); if (guess_number < 1000 || guess_number > 9999) { printf("Invalid number. Must be between 1000 and 9999.\n"); continue; } const DigitMatches matches = DigitsMatchChecker().CheckMatchedDigits(generated_number, guess_number); printf("%d cows, %d bulls\n", matches.matches_in_right_positions, matches.matches_in_wrong_positions); attempts++; if (matches.matches_in_right_positions == kTotalNumberOfDigits) break; } printf("You won! Attempts: %d\n", attempts); return 0; } I would like to hear objective criticism and comments on my code. Answer: Thoughts:
{ "domain": "codereview.stackexchange", "id": 42560, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented", "url": null }
c++, object-oriented I would like to hear objective criticism and comments on my code. Answer: Thoughts: The names are descriptive. This is supposed to be C++ but all of the libraries are from C -- my compiler complains about scanf (changed to scanf_s) as unsafe. Ask yourself "Why did I make a class?" A class is a container for data and code - it defined an object; a "thing" in memory that gets instantiated - and hopefully used. You have created a class that is basically a container for a function. It falls short of being a functor because it does not really maintain its state. Creating a class that held the generated_number as a private variable (or just its digits) and exposed a function to check guesses might be a more logical direction. Did you really need to declare those local variables as 'const'? Const correctness is important and it certainly didn't hurt but that usually refers to arguments to functions and return values etc. i.e. it is used to communicate to others reading/using your code and the compiler when something should be const. With temporary locals, it is not important (but does not hurt anything). -- maybe I have something to learn here. I will think on it more. Reusing the name matches with different types is a bit confusing. Again not BAD but a bit confusing - when a variable graduates to having its own name (as opposed to just i, or x, count, etc.) it is generally is unique within a class or used in a consistent manner (i.e. several functions may have a matches but they would all be of the same type and used in a similar way). generated_number_left_digits should really just be generated_number_left_digit should it not? -- You are referencing just the one element from a similarly named array. Honestly, just a name like generated_digit would be fine. Self-documenting code is wonderful -- but brevity is also to be desired. Why is CountNumberDigits not a member function? Do you really expect to need that function elsewhere?
{ "domain": "codereview.stackexchange", "id": 42560, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented", "url": null }
c++, object-oriented Ask yourself -- what are the likely upgrade paths? Like if users like your game what might they ask for next? More digits perhaps? Using letters and numbers together? etc. How hard would it be to modify this code to work and 8 character hexidecimal strings rather than 4 digit decimal? We want to strive towards generality/abstractness in our code - without sacrificing too much on readability and simplicity. C++ proper, as opposed to the kind of C + "a class" code you have here, offers a lot of features for making things more general. My advice would be to try to do this again in a more C++ way and less C-ish. You can keep the rand() and srand() -- but try to work in some of the C++ standard libraries. I don't just mean cout/cin but C++ data structures/enumerators/algorithms. CountNumberOfDigits just seems to scream re-write with enumerators to me... Also, try to think about how to automate testing. Since your code uses stdin/stdout is actually IS pretty easy to feed it a script but that tests the "whole thing". Maybe try to make sure it is easy to write test cases... I don't know your level of programming but I would say this was pretty good code. It seemed to work, I found it pretty readable and logical to follow. It is not Object Oriented programming but one does not need to view everything in C++ as OOP. Your code was rearranging a bunch of C functions to fit into a class - this is from the school of "C with classes" programming and falls short of C++ programming. Keep it up.
{ "domain": "codereview.stackexchange", "id": 42560, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented", "url": null }
javascript Title: URL redirection via cookie parsing Question: I'm attempting to look at a portion of a cookie's value, and if it contains 'en_us', do one thing, and if it contains 'es_us', do another thing instead. I've written up code that pulls the cookie, returns the cookie value, and then looks to see if the cookie value includes 'en_us'. But I feel like this code can be shortened, I just am struggling with how. const getCookie = async (name) => { const cookie = await cookieStore.get(name); return cookie.value; } const cookieValue = await getCookie('foo'); const cookieEnglish = cookieValue.includes('en_us'); if(cookieEnglish) { redirect to A } else { redirect to B }; Any help is appreciated. Answer: Why would you want to shorten it? I mean you can do it like this: if((await cookieStore.get(name))?.value.includes('en_us')) { redirect to A } else { redirect to B }; But I would lean more towards: const getCookie = async (name) => { return (await cookieStore.get(name))?.value } const isCookieEnglish = (cookie) => { return cookie.includes('en_us') } const cookie = await getCookie('foo') if(isCookieEnglish(cookie)) { redirect to A } else { redirect to B }; Although this has a bug - if foo does not exist we predispose it is Spanish.
{ "domain": "codereview.stackexchange", "id": 42561, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript, node.js Title: Group By Statuses using reduce Question: I have been using reduce() method to group by Open and Closes statuses (Status_111, Status_222, etc) which then creates an array of which Ids (item.Id) it is associated with. Code is working and with an expected result, however, I feel like code could have been written better because as you can see I have been using too many if conditions for creating blank arrays to check if (item.Open && !obj[item.Open]) and if (item.Close && !obj[item.Close]) exists - how would you improve the code? const items = [ { Id: 100, Open: 'Status_111', Close: 'Status_111' }, { Id: 200, Open: 'Status_111', Close: 'Status_222' }, { Id: 300, Open: 'Status_333', Close: 'Status_444' } ] function groupByOpenAndClose(items) { return items.reduce(function (obj, item) { if (item.Open && !obj[item.Open]) { obj[item.Open] = { Open: [], Close: [] } } if (item.Close && !obj[item.Close]) { obj[item.Close] = { Open: [], Close: [] } } if (obj[item.Open]) { obj[item.Open].Open.push(item.Id) } if (obj[item.Close]) { obj[item.Close].Close.push(item.Id) } return obj }, {}); } console.log(groupByOpenAndClose(items)); Answer: Like this: function groupByOpenAndClose(items) { return items.reduce((obj, item) => { return { ...obj, [item.Close]: { Close: [...(obj[item.Close]?.Close ?? []), item.Id], Open: obj[item.Close]?.Open ?? [] }, [item.Open]: { Open: [...(obj[item.Open]?.Open ?? []), item.Id], Close: obj[item.Open]?.Close ?? [] } } }, {}); }
{ "domain": "codereview.stackexchange", "id": 42562, "lm_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", "url": null }
javascript, node.js But in all seriousness, it is not much you can do without creating some structure of your own - something like default dict in python: class DefaultDict { constructor(defFactory) { this.defFactory = defFactory; this.dict = {} } getOrDefault(status) { if(!status) return; if(!this.dict[status]) this.dict[status] = this.defFactory(); return this.dict[status]; } } function groupByOpenAndClose(items) { return items.reduce(function(obj, item) { obj.getOrDefault(item.Close)?.Close.push(item.Id); obj.getOrDefault(item.Open)?.Open.push(item.Id); return obj; }, new DefaultDict(() => ({ Close: [], Open: [] }))); } console.log(groupByOpenAndClose(items).dict);
{ "domain": "codereview.stackexchange", "id": 42562, "lm_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", "url": null }
algorithm, vba, sorting Title: Ordered unique union function Question: I made a user-defined function union in VBA, such that: it could take variable parameters each parameter is a one-column range like A1, A2:A10; we don't need to consider passing constant values to parameters we could consider, within one input range, there are no duplicates; but it is very possible to have duplicates among input ranges. union combines the input ranges, and keeps the order of the elements. For instance, =union(A1:A5, C1:C2, E1:E3) has the following expected output in Column I: I wrote the following code which works. However, it is slow. A union over a list of 4000 rows and a list of 20 rows takes several seconds. First, I don't know whether the way I coded arrays could be improved. Second, the algorithm just consists in comparing each new element against the accumulating result list; there is no sort, no other techniques. Third, I don't know if there are any existing functions we could use in other objects of VBA (eg, VBA FILTER function, Collection, ArrayLists, Scripting.Dictionary). Could anyone propose a more efficient code? Function getDimension(var As Variant) As Long On Error GoTo Err Dim i As Long Dim tmp As Long i = 0 Do While True i = i + 1 tmp = UBound(var, i) Loop Err: getDimension = i - 1 End Function Function exists(v As Variant, arr As Variant, resCount As Long) As Boolean If resCount = 0 Then exists = False Else exists = False i = LBound(arr, 1) Do While (i <= resCount) And (Not exists) If arr(i) = v Then exists = True End If i = i + 1 Loop End If End Function
{ "domain": "codereview.stackexchange", "id": 42563, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, vba, sorting", "url": null }
algorithm, vba, sorting ' assumption: every input is a range (eg, A1, A1:A2) ' assumption: each input range has only one column Function union(ParamArray arr() As Variant) As Variant Dim res As Variant ReDim res(1 To 100000) Dim resCount As Long resCount = 0 For k = LBound(arr) To UBound(arr) Dim arrk As Variant Dim v arrk = arr(k).Value2 If getDimension(arrk) = 0 Then 'case of A1, B1 v = arrk If Not exists(v, res, resCount) Then resCount = resCount + 1 res(resCount) = v End If ElseIf getDimension(arrk) = 2 Then 'case of A1:A10, B1:B10 For i = LBound(arrk, 1) To UBound(arrk, 1) v = arrk(i, 1) If Not exists(v, res, resCount) Then resCount = resCount + 1 res(resCount) = v End If Next i End If Next k ReDim Preserve res(1 To resCount) union = Application.WorksheetFunction.Transpose(res) End Function Answer: Option Explicit Adding Option Explicit to the first line of your modules will force you to declare your variables. Always declare your variables! getDimension() Use arrk.CountLarge instead of this function. If arrk.CountLarge = 1 Then Else End If union Avoid naming User Defined Functions after built in functions. Dim res As Variant ReDim res(1 To 100000) res could initialized when it was declared because it is never resized. Dim res(1 To 100000) As Variant
{ "domain": "codereview.stackexchange", "id": 42563, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, vba, sorting", "url": null }
algorithm, vba, sorting Refactored Code Rem Using a Collection Function Union1(ParamArray Args() As Variant) As Variant Dim Map As New Collection Dim Item As Variant Dim r As Long On Error Resume Next For Each Item In Args If Item.CountLarge > 1 Then For r = 1 To Item.Rows.Count Map.Add Item(r, 1).Value, Item(r, 1).Text Next Else Map.Add Item.Value, Item.Value End If Next On Error GoTo 0 If Map.Count = 0 Then Exit Function Dim Results() As Variant ReDim Results(1 To Map.Count, 1 To 1) For r = 1 To Map.Count Results(r, 1) = Map.Item(r) Next Union1 = WorksheetFunction.TextJoin(",", True, Results) End Function Rem Using an ArrayList Function Union2(ParamArray Args() As Variant) As Variant Dim List As Object Set List = CreateObject("System.Collections.ArrayList") Dim r As Long For Each Item In Args If IsArray(Item) Then For r = 1 To Item.Rows.Count If Not List.Contains(Item(r, 1).Value) Then List.Add Item(r, 1).Value Next Else If Not List.Contains(Item.Value) Then List.Add Item.Value End If Next If List.Count = 0 Then Exit Function Union2 = WorksheetFunction.Transpose(List.ToArray) End Function
{ "domain": "codereview.stackexchange", "id": 42563, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, vba, sorting", "url": null }
algorithm, vba, sorting Union2 = WorksheetFunction.Transpose(List.ToArray) End Function Rem Using a Scripting.Dictionary Function Union3(ParamArray Args() As Variant) As Variant Dim List As Object Set List = CreateObject("Scripting.Dictionary") Dim r As Long For Each Item In Args If IsArray(Item) Then For r = 1 To Item.Rows.Count If Not List.Exists(Item(r, 1).Value) Then List.Add Item(r, 1).Text, Item(r, 1).Value Next Else If Not List.Exists(Item.Value) Then List.Add Item.Text, Item.Value End If Next If List.Count = 0 Then Exit Function Dim Res Res = WorksheetFunction.Transpose(List.Items) Union3 = WorksheetFunction.Transpose(List.Items) End Function
{ "domain": "codereview.stackexchange", "id": 42563, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, vba, sorting", "url": null }
python, numpy Title: find max value in islands defined by other vector Question: I have a vector of values vals, a same-dimension vector of frequencies freqs, and a set of frequency values pins. I need to find the max values of vals within the corresponding interval around each pin (from pin-1 to pin+1). However, the intervals merge if they overlap (e.g., [1,2] and [0.5,1.5] become [0.5,2]). I have a code that (I think) works, but I feel is not optimal at all: import numpy as np freqs = np.linspace(0, 20, 50) vals = np.random.randint(100, size=(len(freqs), 1)).flatten() print(freqs) print(vals) pins = [2, 6, 10, 11, 15, 15.2] # find one interval for every pin and then sum to find final ones islands = np.zeros((len(freqs), 1)).flatten() for pin in pins: island = np.zeros((len(freqs), 1)).flatten() island[(freqs >= pin-1) * (freqs <= pin+1)] = 1 islands += island islands = np.array([1 if x>0 else 0 for x in islands]) print(islands) maxs = [] k = 0 idxs = [] for i,x in enumerate(islands): if (x > 0) and (k == 0): # island begins k += 1 idxs.append(i) elif (x > 0) and (k > 0): # island continues pass elif (x == 0) and (k > 0): # island finishes idxs.append(i) maxs.append(np.max(vals[idxs[0]:idxs[1]])) k = 0 idxs = [] continue print(maxs) Answer: I feel is not optimal at all Good instincts! There is room for vectorisation here. Don't represent pins as a list, but rather as a numpy array. Don't write any loops. Stop creating two-dimensional arrays if you intend to flatten them immediately after. Calculate your islands by broadcasting comparisons for each pin into a matrix, and then reducing it to a vector over the logical_or function. Find the boundaries of your islands by applying a discrete differential. Find the maximum values in each island by masking your value vector with a group matrix, and then applying max over the second axis. Suggested import numpy as np
{ "domain": "codereview.stackexchange", "id": 42564, "lm_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, numpy Suggested import numpy as np # This needs a constant seed for your test to be repeatable rand = np.random.default_rng(seed=0) freqs = np.linspace(start=(0,), stop=(20,), num=50) vals = rand.integers(low=0, high=100, size=(len(freqs),)) pins = np.array((2, 6, 10, 11, 15, 15.2)) # Matrix, for each pin, of booleans for which values are in range all_islands = (freqs >= pins - 1) & (freqs <= pins + 1) # Reduce to a vector, one entry per value islands = np.logical_or.reduce(all_islands, dtype=int, axis=1, keepdims=True) # Discrete differential to find island boundaries (vector) diffs = np.diff(islands.T.astype(int)) # Value indices needed to construct group masks (vector) val_idx = np.arange(len(vals))[np.newaxis, :] # Start and end indices for each island (vectors) _, island_starts = np.nonzero(diffs == 1) _, island_ends = np.nonzero(diffs == -1) # For each island, of group masks (matrix) groups = (val_idx > island_starts[:, np.newaxis]) & (val_idx < island_ends[:, np.newaxis]) # Reduce over the second axis getting maximum values in each group maxes = np.max(groups * vals, axis=1) assert np.all(maxes == (30, 97, 85, 54))
{ "domain": "codereview.stackexchange", "id": 42564, "lm_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, pandas Title: count number of rows given column names and values - pandas Question: I am currently switching for R to Python so please be patient with me. Is the following a good way to count the number of rows given column names and values? import pandas as pd df = pd.DataFrame([["1", "2"], ["2", "4"], ["1", "4"]], columns=['A', 'B']) cn1 = "A" cn2 = "B" cv1 = "1" cv2 = "2" no_rows = len(df[(df[cn1]==cv1) & (df[cn2]==cv2)].index) print(no_rows) Answer: First, it's a bad idea to input your numerics as strings in your dataframe. Use plain ints instead. Your code currently forms a predicate, performs a slice on the frame and then finds the size of the frame. This is more work than necessary - the predicate itself is a series of booleans, and running a .sum() on it produces the number of matching values. That, plus your current code is not general-purpose. A general-purpose implementation could look like from typing import Dict, Any import pandas as pd def match_count(df: pd.DataFrame, **criteria: Any) -> int: pairs = iter(criteria.items()) column, value = next(pairs) predicate = df[column] == value for column, value in pairs: predicate &= df[column] == value return predicate.sum() def test() -> None: df = pd.DataFrame( [[1, 2], [2, 4], [1, 4]], columns=['A', 'B'], ) print(match_count(df, A=1, B=2)) if __name__ == '__main__': test()
{ "domain": "codereview.stackexchange", "id": 42565, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas", "url": null }
c++, ascii-art Title: Output a pyramid of numbers Question: I have this problem where I've to print a number pyramid by taking input from the user. 1 2 3 2 3 4 5 4 3 4 5 6 7 6 5 4 5 6 7 8 9 8 7 6 5 I've written the following code and then output is correct. However, I was wondering if there are any other optimized way to print this pyramid, since mine includes 4 loops. #include<iostream> using namespace std; int main() { int a; cin>>a; for(int i=1;i<=a;i++) { for(int j=a-i;j>=0;j--) { cout<<" "; } for(int k=i;k<=(i+i-1);k++) { cout<<(k)<<" "; } for(int l=i+i-2;l>=i;l--) { cout<<l<<" "; } cout<<endl; } return 0; } Answer: Don’t write using namespace std;. You can, however, in a CPP file (not H file) or inside a function put individual using std::string; etc. (See SF.7.) ⧺SL.io.50 Don't use endl. Your first inner loop is just printing a-i spaces, right? Use the width modifier to ostream output to just do that with one command. A single space should be a character, not a string. It will be more efficient. cout << setw(a-i) << ' '; Prefer prefix increment/decrement. It doesn't affect the efficiency for plain int when not using the value of the expression, but more generally the prefix for is efficient in-place modification and the postfix causes a copy to be made. Seeing a postfix ++ in a for loop or whenever the return value is not used is a code review issue — it's wasted brain power and a distraction to figure out "Oh, it doesn't matter this time." Looping n times: The C-style for loop is awkward and more complex than simply saying what you want. With C++20 you can use std::ranges::views::iota. In older versions where this is not included with the compiler, you can use other libraries with your program or supply your own simple counter as part of your program.
{ "domain": "codereview.stackexchange", "id": 42566, "lm_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++, ascii-art", "url": null }
php, wordpress Title: Custom Block with ACF in WordPress Question: I'm learning and want to improve as much as possible. In doing so I have written this custom block that has an image on one side and an inner block on the other. It's using ACF to get the variables and comments should state most of the items. I'm looking for recommendations to improve, readability, functionality, or security issues I may not have addressed. I made an image function that should be responsive. Everything functions fine but I'd like to make it cleaner and faster. Looking forward to seeing recommendations - I want to improve in any way possible! First off the block file <?php /** * Two Column Block with Image & Innerblock * * A two column block with innerblock on one side and image on the other * options of 50/50 and 40/60 sizes available * Can switch content sides and image is always on top * * @param function wg_child_acf_image_block() to return images output * @author Andrew */
{ "domain": "codereview.stackexchange", "id": 42567, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, wordpress", "url": null }
php, wordpress $padding = get_field( 'padding' ); //Padding $top = get_field( 'top' ); //Custom padding top $bottom = get_field( 'bottom' ); //Custom Padding bottom $image = get_field( 'image' ); //Image field $sizing = get_field( 'sizing' ) ?: 'fiftyFifty'; //Select field that sets sizes to 50/50 or 40/60 $side = get_field( 'side' ) ?: 'normal'; //Switch Content Sides $combined = $sizing . ' ' . $side; //Combined for output $image_fallback = 'wg-align-image-left'; //Set Default Image alignment $inlineStyle = ''; //Create variable for optional custom padding $anchor = ''; //Create variable for custom anchor option $center = ''; //Create variable for align-self innerblock //Change default image alignment if reversed if( $side == 'reverse' ) { $image_fallback = 'wg-align-image-right'; } //Alignment of image w/ fallback $align_image = get_field( 'alignimage' ) ?: $image_fallback; //Determining Padding For Block - default is else if( 'narrow' == $padding ) { $padding = 'blockPadding-narrow'; } elseif( 'none' == $padding ) { $padding = 'blockPadding-none'; } elseif( 'custom' == $padding ) { $inlineStyle = 'style="padding-top: ' . $top . 'vh; padding-bottom: ' . $bottom . 'vh;"'; $padding = false; } else { $padding = 'blockPadding'; } //Determines if padding is a class or inline and created classes array if( $padding ) { $classes = [$padding]; } else { $classes = []; } //Adds custom class if provided if( !empty( $block['className'] ) ) $classes = array_merge( $classes, explode( ' ', $block['className'] ) );
{ "domain": "codereview.stackexchange", "id": 42567, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, wordpress", "url": null }
php, wordpress //Adds custom anchor if provided if( !empty( $block['anchor'] ) ) $anchor = ' id="' . sanitize_title( $block['anchor'] ) . '"'; //Default data that goes inside innerblock when created but can be removed $template = array( array('core/heading', array( 'content' => 'Title Text Goes Here', )), array( 'core/paragraph', array( 'content' => 'Enter in your paragraph text here for further information', ) ) ); //Option to turn off align-self: center; if( get_field( 'center' ) == false ) { $center = ' center-self'; } //Opening Div - determines if class or inline for padding if( $inlineStyle ) { echo '<section class="' . join( ' ', $classes ) . '"' . esc_attr($anchor) . ' ' . esc_attr($inlineStyle) . '>'; } else { echo '<section class="' . join( ' ', $classes ) . '"' . esc_attr($anchor) . '>'; } ?> <div class="wrapper"> <div class="twoColumns <?php echo esc_attr($combined); ?>"> <div class="leftSide"> <div class="imageWrap"> <?php //arguments are image array, optional image class, optional image size ?> <?php wg_child_acf_image_block( $image, $align_image ); ?> </div> </div> <div class="rightSide<?php if($center) { echo esc_attr($center); } ?>"> <?php echo '<InnerBlocks template="' . esc_attr( wp_json_encode( $template ) ) . '" />'; ?> </div> </div> </div> <?php //closing div echo '</section>'; ?>
{ "domain": "codereview.stackexchange", "id": 42567, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, wordpress", "url": null }
php, wordpress <?php //closing div echo '</section>'; ?> Next is the image function which is used in the above file: <?php /** * Function to call ACF Image array and convert it to a SEO friendly image result * * Image function that takes an image array from ACF (or other similiar plugins) and * converts it into a responsive image. * Required argument of $image which is the array * Optional argument of $imageClass to pass an optional class * Optional argument of $imgsize that passes a different size iamge * * @param array $image uses ACF image array * @since 1.0.0 * @author: Andrew */ function wg_child_acf_image_block($image, $imageClass = '', $imgsize = 'large') { if( $image ) { // Image attribuates. $url = $image['url']; $title = $image['title']; $alt = $image['alt'] ?: $title; $caption = $image['caption']; $imgsize = 'large'; //adds w on the end of sizes $w = 'w'; // Image sizes and src sets. $thumb = $image['sizes'][ $imgsize ]; $width = $image['sizes'][ $imgsize . '-width' ]; $height = $image['sizes'][ $imgsize . '-height' ]; $medlg = $image['sizes']['medium_large']; $medlg_width = $image['sizes']['medium_large-width'] . $w; $med = $image['sizes']['medium']; $med_width = $image['sizes']['medium-width'] . $w; $tn = $image['sizes']['thumbnail']; $tn_width = $image['sizes']['thumbnail-width'] . $w; //Returned Result $result = ''; // Begin caption wrap. if( $caption ): $result .= '<div class="wp-caption">'; endif;
{ "domain": "codereview.stackexchange", "id": 42567, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, wordpress", "url": null }
php, wordpress //img item $result .= '<img src="' . esc_url($thumb) . '" srcset="' . esc_url($medlg) .' '. esc_attr($medlg_width) . ', ' . esc_url($med) . ' ' . esc_attr($med_width) . ', ' . esc_url($tn) . ' ' . esc_attr($tn_width) . '" alt="' . esc_attr($alt) . '" width="' . esc_attr($width) . '" height="' . esc_attr($height) . '" title="' . esc_attr($title) . '" class="' . esc_attr($imageClass) . ' wg-image-class" />'; // End caption wrap. if( $caption ): $result .= '<p class="wp-caption-text">' . esc_html($caption) . '</p>'; $result .= '</div>'; ?> <?php endif; ?> <?php //end if($image) statement } else { //Fallback image if no image $result = '<img src="' . get_stylesheet_directory_uri() . '/assets/images/filler.jpg' . '" alt="Filler Image" class="' . esc_attr($imageClass) . ' wg-image-class">'; } //Output the image echo $result; }
{ "domain": "codereview.stackexchange", "id": 42567, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, wordpress", "url": null }
php, wordpress //Output the image echo $result; } Answer: Regarding readability/maintainability, my eye is drawn toward missed opportunities to practice D.R.Y. coding practices. I will suggest ways to make less verbose/repeated code, avoid heavily concatenated strings, and minimize the total number of variables declared. The adjustments to padding are all checking the same variable; this makes a switch() (or match() if you are using the latest and greatest PHP version) appropriate. I also don't see any benefit to overwriting $padding only to conditionally populate the $classes variable further down the script. In fact, with my snippet below, $padding becomes a single-use variable and this indicates that it shouldn't be declared at all -- just use get_field('padding'). $classes = []; switch(get_field('padding')) { case 'narrow': $classes[] = 'blockPadding-narrow'; break; case 'none': $classes[] = 'blockPadding-none'; break; case 'custom': $inlineStyle = 'style="padding-top: ' . $top . 'vh; padding-bottom: ' . $bottom . 'vh;"'; break; default: $classes[] = 'blockPadding'; } Next, I don't see anywhere in the first snippet where the $block array is declared. This makes it very hard for me to review its relevance. I'll just mention that if you are going to write a condition block, always obey PSR-12 coding standards and use curly braces to encapsulate your condition body. This makes your code far less vulnerable to typos/oversights. The handling of $center could be cleaned up. You declare it as an empty string, then you check if get_field('center') is loosely false, then in your html you are only conditionally printing a value. I think the preparation should be closer to the top and consolidated/simplified. $center = get_field('center') ? '' : ' center-self'; // Option to turn off align-self: center;
{ "domain": "codereview.stackexchange", "id": 42567, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, wordpress", "url": null }
php, wordpress As for the remaining HTML generation, I recommend using printf() to avoid concatenation. If you get lost counting the %s placeholders, you can number them (e.g. %1$s, %2$s, etc.). $template = <<<HTML <section class="%s"%s%s> <div class="wrapper"> <div class="twoColumns %s"> <div class="leftSide"> <div class="imageWrap">%s</div> </div> <div class="rightSide%s"> <InnerBlocks template="%s" /> </div> </div> </div> </section> HTML; printf( $template, implode(' ', $classes), esc_attr($anchor), $inlineStyle ? ' ' . esc_attr($inlineStyle) : '', esc_attr($combined), wg_child_acf_image_block($image, $align_image), //arguments are image array, optional image class, optional image size $center ? esc_attr($center) : '', esc_attr(wp_json_encode($template)) ); I'll curb the urge to repeat myself and keep this answer D.R.Y. Suffice to say that the same general guidance for your first snippet can be re-applied to your second snippet.
{ "domain": "codereview.stackexchange", "id": 42567, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, wordpress", "url": null }
rust, pig-latin Title: Pig Latin terminal app in Rust Question: I've started learning Rust a few days ago. This is the Pig Latin exercise from the Rust Book. The code works as expected. I have commented the logic of the program in the code. My handling of Strings is very hacky, as far as I know. To be honest, I mostly fiddled with it looking at error messages until the compiler was satisfied. I'd like to know what would be a idiomatic and may be more readable way to write it and if there as sane ways to optimize, especially the string manipulation part. Thank you use std::io; fn main() { println!("Please enter a sentence:"); const VOWELS: &str = "aeoiu"; let mut sentence = String::new(); io::stdin() .read_line(&mut sentence) .expect("An error occured"); let mut words = sentence .split_whitespace() .map(|x| String::from(x)) .collect::<Vec<String>>(); for word in &mut words { if VOWELS.contains(word.chars().nth(0).unwrap().to_ascii_lowercase()) { // Starts with consonant: // The first consonant of each word is moved to the end of the word // and “ay” is added, so “first” becomes “irst-fay.” *word = format!("{}-hay", (*word).clone()); // *word = (*word).clone() + "-" + "hay"; } else { // Starts with a vowel: // Add “hay” to the end (“apple” becomes “apple-hay”). *word = format!( "{}-{}ay", String::from(&word[1..]), word.chars().nth(0).unwrap().to_string() ); // String::from(&word[1..]) + "-" + &(word.chars().nth(0).unwrap().to_string()) + "ay"; } } println!("{}", words.join(" ")) ``` Answer: I wrote my comments in the new code: fn main() { // I removed the input for simplicity let sentence = String::from("The elves are coming");
{ "domain": "codereview.stackexchange", "id": 42568, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, pig-latin", "url": null }
rust, pig-latin // I removed the input for simplicity let sentence = String::from("The elves are coming"); // You don't need to collect to an intermediary vector and then mutate values inside // It is always nice if you can manage without mutating // It is also always good to split out big chunks of code into functions, here "pigifize". You can then debug or unit test that single function, for example let words = sentence .split_whitespace() .map(pigifize) .collect::<Vec<_>>(); println!("{}", words.join(" ")) } const VOWELS: &str = "aeoiu"; fn pigifize(word: &str) -> String { if word.is_empty() { // I don't know if this case can happen from split_whitespace, but just to get it out of the way (it makes the function more robust, should it get called in other cases) word.into() } else { // I removed your comments about the 2 cases because they were inverted. But they could be readded let first = word.chars().nth(0).unwrap(); if VOWELS.contains(first.to_ascii_lowercase()) { format!("{}-hay", word) // format! can print string slices so you don't need to create String's as much } else { format!( "{}-{}ay", &word[1..], first ) } } } Some example tests (they can help you while you develop the function too): #[test] fn pigifize_vowel() { assert_eq!(pigifize("unicorn"), "unicorn-hay") } #[test] fn pigifize_consonant() { assert_eq!(pigifize("rhino"), "hino-ray") } #[test] fn pigifize_empty() { assert_eq!(pigifize(""), "") }
{ "domain": "codereview.stackexchange", "id": 42568, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, pig-latin", "url": null }
python, python-3.x Title: Cached shortened urls Question: Im currently writing my own cached shortened urls where I at the start of application read the database that has all the stored url:uuid from the database into a global dict value. When a person enters a url. It checks if its already in the dict. If the url exists in the dict, then we re-use the uuid (instead of creating a new one). If it does not exists. Then we insert it to database and return the generated uuid. My goal is to have a cached stored shortened urls so that it doesn't take any extra "hits" on the database and actually reuses the existed url:uuid. from lib.database import Stores, Urls SHORTENED_URLS: dict = {} DOMAIN = 'https://helloworld.com/' # add all uuid to url as a dict that are already stored in db for i in Urls.get_all_by_store(): SHORTENED_URLS[i.url] = i.uuid def generate_url(url): # Check if the URL is in the dict if url in SHORTENED_URLS: # Return the uuid from the "cached" dict return f'{DOMAIN}{SHORTENED_URLS[url]}' # Else get the uuid from the database # Database will try to insert, if duplicated then get the uuid generated = Urls.get_uuid(url) # Add the url : uuid to the database SHORTENED_URLS[url] = generated return f'{DOMAIN}{generated}' if __name__ == '__main__': get_url = generate_url('https://www.testing.com') print(get_url) DATABASE # ------------------------------------------------------------------------------- # # Redirect urls # ------------------------------------------------------------------------------- # class Urls(Model): store_id = IntegerField(column_name='store_id') url = TextField(column_name='url') uuid = TextField(column_name='uuid') store = ForeignKeyField(Stores, backref='urls') class Meta: database = postgres_pool db_table = "urls"
{ "domain": "codereview.stackexchange", "id": 42569, "lm_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 class Meta: database = postgres_pool db_table = "urls" @classmethod def get_all_by_store(cls): try: return cls.select().where((cls.store_id == Stores.store_id)) except peewee.IntegrityError as err: print(f"{type(err).__name__} at line {err.__traceback__.tb_lineno} of {__file__}, {url}: {err}") return False @classmethod def get_uuid(cls, url): try: return cls.select().where((cls.store_id == Stores.store_id) & (cls.url == url)).get().uuid except Urls.DoesNotExist: while True: try: gen_uuid = ''.join(choices(string.ascii_letters + string.digits, k=8)) cls.insert( store_id=Stores.store_id, url=url, uuid=gen_uuid ).execute() return gen_uuid except peewee.IntegrityError as err: print(f"Duplicated key -> {err}") postgres_pool.rollback() sleep(1) except peewee.IntegrityError as err: print(f"{type(err).__name__} at line {err.__traceback__.tb_lineno} of {__file__}, {url}: {err}") return False My question is, is there anything I can do to improve the shortened url cached?
{ "domain": "codereview.stackexchange", "id": 42569, "lm_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 My question is, is there anything I can do to improve the shortened url cached? Answer: Re. for i in Urls.get_all_by_store(), beware putting significant work like this in the global namespace. This bypasses your main check and will incur a delay whenever someone attempts to load your module. As @FMc warns, this program - unless it's single-process - cannot scale. Caching is a very difficult and complicated thing to get right. As soon as there are multiple processes serving requests for your clients, how are you going to coordinate in-memory cache between them? There are off-the-shelf solutions for this, but broadly, I suspect that caching should not be your only concern when scaling. There's a whole constellation of decisions you need to make around service architecture that will influence which caching solution you need, or indeed if you need one at all.
{ "domain": "codereview.stackexchange", "id": 42569, "lm_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, beginner, object-oriented Title: Hot Dog Cookout Calculator Question: Hiii... Can you please check the code and see whether I might have done a mistake ? Beginner's eyes can be misleading quite easily. I feel like there's something wrong in this solution. I can't figure out what. so please check the solution and let me know. keep in mind i'm native sinhala speaker. Assume hot dogs come in packages of 10, and hot dog buns come in packages of 8. Write a program that calculates the number of packages of hot dogs and the number of packages of hot dog buns needed for a cookout, with the minimum amount of leftovers. The program should ask the user for the number of people attending the cookout and the number of hot dogs each person will be given. The program should display the following details: The minimum number of packages of hot dogs required. The minimum of hot dogs that will be left over. The number of hot dog buns that will be left over. # Declare hot dogs and hot dog buns HOT_DOGS_PER_PACKAGE = 10 HOT_DOGS_BUNS_PER_PACKAGE = 8 # Get the number of attendees attendees = int(input('Enter the number of guests: ')) # Number of hot dogs per person hot_dogs_per_person = int(input('Hot dogs per person: ')) # Number of hot dogs required required_hot_dogs = attendees * hot_dogs_per_person packages_of_hot_dogs = required_hot_dogs / HOT_DOGS_PER_PACKAGE # Number of hot dog buns required packages_of_hot_dog_buns = required_hot_dogs / HOT_DOGS_BUNS_PER_PACKAGE print(f"You require {packages_of_hot_dogs} hot dogs for the cookout.") print(f"You require {packages_of_hot_dog_buns} buns for the cookout.") # Number of left over hot dogs remain_hotdogs = required_hot_dogs % HOT_DOGS_PER_PACKAGE if remain_hotdogs != 0: print(f'You have {remain_hotdogs} left over hot dogs') remain_buns = required_hot_dogs % HOT_DOGS_BUNS_PER_PACKAGE if remain_buns != 0: print(f'you have {remain_buns} left over hot dog buns. ')
{ "domain": "codereview.stackexchange", "id": 42570, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, object-oriented", "url": null }
python, beginner, object-oriented Program output Enter the number of guests: 25 Hot dogs per person: 5 You require 12.5 hot dogs for the cookout. You require 15.625 buns for the cookout. You have 5 left over hot dogs you have 5 left over hot dog buns. Answer: I think the error is in your output. You require 12.5 hot dogs for the cookout. You require 15.625 buns for the cookout. It should be: You require 12.5 packs of hot dogs for the cookout. You require 15.625 packs of buns for the cookout. But in the real world, you should use math.ceil for it: You require 13 packs of hot dogs for the cookout. You require 16 packs of buns for the cookout. import math print(f"You require {math.ceil(packages_of_hot_dogs)} packs of hot dogs for the cookout.") print(f"You require {math.ceil(packages_of_hot_dog_buns)} packs of buns for the cookout.") Also your math with buns doesn't add up. But you can fix it very easily. import math HOT_DOGS_PER_PACKAGE = 10 HOT_DOGS_BUNS_PER_PACKAGE = 8 attendees = int(input('Enter the number of guests: ')) hot_dogs_per_person = int(input('Hot dogs per person: ')) required_hot_dogs = attendees * hot_dogs_per_person packages_of_hot_dogs = required_hot_dogs / HOT_DOGS_PER_PACKAGE packages_of_hot_dog_buns = required_hot_dogs / HOT_DOGS_BUNS_PER_PACKAGE print(f"You require {math.ceil(packages_of_hot_dogs)} packs of hot dogs for the cookout.") print(f"You require {math.ceil(packages_of_hot_dog_buns)} packs of buns for the cookout.") remain_hotdogs = (math.ceil(packages_of_hot_dogs) * HOT_DOGS_PER_PACKAGE) - required_hot_dogs if remain_hotdogs != 0: print(f'You have {remain_hotdogs} left over hot dogs') remain_buns = (math.ceil(packages_of_hot_dog_buns) * HOT_DOGS_BUNS_PER_PACKAGE) - required_hot_dogs if remain_buns != 0: print(f'You have {remain_buns} left over hot dog buns. ') Also, if you name your variable required_hot_dogs, you don't really need to add a comment to it. Your names are more than self-explanatory, so try to keep it nice and clean.
{ "domain": "codereview.stackexchange", "id": 42570, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, object-oriented", "url": null }
c++, beginner, c++11, pointers, namespaces Title: C++ Linked list with smart pointers Question: This seems to work fine, but I'm very new to C++ and would like any suggestions for improvements. Areas I have the most trouble with are: Namespacing (honestly, it's still half looking stuff up and making an educated guess with typename blah blah blah). Is there a "cleaner" way to implement this? Various C++ idioms (copy and swap) that aren't as common in, say, C or Java. There are good answers relating to copy and swap in particular, but I just don't quite "get it" yet. The principal makes sense, but specifically what to do with regards to protecting against exceptions in the copy constructor itself Adding to that, exceptions in general in C++ (coming from the strict Java approach and the "check errno/return value/whatever" C approach), although in the context of this code it's more about guaranteeing exception safety where people would expect it (see above). General good "style". Specifically, what's the cleanest way to implement the Node class in data structures where we see something like this? this plays into how namespacing can get tricky. There seems to be a tradeoff of encapsulation (e.g. defining a struct node within the LinkedList class seems intuitively more "reasonable", but this makes dealing with nodes in any function that may be written outside my definition file strewn with typename). Another example: should root really be a unique_ptr here instead of a regular object? It certainly made my code easier to write, but I'm curious as to arguments for or against it. I'm still fairly unclear as to when exactly I need the template declaration for classes (see the copy constructor for instance, where it takes LinkedList as an argument instead of LinkedList<T>, but it worked, which seems odd).
{ "domain": "codereview.stackexchange", "id": 42571, "lm_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, c++11, pointers, namespaces", "url": null }
c++, beginner, c++11, pointers, namespaces I understand the use case between e.g. unique_ptr and shared_ptr for the most part, but certainly want to know if I'm misusing anything here. There is nothing fancy (like a reference to the tail to make insertion faster), but I just want to make sure I'm starting out on the right foot as the more I use C++ it seems the less I actually understand anything. LinkedList class header #ifndef _NEW_LL_H #define _NEW_LL_H #include<memory> #include "node.h" template <typename T> class LinkedList { public: LinkedList() {}; ~LinkedList() {}; // destructor LinkedList(LinkedList const & ll); // copy constructor LinkedList& operator=(LinkedList const & ll); // copy assignment LinkedList(LinkedList && ll); // move constructor LinkedList& operator=(LinkedList && ll); // move assignment void append(T const& item); // deletes the first node containing item, returns true if successful bool delete_node(T const& item); void print(); bool search(T const& item); std::unique_ptr<typename Node<T>::Node> root; // std::unique_ptr<Node> tail; maybe later }; #endif Node header #ifndef _NODE_H #define _NODE_H #include<memory> template <typename T> class Node { public: T item; std::unique_ptr<Node> next=nullptr; Node(T const& t); // default constructor Node(Node const& insert); // copy constructor }; #endif Implementation file #include <iostream> #include <memory> #include "new_ll.h" using namespace std; template <typename T> LinkedList<T>::LinkedList(LinkedList const & ll) { if(ll.root) root = make_unique<Node<T>>(*ll.root); } // copy constructor calls node's recursively template <typename T> LinkedList<T>& LinkedList<T>::operator=(LinkedList<T> const & ll) { if(ll.root) root = make_unique<Node>(*ll.root); } // copy assignment template <typename T> LinkedList<T>::LinkedList(LinkedList<T> && ll) { root = move(ll.root); } // move constructor
{ "domain": "codereview.stackexchange", "id": 42571, "lm_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, c++11, pointers, namespaces", "url": null }
c++, beginner, c++11, pointers, namespaces template <typename T> LinkedList<T>& LinkedList<T>::operator=(LinkedList<T> && ll) { root = move(ll.root); } // move assignment template <typename T> void LinkedList<T>::append(T const& item) { if(root==nullptr) { root = make_unique<Node<T>>(item); return; } Node<T> *tmpNode = root.get(); while(tmpNode->next!=nullptr) tmpNode=tmpNode->next.get(); tmpNode->next = make_unique<Node<T>>(item); } template <typename T> bool LinkedList<T>::delete_node(T const& item) { if(root->item == item) { root = move(root->next); return true; } Node<T> *tmpNode = root.get(); while(tmpNode->next!=nullptr) { if(tmpNode->next->item == item) { tmpNode->next = move(tmpNode->next->next); return true; } tmpNode = tmpNode->next.get(); } return false; } template <typename T> void LinkedList<T>::print() { Node<T> *tmpNode = root.get(); while(tmpNode!=nullptr) { cout << "Address: " << tmpNode << " value: " << tmpNode->item << endl; tmpNode = tmpNode->next.get(); } } template <typename T> bool LinkedList<T>::search(T const& item) { Node<T> *tmpNode = root.get(); while(tmpNode!=nullptr) { if(tmpNode->item == item) return true; tmpNode = tmpNode->next.get(); } return false; } template <typename T> Node<T>::Node(T const& t) : item(t) {}; // default constructor template <typename T> Node<T>::Node(Node const& insert) : item(insert.item) { if(insert.next) next = make_unique<Node<T>>(*insert.next); }; // copy constructor Any input is appreciated! I just feel like an idiot as I seem to constantly be learning and forgetting "good" C++ practice. Answer: LinkedList Header Don't use identifiers with a leading underscore: #ifndef _NEW_LL_H #define _NEW_LL_H These two are not valid (reserved for the implementation). Header inclusion order: #include<memory> #include "node.h"
{ "domain": "codereview.stackexchange", "id": 42571, "lm_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, c++11, pointers, namespaces", "url": null }
c++, beginner, c++11, pointers, namespaces I always do most specific to least. So your local header files first. Then C++ header files. Then C header files. Also add a space before <memory.h>. Put the & with the type (its part of the type information). LinkedList(LinkedList const & ll); // copy constructor LinkedList& operator=(LinkedList const & ll); // copy assignment LinkedList(LinkedList && ll); // move constructor LinkedList& operator=(LinkedList && ll); // move assignment You have a normal append. void append(T const& item); But your list is move aware. So it seems like you should be able to move elements into the list. void append(T&& item); template<typename... Args> void append(Args&&... args); // append item but use its constructor. Node Header Don't use identifiers with a leading underscore: #ifndef _NODE_H #define _NODE_H These two are not valid (reserved for the implementation). You have normal constructors: Node(T const& t); // default constructor Node(Node const& insert); // copy constructor But what about the move constructors. Node(Node&& move); Source File review: Don't do this: using namespace std; Its short for a reason. Adding std:: as a prefix is not that much of a burden. Get used to it. Also worth a read Why is “using namespace std” considered bad practice?. It will explain in detail why it is bad practice. This does not work if the source is empty. template <typename T> LinkedList<T>& LinkedList<T>::operator=(LinkedList<T> const & ll) { if(ll.root) root = make_unique<Node>(*ll.root); } // copy assignment This means if you try and copy a list (that happens to be empty) nothing happens. Which is not what you want. If the source is empty then you want your list to become empty (not keep its current content). just convert to using the copy and swap idiom. Prefer to use the initializer list than the body. template <typename T> LinkedList<T>::LinkedList(LinkedList<T> && ll) { root = move(ll.root); } // move constructor
{ "domain": "codereview.stackexchange", "id": 42571, "lm_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, c++11, pointers, namespaces", "url": null }
c++, beginner, c++11, pointers, namespaces Here you are basically initializing root with nullptr then immediately assigning over it. You can simplify this a lot. It should not matter if the root is nullptr or not. You are always adding to a thing that is unique_ptr<Node>. Just find the correct one then call make_unique() template <typename T> void LinkedList<T>::append(T const& item) { if(root==nullptr) { root = make_unique<Node<T>>(item); return; } Node<T> *tmpNode = root.get(); while(tmpNode->next!=nullptr) tmpNode=tmpNode->next.get(); tmpNode->next = make_unique<Node<T>>(item); } Your delete is basically a search() followed by a delete. Why not reduce redundant code by moving the search into its own private doSearch() function that returns a Node*. Then the public functions can use this private function and return the appropriate value. template <typename T> bool LinkedList<T>::delete_node(T const& item) { if(root->item == item) { root = move(root->next); return true; } Node<T> *tmpNode = root.get(); while(tmpNode->next!=nullptr) { if(tmpNode->next->item == item) { tmpNode->next = move(tmpNode->next->next); return true; } tmpNode = tmpNode->next.get(); } return false; } If you are going to print. Then a least allow the user to specify what stream you want to print too (you can provide a default version): template <typename T> void LinkedList<T>::print(std::ostream& out = std::cout) { } Note the default way to print something in C++ is to use the operator<< so you may as well define one of those while you are at it: frined std::ostream& operator<<(std::ostream& str, LinkedList const& list) { list.print(str); return str; }
{ "domain": "codereview.stackexchange", "id": 42571, "lm_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, c++11, pointers, namespaces", "url": null }
c++, image Title: Duplicating 8-bit BMP with C++ Question: Trying to create a simple image processing library in pure C++. Here is the first part, duplicating 8-bit BMP images (taken from Udemy in hybrid c/c++ but I modified it a bit). Any comments are welcome. Image.hpp #pragma once #include <stdlib.h> #include <stdio.h> #include <iostream> class Image { public: Image(const char *filename); ~Image(); void CopyTo(const char *filename) const; private: int _width; int _height; int _depth; unsigned char *_header; unsigned char *_table; unsigned char *_buffer; }; Image.cpp #include "Image.hpp" Image::Image(const char *filename) { FILE *fi = fopen(filename, "rb"); if (fi == nullptr) { printf("%s", "Unable to open the file"); exit(1); } _header = new unsigned char[54]; fread(_header, sizeof(unsigned char), 54, fi); memcpy(&_width, _header + 18, 4); memcpy(&_height, _header + 22, 4); memcpy(&_depth, _header + 28, 2); if (_depth <= 8) { _table = new unsigned char[1024]; fread(_table, sizeof(unsigned char), 1024, fi); } _buffer = new unsigned char[_width * _height]; fread(_buffer, sizeof(unsigned char), _width * _height, fi); fclose(fi); } Image::~Image() { delete _header; delete _table; delete _buffer; } void Image::CopyTo(const char *filename) const { FILE *fo = fopen(filename, "wb"); fwrite(_header, sizeof(unsigned char), 54, fo); if (_depth <= 8) fwrite(_table, sizeof(unsigned char), 1024, fo); fwrite(_buffer, sizeof(unsigned char), _width * _height, fo); fclose(fo); } test.cpp #include "Image.hpp" const string array[] = { "flower", // 0 "car", // 1 "robot", // 2 "computer", // 3 "baby", // 4 };
{ "domain": "codereview.stackexchange", "id": 42572, "lm_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++, image", "url": null }
c++, image const int selector = 4; const string pi = (string)getenv("RESOURCES") + "/" + array[selector] + ".bmp"; const string po = (string)getenv("RESOURCES") + "/" + array[selector] + "_copy.bmp"; int main() { Image m(pi.c_str()); m.CopyTo(po.c_str()); return 0; } Answer: The code in question doesn't take in to account the palette which comes before pixel data. It ends up reading the palette in to pixel data. 8-bit, 4-bit, and 1-bit bitmaps have palettes. The palette starts immediately after file header, and before image data. Width alignment is not considered. The width of the bitmap, in bytes, should always be aligned to 4. For example, for 8-bit bitmap, if the width of the bitmap is 311, it should be padded in memory and in file, so it reaches 312. The display will still show only 311 pixels in width. Support for big/little endian can be added. std::vector<uint8_t> instead of user allocated buffer will simplify memory management. #include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> class Image { template<typename T> void readint(std::ifstream& f, T& val) { //endian-independant read //static_assert(sizeof(T) <= 4); //requires c++17 uint8_t buf[4]; f.read((char*)buf, sizeof(val)); val = 0; for (int i = sizeof(val) - 1; i >= 0; i--) val += (buf[i] << (8 * i)); } template<typename T> void writeint(std::ofstream& f, T val) { //endian-independant write //static_assert(sizeof(T) <= 4); //requires c++17 uint8_t buf[4]; for (int i = sizeof(val) - 1; i >= 0; i--) buf[i] = (val >> 8 * i) & 0xff; f.write((char*)buf, sizeof(val)); } //based on BITMAPFILEHEADER, struct size will be off struct cfileheader { char type[2]; uint32_t size; uint32_t reserved; uint32_t offset; };
{ "domain": "codereview.stackexchange", "id": 42572, "lm_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++, image", "url": null }
c++, image //based on BITMAPINFOHEADER, struct size will be off struct cinfoheader { uint32_t struct_size; uint32_t width; uint32_t height; uint16_t planes; uint16_t bitcount; uint32_t compression; uint32_t image_size; uint32_t xpermeter; uint32_t ypermeter; uint32_t colors_used; uint32_t colors_important; };
{ "domain": "codereview.stackexchange", "id": 42572, "lm_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++, image", "url": null }
c++, image Image(const Image&) {} //lets make these inaccessible Image& operator = (Image const&) {} public: Image(); bool readfile(const char* filename); bool writefile(const char* filename); bool isopen; int width, height; int width_in_bytes; int bitcount; cfileheader fileheader; cinfoheader info; std::vector<uint32_t> palette; std::vector<uint8_t> image; uint32_t getpixel(int x, int y) { switch (bitcount) { case 1: { const int rowindex = (height - y - 1) * width_in_bytes; const uint8_t bit = (image[rowindex + x / 8] >> (7 - (x % 8))) & 1; return palette[bit]; } case 4: { const int start = (height - y - 1) * width_in_bytes; uint8_t pal = image[start + x / 2]; if (!(x % 2)) pal >>= 4; return palette[pal & 0xf]; } case 8: { //find the index of pixel at x/y //the pixel should have a value between 0 to 256 //get the color from palette const int i = (height - y - 1)* width_in_bytes + x; const uint8_t pal = image[i]; return palette[pal]; } case 24: { const int i = (height - y - 1) * width_in_bytes + x * 3; return image[i + 2] + (image[i + 1] << 8) + (image[i + 0] << 16); } case 32: { const int i = (height - y - 1) * width_in_bytes + x * 4; return image[i + 2] + (image[i + 1] << 8) + (image[i + 0] << 16); } } return 0; } }; Image::Image(): isopen{ false }, fileheader{}, info{}, bitcount{}, width{}, height{}, width_in_bytes{} { }
{ "domain": "codereview.stackexchange", "id": 42572, "lm_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++, image", "url": null }
c++, image bool Image::readfile(const char* filename) { std::ifstream fin(filename, std::ios::binary); if (!fin) { std::cout << "open failed " << filename << '\n'; return false; } fin.read(fileheader.type, 2); if (strncmp(fileheader.type, "BM", 2) != 0) return false; readint(fin, fileheader.size); readint(fin, fileheader.reserved); readint(fin, fileheader.offset); readint(fin, info.struct_size); readint(fin, info.width); readint(fin, info.height); readint(fin, info.planes); readint(fin, info.bitcount); readint(fin, info.compression); readint(fin, info.image_size); readint(fin, info.xpermeter); readint(fin, info.ypermeter); readint(fin, info.colors_used); readint(fin, info.colors_important); width = info.width; height = info.height; bitcount = info.bitcount; if (info.struct_size != 40) { printf("wrong structure size %d\n", info.struct_size); return false; } std::vector<uint16_t> bitcheck {1,4,8,24,32}; if(std::find(bitcheck.begin(), bitcheck.end(), bitcount) == bitcheck.end()) { printf("cannot handle this bitcount %d\n", bitcount); return false; } int palette_size = (bitcount > 8) ? 0 : (1 << bitcount); palette.resize(palette_size); for (auto &e : palette) { //BGRA -> ABGR uint8_t buf[4] {}; fin.read((char*)buf, 4); e = buf[2] | (buf[1] << 8) | (buf[0] << 16) | (buf[3] << 24); } if(fin.tellg() != fileheader.offset) { printf("error reading image\n"); return false; } width_in_bytes = ((width * info.bitcount + 31) / 32) * 4; image.resize(width_in_bytes * height); fin.read((char*)image.data(), image.size()); isopen = true; return true; } bool Image::writefile(const char* filename) { if (!isopen) return false; std::ofstream fout(filename, std::ios::binary); if (!fout) { std::cout << "open failed " << filename << '\n'; return false; }
{ "domain": "codereview.stackexchange", "id": 42572, "lm_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++, image", "url": null }
c++, image fout.write((char*)fileheader.type, 2); writeint(fout, fileheader.size); writeint(fout, fileheader.reserved); writeint(fout, fileheader.offset); writeint(fout, info.struct_size); writeint(fout, info.width); writeint(fout, info.height); writeint(fout, info.planes); writeint(fout, info.bitcount); writeint(fout, info.compression); writeint(fout, info.image_size); writeint(fout, info.xpermeter); writeint(fout, info.ypermeter); writeint(fout, info.colors_used); writeint(fout, info.colors_important); for (auto &e : palette) { //ABGR -> BGRA uint8_t buf[4]{}; buf[0] = (e >> 16) & 0xff; buf[1] = (e >> 8) & 0xff; buf[2] = (e >> 0) & 0xff; buf[3] = (e >> 24) & 0xff; fout.write((char*)buf, 4); } fout.write((char*)image.data(), image.size()); return true; } Usage: If image is opened successfully, we access to image (these are the pixels on the screen), palette if any, plus basic information such as width, height, and bit count. For example, img.image[index] is the pixel at that index, it has matching color based on img.palette See getpixel function for more detail. Image img; img.readfile("bitmap8bit.bmp"); if (img.isopen) for (int row = 0; row < img.height; row++) for (int col = 0; col < img.width; col++) { //drawpixel(row, col, img.getpixel(col, row)); ? } Reading 8-bit bitmap is easier than modifying it. To edit 8-bit, we may need to modify the palette color and rebuild the color palette, this code will not do that. Note that bitmap file header is always 14 bytes. The bitmap header is usually 40, but not always. This code assumes 40, otherwise it reports failure.
{ "domain": "codereview.stackexchange", "id": 42572, "lm_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++, image", "url": null }
c++ Title: How to elegantly read string with delimiters? Question: Firstly consider this code: #include <iostream> #include <set> using namespace std; int main() { const char delim = '\n'; char inp; int cnt = 0; multiset<char> m1; while (cin.get(inp) && cnt != 2) if (inp == delim) cnt++; else m1.insert(inp); multiset<char> m2; while (cin.get(inp).peek() != '\n') m2.insert(inp); ... } I wanted to read input like this: SANTACLAUS DEDMOROZ //read characters of first 2 strings in m1 SANTAMOROZDEDCLAUS //read characters of this string in m2 Code look messy. And quite hard to debug. But still I need to read somehow character by character. Of course I can do reading through strings: #include <iostream> #include <set> #include <string> using namespace std; int main() { multiset<char> m1; string inp; for (size_t i = 0; i < 2; i++) { cin >> inp; for (size_t j = 0; j < inp.size(); j++) { m1.insert(inp[j]); } } cin >> inp; multiset<char> m2; for (size_t j = 0; j < inp.size(); j++) { m2.insert(inp[j]); } ... } But still I feel somewhat bad for using extra memory. Can I achieve the elegant solution for this problem without using extra memory? Answer: refactor to avoid duplication Your instincts are good: Don't Repeat Yourself. You have identical blocks of code with only one variable changed. You should break this out into a function, making the changeable part a parameter to that function. multiset<char> m1; string inp; for (size_t i = 0; i < 2; i++) { cin >> inp; for (size_t j = 0; j < inp.size(); j++) { m1.insert(inp[j]); } }
{ "domain": "codereview.stackexchange", "id": 42573, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ In this case, you abstract out m1 as the return value, and i as the parameter. Just doing this you get: auto scan_n_lines (size_t lines) { multiset<char> m; for (size_t i = 0; lines < 2; lines++) { string inp; cin >> inp; for (size_t j = 0; j < inp.size(); j++) m.insert(inp[j]); } return m; } Now you can use this twice in your original code, rather than typing it twice. multiset<char> m1 = scan_n_lines (2); multiset<char> m2 = scan_n_lines (1); ... meanwhile Don’t write using namespace std;. You can, however, in a CPP file (not H file) or inside a function put individual using std::string; etc. (See SF.7.) Prefer using prefix ++. Process each character in the string using a ranged for loop, not a C style counting loop. There is no j and no need to subscript the string. for (auto ch : inp) m.insert(ch); But look at the class: insert can do an entire range at once. You don't even need the loop! m.insert (inp.begin(), inp.end()); So, review the documentation for the library components you use. You know that a set (or multiset) has insert as an essential operation, but do you know it has 8 different forms? Memorize the essentials of what the class does, but rely on the docs for details as you use it. Finally, the outer loop is just to repeat n times. In C++20, you can use std::ranges::iota. If it's not available as part of the compiler's library, use a different library or your own simple version. auto scan_n_lines (size_t lines) { multiset<char> m; for (auto i : std::ranges::iota(0,lines)) { string inp; cin >> inp; m.insert (inp.begin(), inp.end()); } return m; } ```
{ "domain": "codereview.stackexchange", "id": 42573, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++, c++14, template-meta-programming, polymorphism Title: One-time dynamic, many-time *almost* static type dispatch Question: Annoyed at the tension between good software design principles that require well-defined delimitations between interface and implementations, and the requirements for critical code to run fast, which demands avoid placing runtime overheads in the critical path, I've come up with a solution that I haven't seen elsewhere. The concept is to build a template structure that is initialized with a pointer to an abstract interface, which runs dynamic_cast on every possible desired implementation case, and leaving the structure ready to use with a templated apply helper that checks which implementation pointer is non-null. The design assumptions I've made are two-fold: making a couple comparisons with an integer in the stack can be slightly faster sometimes that walking to a vtable, which would pay-off if the object methods are called many times the tradeoff of bigger stack space occupied by the extra-pointers and the extra-comparisons instead of a parametrized Duff's device jump is unavoidable without compiler support of variadic parameter pack switch folds (not totally true, see final remarks) so I would like to elicit comments on the code structure, but also if my design assumptions are correct (specially 2) Enough talk, now to the code: template<typename Interface, typename Impl, int Instance> struct ImplRef { Impl* const m_ref; ImplRef(Interface* ref) : m_ref(dynamic_cast<Impl*>(ref)) {} inline int instance() const { if (nullptr == m_ref) return -1; return Instance; } template<typename Functor> decltype(std::declval<Functor>()(std::declval<Impl&>())) apply(Functor f) { return f(*m_ref); } };
{ "domain": "codereview.stackexchange", "id": 42574, "lm_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++, c++14, template-meta-programming, polymorphism", "url": null }
c++, c++14, template-meta-programming, polymorphism template <typename Interface, typename Impl0, typename...Impls> struct OpaqueImplCollector : public ImplRef<Interface, Impl0, sizeof...(Impls)>, public OpaqueImplCollector<Interface, Impls...> { using BaseImplRef = ImplRef<Interface, Impl0, sizeof...(Impls)>; using BaseImplCollector = OpaqueImplCollector<Interface, Impls...>; static constexpr int level = sizeof...(Impls); const int m_idx; //template<typename > OpaqueImplCollector(Interface* i) : BaseImplRef(i), BaseImplCollector(i), m_idx( (BaseImplRef(i).instance() > -1) ? level : BaseImplCollector(i).instance() ) {} inline int instance() const { int base_ref = BaseImplRef::instance(); if (base_ref > -1) return base_ref; return BaseImplCollector::instance(); } template<typename Functor> decltype(std::declval<Functor>()(std::declval<Interface&>())) apply(Functor f) { if (m_idx > -1) return BaseImplRef::apply(f); return BaseImplCollector::apply(f); } }; template <typename Interface, typename ImplLast> struct OpaqueImplCollector< Interface, ImplLast> : public ImplRef<Interface, ImplLast, 0> { using BaseImplRef = ImplRef<Interface, ImplLast, 0>; static constexpr int level = 0; const int m_idx; //template<typename > OpaqueImplCollector(Interface* i) : BaseImplRef(i), m_idx( (BaseImplRef(i).instance() > -1) ? level : -1 ) { //assert(m_idx > -1); } inline int instance() const { return BaseImplRef::instance(); } template<typename Functor> decltype(std::declval<Functor>()(std::declval<ImplLast&>())) apply(Functor f) { assert(m_idx > -1); return BaseImplRef::apply(f); } }; That's it. This is an example of how to use it: struct iFace { virtual int meth() = 0; };
{ "domain": "codereview.stackexchange", "id": 42574, "lm_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++, c++14, template-meta-programming, polymorphism", "url": null }
c++, c++14, template-meta-programming, polymorphism That's it. This is an example of how to use it: struct iFace { virtual int meth() = 0; }; struct Impl1 : public iFace { int m_a; inline int meth() override { return m_a; } }; struct Impl2 : public iFace { int m_a, m_b; inline int meth() override { return m_a + m_b; } }; struct PolyOp { //this is only required for inferring the return-type expected by the interface int operator()(iFace&); inline int operator()(Impl1& impl1) { return impl1.meth(); } //template impl because default, specific instances become overrides template<typename Impl> inline int operator()(Impl& impl2) { return impl2.meth() - impl2.m_b; } }; TEST(Basic, HybridPolyContainer) { Impl2 impl; std::tie(impl.m_a, impl.m_b) = std::pair{3, 2}; iFace* ref = &impl; ImplRef< iFace, Impl1, 0 > ir1(ref); ImplRef< iFace, Impl2, 0 > ir2(ref); assert(ir1.instance() == -1); assert(ir2.instance() == 0); OpaqueImplCollector< iFace, Impl2, Impl1 > implContainer(ref); assert(implContainer.m_idx == 1); PolyOp polyop; assert(implContainer.apply(polyop) == 3); // impl.m_a); Impl1 implOne; implOne.m_a = 7; ref = &implOne; OpaqueImplCollector< iFace, Impl2, Impl1 > implContainerOne(ref); assert(implContainerOne.m_idx == 0); // does not access template operator, access specific overload assert(implContainerOne.apply(polyop) == 7); };
{ "domain": "codereview.stackexchange", "id": 42574, "lm_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++, c++14, template-meta-programming, polymorphism", "url": null }
c++, c++14, template-meta-programming, polymorphism }; Notice that polyop calls can in principle be inlined by the compiler, as the implContainer is behaving as a switch function (but not as fast as a switch, as it's not a parametrized jump, but a variable sequence of comparisons) Also note that PolyOp didn't need to provide a definition for void operator()(iFace&), just the declaration suffices so that apply can infer a return type Final remarks Although lack of a switch fold expression makes life a bit harder, it's still possible to destructure several variadic specializations in order to provide switch-based apply implementations: template <typename Interface, typename ImplFirst, typename ImplLast> struct OpaqueImplCollector< Interface, ImplFirst, ImplLast> : public ImplRef<Interface, ImplLast, 0>, public ImplRef<Interface, ImplFirst, 1> { using BaseImplRef0 = ImplRef<Interface, ImplLast, 0>; using BaseImplRef1 = ImplRef<Interface, ImplFirst, 1>; static constexpr int level = 1; const int m_idx; //template<typename > OpaqueImplCollector(Interface* i) : BaseImplRef0(i), BaseImplRef1(i), m_idx( (BaseImplRef1(i).instance() > -1) ? level : BaseImplRef0(i).instance() ) {} inline int instance() const { return m_idx; } template<typename Functor> decltype(std::declval<Functor>()(std::declval<Interface&>())) apply(Functor f) { assert(m_idx > -1); switch( m_idx) { case 0: return BaseImplRef0::apply(f); case 1: return BaseImplRef1::apply(f); default: assert(m_idx > -1); } } };
{ "domain": "codereview.stackexchange", "id": 42574, "lm_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++, c++14, template-meta-programming, polymorphism", "url": null }
c++, c++14, template-meta-programming, polymorphism Answer: Use std::variant and std::visit() instead Basically, you want to turn a base pointer into a derived pointer at runtime, and you want to store that somehow in a variable. Since C++17, there's std::variant, which solves the latter problem. So what if you made a function that looks like this: template<typename Interface, typename... Impls> auto make_impl_variant(Interface* i) { std::variant<Impls*...> result; ([&]{if (Impls* i = dynamic_cast<Impls*>(base)) result = i;}(), ...); return result; } There is no apply() member function in std::variant, instead you use std::visit(), like so: Impl2 impl; iFace* ref = &impl; auto implContainer = make_impl_variant<iFace, Impl1, Impl2>(ref); PolyOp polyop; assert(std::visit(polyop, implContainer) == 3); One issue that doesn't make it a drop-in replacement for your version is that you can't easily store references inside a variant, so either you need to modify PolyOp::operator() in your code to take pointers instead of references, or create a helper function that converts the pointer to a reference before applying it to the desired functor while visiting, like so: std::visit([&](auto* i){return polyop(*i);}, implContainer); You can of course still wrap all this into a class OpaqueImplContainer if that is easier. If you can't use C++17 yet, then perhaps you can implement your own versions of std::variant and std::visit, or use an existing library implementation like Boost::Variant.
{ "domain": "codereview.stackexchange", "id": 42574, "lm_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++, c++14, template-meta-programming, polymorphism", "url": null }
algorithm, rust Title: Rabbit Searching Problem in Rust Question: This is my Rust implementation of the rabbit searching algorithm I found yesterday in this video. The problem statement is as follows. There are 100 holes in a line. A rabbit is in one of the holes. You need to catch the rabbit. However, you can only look at one hole at a time. If the rabbit is in the hole that you looked, you catch the rabbit. If the rabbit is not in the hole, the rabbit will move to an adjacent hole. The algorithm works as intended. You need to search two times. First, do a whole pass, and then do another pass but starting at index 1. However, I'm not familiar with Rust yet, so there are some awkward code snippets in my implementation. How can I improve the code according to Rust's best practices? Thanks. use rand::Rng; const N: i32 = 100; fn main() { let mut rabbit_pos: i32 = rand::thread_rng().gen_range(0..N); println!("Rabbit is at {}", rabbit_pos); let searched = search(&mut rabbit_pos); println!("Rabbit is at {}", rabbit_pos); } fn search(rabbit_pos: &mut i32) -> i32 { let mut found = false; let mut found_pos = 0; for i in 0..N { if lookup(i, rabbit_pos) { println!("Found {}", i); found = true; found_pos = i; break; } } if found { return found_pos; } for i in 1..N { if lookup(i, rabbit_pos) { println!("Found {}", i); found = true; found_pos = i; break; } } found_pos } fn lookup(n: i32, rabbit_pos: &mut i32) -> bool { println!("Searching for {}", n); if *rabbit_pos == n { return true; } else { move_rabbit(rabbit_pos); return false; } }
{ "domain": "codereview.stackexchange", "id": 42575, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, rust", "url": null }
algorithm, rust fn move_rabbit(prev: &mut i32) { let new_pos = match *prev { 0 => 1, i if i == (N-1) => N-2, _ => *prev + (rand::thread_rng().gen_range(0..2) * 2 - 1), }; println!("Rabbit moved from {} to {}", *prev, new_pos); *prev = new_pos; } Answer: In the search function, I suggest eliminating the variables found and foundpos. If lookup succeeds, simply return i. Otherwise it looks fine to me, although I have only scanned the code briefly. Maybe you could put in a call panic!("Rabbit not found"); in if the algorithm unexpectedly fails ( rabbit not found after the two search loops ). Simply returning found_pos when the algorithm failed would be a little mis-leading!
{ "domain": "codereview.stackexchange", "id": 42575, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, rust", "url": null }
python, python-3.x, web-scraping, selenium Title: Web scraping data.cdc.gov for COVID-19 Data with Selenium in Python Question: I'm attempting to scrape data.cdc.gov for their COVID-19 information on cases and deaths. The problem that I'm having is that the code seems to be very inefficient. It takes an extremely long time for the code to work. For some reason the CDC's XML file doesn't work at all, and the API is incomplete. I need all of the information about Covid-19 starting from January 22, 2020, up until now. However, the API just doesn't contain all of the information for all of those days. Please someone assist me in making this code more efficient so that I can more seamlessly extract the information that I need. from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import time options = Options() options.add_argument('--no-sandbox') url = 'https://data.cdc.gov/Case-Surveillance/United-States-COVID-19-Cases-and-Deaths-by-State-o/9mfq-cb36/data' driver = webdriver.Chrome(executable_path=r"C:\Program Files (x86)\chromedriver.exe",options=options) driver.implicitly_wait(10) driver.get(url)
{ "domain": "codereview.stackexchange", "id": 42576, "lm_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, web-scraping, selenium", "url": null }
python, python-3.x, web-scraping, selenium driver.implicitly_wait(10) driver.get(url) while True: rows = driver.find_elements_by_xpath("//div[contains(@class, 'socrata-table frozen-columns')]") covid_fin = [] for table in rows: headers = [] for head in table.find_elements_by_xpath('//*[@id="renderTypeContainer"]/div[4]/div[2]/div/div[4]/div[1]/div/table/thead/tr/th'): headers.append(head.text) for row in table.find_elements_by_xpath('//*[@id="renderTypeContainer"]/div[4]/div[2]/div/div[4]/div[1]/div/table/tbody/tr'): covid = [] for col in row.find_elements_by_xpath("./*[name()='td']"): covid.append(col.text) if covid: covid_dict = {headers[i]: covid[i] for i in range(len(headers))} covid_fin.append(covid_dict) try: WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, 'pager-button-next'))).click() time.sleep(5) except: break Answer: In my opinion, Selenium isn't the right tool for web scraping much (probably, most) of the time. It turns out that even when websites use javascript, you can usually figure out what that js is doing by using your browser's inspect network. If you open inspector (ctrl-shift-I in Chrome), then open the initial url you'll see all these requests with the preview to the right. One trick is to just click on all the requests looking at the preview until you see something that looks like the data you want. The first "data" page turns out not to have any data. If you go down a little ways, you'll find the data. Once you find the data, go back to the Headers of the inspector where you can get the URL of the data. Let's copy and paste that into a script dataurl="https://data.cdc.gov/api/id/9mfq-cb36.json?$query=select%20*%2C%20%3Aid%20limit%20100"
{ "domain": "codereview.stackexchange", "id": 42576, "lm_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, web-scraping, selenium", "url": null }
python, python-3.x, web-scraping, selenium Now, on the site, let's click Next and see what happens (well I already did that before doing the screenshots so you can see what happened next already). If you get the URLs from those requests you'll start to see a pattern... dataurl= "https://data.cdc.gov/api/id/9mfq-cb36.json?$query=select%20*%2C%20%3Aid%20limit%20100" dataurl2="https://data.cdc.gov/api/id/9mfq-cb36.json?$query=select%20*%2C%20%3Aid%20offset%20100%20limit%20100" dataurl3="https://data.cdc.gov/api/id/9mfq-cb36.json?$query=select%20*%2C%20%3Aid%20offset%20200%20limit%20100" In the first one, there is a select with some jibberish followed by a limit of 100. In the next ones, that select jibberish and the limit of 100 stayed the same by now there's an offset. Now we can just do... import pandas as pd import requests df=[] i=0 while True: if i==0: offset="" else: offset=f"%20offset%20{i}00" url=f"https://data.cdc.gov/api/id/9mfq-cb36.json?$query=select%20*%2C%20%3Aid{offset}%20limit%20100" temp=pd.read_json(requests.get(url).text) if temp.shape[0]>0: df.append(pd.read_json(requests.get(url).text)) i+=1 else: break df=pd.concat(df) On my computer, this ran in about 4min.
{ "domain": "codereview.stackexchange", "id": 42576, "lm_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, web-scraping, selenium", "url": null }
c++, chess Title: Basic chess engine Question: I'm playing around with a chess engine that I wanted it to know all the rules such as pawn promotion, en-passant, and castling. Currently, I'm using a basic Negamax for the AI but I plan to improve at a later stage. I have not spent too much effort on the interface as I plan to make it compatible with XBoard / Winboard when I'm bored enough. Any ideas to get the basics more efficient or dry? #include <array> #include <cstring> #include <iostream> #include <optional> #include <string> #include <string_view> #include <vector> // bit-util.h typedef std::uint8_t uint8; typedef std::uint64_t uint64; #ifdef _MSC_VER #define lzcnt(a) __lzcnt64(a) #define popcnt(a) __popcnt64(a) #else #define lzcnt(a) __builtin_clzl(a) #define popcnt(a) __builtin_popcountl(a) #endif constexpr uint64 one = 1ul; uint64 bitcalc(int col, int row) { return one << (col + row * 8); } bool excludes(uint64 bits, uint64 flag) { return !(bits & flag); } bool includes(uint64 bits, uint64 flag) { return bits & flag; } uint8 square(uint64 index) { return 63 - static_cast<uint8>(lzcnt(index)); } struct Cell { Cell(uint8 col, uint8 row) : col{ col } , row{ row } { } Cell(uint8 index) { col = index % 8; row = index / 8; } bool valid() { return col >= 0 && col < 8 && row >= 0 && row < 8; } bool move(int icol, int irow) { col += icol; row += irow; return valid(); } uint8 index() { return col + row * 8; } uint64 flag() { return one << index(); } uint8 col; uint8 row; }; std::optional<uint64> onboard(int col, int row) { if (col >= 0 && col < 8 && row >= 0 && row < 8) return bitcalc(col, row); return std::nullopt; } int rank(int player, int row) { return player ? 7 - row : row; } // bitboard.h
{ "domain": "codereview.stackexchange", "id": 42577, "lm_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++, chess", "url": null }
c++, chess int rank(int player, int row) { return player ? 7 - row : row; } // bitboard.h enum Piece { Pawn, Rook, Knight, Bishop, Queen, King, Max }; struct BState { bool attacks; uint64 excludes; }; class BitBoard { public: BitBoard() : rookMoves{ {-1, 0}, {1, 0}, {0, -1}, {0, 1} } , bishopMoves{ {-1, -1}, {1, -1}, {-1, 1}, {1, 1} } , knightMoves{ {-1, 2}, {1, 2} , {-1, -2} , {1, -2}, {-2, 1} , {2, 1} , {-2, -1} , {2, -1} } , queenMoves{ {-1, -1}, {0, -1} , {1, -1} , {-1, 1} , {0, 1} , {1, 1} , {-1, 0} , {1, 0} } { std::memset(state, 0, sizeof(state)); for (int s = 0; s < 2; s++) { for (int p = 0; p < Piece::Max; p++) { for (uint8 i = 0; i < 64; i++) { for (uint8 j = 0; j < 64; j++) { generate(s, s ? -1 : 1, p, i, j); } } } } } bool check(int side, int piece, uint8 src, uint8 dst, uint64 all) { BState& st = state[side][piece][src][dst]; return st.attacks && excludes(all, st.excludes); }
{ "domain": "codereview.stackexchange", "id": 42577, "lm_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++, chess", "url": null }
c++, chess private: void generate(int side, int dir, int piece, uint8 src, uint8 dst) { BState& st = state[side][piece][src][dst]; switch (piece) { case Pawn: genray(st, dir, src, dst, -1, dir, true); genray(st, dir, src, dst, 1, dir, true); break; case Rook: for (const auto& move : rookMoves) genray(st, dir, src, dst, move[0], move[1], false); break; case Knight: for (const auto& move : knightMoves) genray(st, dir, src, dst, move[0], move[1], true); break; case Bishop: for (const auto& move : bishopMoves) genray(st, dir, src, dst, move[0], move[1], false); break; case Queen: for (const auto& move : queenMoves) genray(st, dir, src, dst, move[0], move[1], false); break; case King: for (const auto& move : queenMoves) genray(st, dir, src, dst, move[0], move[1], true); break; default: break; } } void genray(BState& state, int dir, uint8 src, uint8 dst, int inccol, int incrow, bool single) { Cell csrc(src); Cell cdst(dst); if (csrc.move(inccol, incrow)) { if (csrc.index() == dst) { state.attacks = true; state.excludes = 0; } if (single) return; uint64 excludes = csrc.flag(); while (csrc.move(inccol, incrow)) { if (csrc.index() == dst) { state.attacks = true; state.excludes = excludes; break; } else { excludes |= csrc.flag(); } } } }
{ "domain": "codereview.stackexchange", "id": 42577, "lm_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++, chess", "url": null }
c++, chess private: BState state[2][Piece::Max][64][64]; public: const int knightMoves[8][2]; const int rookMoves[4][2]; const int bishopMoves[4][2]; const int queenMoves[8][2]; }; // board.h const static std::string pieces[] = { "PRNBQK", "prnbqk" }; enum Special { None, Promote, EnPassant, CastShort, CastLong, Draw, Fail }; struct Move { Move(Piece piece, uint64 src, uint64 dst, uint8 special, int score = 0) : piece{ piece } , src{ src } , dst{ dst } , special{ special } , score{ score } { } int score; uint64 src; uint64 dst; uint8 special; Piece piece; }; struct Player { uint64 prev; uint64 all; uint64 pieces[Piece::Max]; }; class Board { public: uint64 moved; uint64 all; Player players[2]; void init(std::string_view str) { std::memset(this, 0, sizeof(*this)); for (uint64 i = 0; i < str.size(); i++) { for (int p = 0; p < 2; p++) { const auto& color = pieces[p]; auto index = color.find(str[i]); if (index != std::string::npos) { uint64 bit = one << i; all |= bit; players[p].all |= bit; players[p].pieces[index] |= bit; } } } }
{ "domain": "codereview.stackexchange", "id": 42577, "lm_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++, chess", "url": null }
c++, chess void print(int depth = 0) { std::string header = " A B C D E F G H\n"; std::cout << header; for (int r = 0; r < 8; r++) { std::cout << 8 - r; char bk = r % 2; for (int c = 0; c < 8; c++) { char ch = ' '; for (int p = 0; p < 2; p++) { auto& player = players[p]; for (int i = 0; i < Piece::Max; i++) { if (player.pieces[i] & bitcalc(c, r)) ch = pieces[p][i]; } } std::cout << (bk ? "\033[0;47;30m" : "\033[0;30;107m") << ' ' << ch << ' '; bk = !bk; } std::cout << "\033[m" << 8 - r << '\n'; } std::cout << header << '\n'; }
{ "domain": "codereview.stackexchange", "id": 42577, "lm_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++, chess", "url": null }
c++, chess void apply(int player, Move move) { Player& me = players[player]; Player& op = players[!player]; moved |= move.src | move.dst; me.prev = square(move.src) + square(move.dst) * 64; switch (move.special) { case Special::Promote: removePiece(op, Piece::Max, move.dst); removePiece(me, Piece::Pawn, move.src); insertPiece(me, move.piece, move.dst); break; case Special::EnPassant: removePiece(op, Piece::Pawn, bitcalc(Cell(square(move.dst)).col, Cell(square(move.src)).row)); removePiece(me, Piece::Pawn, move.src); insertPiece(me, Piece::Pawn, move.dst); break; case Special::CastShort: removePiece(me, Piece::Rook, bitcalc(7, rank(player, 0))); insertPiece(me, Piece::Rook, bitcalc(5, rank(player, 0))); removePiece(me, Piece::King, move.src); insertPiece(me, Piece::King, move.dst); break; case Special::CastLong: removePiece(me, Piece::Rook, bitcalc(0, rank(player, 0))); insertPiece(me, Piece::Rook, bitcalc(3, rank(player, 0))); removePiece(me, Piece::King, move.src); insertPiece(me, Piece::King, move.dst); break; default: removePiece(op, Piece::Max, move.dst); removePiece(me, move.piece, move.src); insertPiece(me, move.piece, move.dst); } } int eval(Player& player) { int values[] = { 1, 5, 3, 3, 10, 200 }; int total = 0; for (int i = 0; i < Piece::Max; i++) total += static_cast<int>(popcnt(player.pieces[i])) * values[i]; return total; } private: void insertPiece(Player& player, Piece piece, uint64 bit) { all |= bit; player.all |= bit; player.pieces[piece] |= bit; }
{ "domain": "codereview.stackexchange", "id": 42577, "lm_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++, chess", "url": null }
c++, chess void changePiece(Player& player, uint64 bit, Piece from, Piece to) { player.pieces[from] &= ~bit; player.pieces[to] |= bit; } void removePiece(Player& player, Piece piece, uint64 bit) { all &= ~bit; player.all &= ~bit; if (piece == Piece::Max) { for (auto& piece : player.pieces) piece &= ~bit; } else { player.pieces[piece] &= ~bit; } } }; // AI.h class AI { public: AI(BitBoard& bitboard) : bitboard{ bitboard } { } Move move(Board& board, int player, int maxDepth) { allMoves.clear(); bestMoves.clear(); negaMax(board, player, maxDepth, 0); if (bestMoves.empty()) return Move(Piece::Max, 0, 0, Special::Draw, 0); return bestMoves[rand() % bestMoves.size()]; }
{ "domain": "codereview.stackexchange", "id": 42577, "lm_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++, chess", "url": null }
c++, chess int negaMax(Board& board, int player, int maxDepth, int depth) { int scoreMe = board.eval(board.players[player]); int scoreOp = board.eval(board.players[!player]); int max = -9999; if (depth == maxDepth) return scoreMe - scoreOp; for (int i = 0; i < Piece::Max; i++) { Piece piece = static_cast<Piece>(i); uint64 bits = board.players[player].pieces[piece]; while (bits) { uint64 src = bits & (0ul - bits); int index = square(src); Cell cell(index); switch (i) { case Piece::Pawn: movePawn(board, player, maxDepth, depth, src, cell, piece, max); break; case Piece::Rook: moveRook(board, player, maxDepth, depth, src, cell, piece, max); break; case Piece::Bishop: moveBishop(board, player, maxDepth, depth, src, cell, piece, max); break; case Piece::Knight: moveKnight(board, player, maxDepth, depth, src, cell, piece, max); break; case Piece::Queen: moveQueen(board, player, maxDepth, depth, src, cell, piece, max); break; case Piece::King: moveKing(board, player, maxDepth, depth, src, cell, piece, max); break; } bits ^= src; } } return max; }
{ "domain": "codereview.stackexchange", "id": 42577, "lm_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++, chess", "url": null }
c++, chess void recurse(Board board, int player, int maxDepth, int depth, Move move, int& max) { Board b = board; b.apply(player, move); move.score = -negaMax(b, !player, maxDepth, depth + 1); if (depth == 0) { allMoves.push_back(move); if (bestMoves.size() && bestMoves[0].score < move.score) bestMoves.clear(); if (bestMoves.empty() || bestMoves[0].score == move.score) bestMoves.push_back(move); } else { if (move.score > max) max = move.score; } } void pawnPromotion(Board board, int player, int maxDepth, int depth, uint64 src, uint64 dst, int row, Piece piece, int& max) { if (rank(player, row) == 7) { for (int p = Piece::Rook; p < Piece::King; p++) recurse(board, player, maxDepth, depth, Move((Piece)p, src, dst, Special::Promote), max); } else { recurse(board, player, maxDepth, depth, Move(piece, src, dst, 0), max); } }
{ "domain": "codereview.stackexchange", "id": 42577, "lm_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++, chess", "url": null }
c++, chess void movePawn(Board& board, int player, int maxDepth, int depth, uint64 src, Cell cell, Piece piece, int& max) { Player& opponent = board.players[!player]; int direction = player ? -1 : 1; // forward moves auto dst = onboard(cell.col, cell.row + direction * 1); if (dst != std::nullopt && excludes(board.all, *dst)) { pawnPromotion(board, player, maxDepth, depth, src, *dst, cell.row + direction * 1, piece, max); if (rank(player, cell.row) == 1) { dst = onboard(cell.col, cell.row + direction * 2); if (dst != std::nullopt && excludes(board.all, *dst)) { pawnPromotion(board, player, maxDepth, depth, src, *dst, cell.row + direction * 2, piece, max); } } } // sideways captures dst = onboard(cell.col - 1, cell.row + direction); if (dst != std::nullopt && includes(opponent.all, *dst)) { pawnPromotion(board, player, maxDepth, depth, src, *dst, cell.row + direction, piece, max); } dst = onboard(cell.col + 1, cell.row + direction); if (dst != std::nullopt && includes(opponent.all, *dst)) { pawnPromotion(board, player, maxDepth, depth, src, *dst, cell.row + direction, piece, max); } // en-passant uint8 psrc = static_cast<uint8>(opponent.prev % 64); uint8 pdst = static_cast<uint8>(opponent.prev / 64); if (opponent.pieces[Piece::Pawn] & (one << pdst)) { Cell ps(psrc); Cell pd(pdst); if (ps.row == rank(!player, 1) && pd.row == rank(!player, 3)) { if (ps.col == cell.col - 1) { dst = onboard(cell.col - 1, cell.row + direction); recurse(board, player, maxDepth, depth, Move(piece, src, *dst, Special::EnPassant), max); } if (ps.col == cell.col + 1) {
{ "domain": "codereview.stackexchange", "id": 42577, "lm_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++, chess", "url": null }
c++, chess } if (ps.col == cell.col + 1) { dst = onboard(cell.col + 1, cell.row + direction); recurse(board, player, maxDepth, depth, Move(piece, src, *dst, Special::EnPassant), max); } } } }
{ "domain": "codereview.stackexchange", "id": 42577, "lm_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++, chess", "url": null }
c++, chess void moveRook(Board& board, int player, int maxDepth, int depth, uint64 src, Cell cell, Piece piece, int& max) { for (auto move : bitboard.rookMoves) moveDir(board, player, maxDepth, depth, src, cell, move[0], move[1], false, piece, max); } void moveKnight(Board& board, int player, int maxDepth, int depth, uint64 src, Cell cell, Piece piece, int& max) { for (auto move : bitboard.knightMoves) moveDir(board, player, maxDepth, depth, src, cell, move[0], move[1], true, piece, max); } void moveBishop(Board& board, int player, int maxDepth, int depth, uint64 src, Cell cell, Piece piece, int& max) { for (auto move : bitboard.bishopMoves) moveDir(board, player, maxDepth, depth, src, cell, move[0], move[1], false, piece, max); } void moveQueen(Board& board, int player, int maxDepth, int depth, uint64 src, Cell cell, Piece piece, int& max) { for (auto move : bitboard.queenMoves) moveDir(board, player, maxDepth, depth, src, cell, move[0], move[1], false, piece, max); }
{ "domain": "codereview.stackexchange", "id": 42577, "lm_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++, chess", "url": null }
c++, chess void moveKing(Board& board, int player, int maxDepth, int depth, uint64 src, Cell cell, Piece piece, int& max) { for (auto move : bitboard.queenMoves) moveDir(board, player, maxDepth, depth, src, cell, move[0], move[1], true, piece, max); int col = cell.col; int row = cell.row; if (rank(player, row) == 0 && col == 4 && excludes(board.moved, src)) { Player& me = board.players[player]; // castling queenside if (includes(me.pieces[Piece::Rook], bitcalc(0, row)) && excludes(board.moved, bitcalc(0, row))) { if (excludes(board.all, bitcalc(1, row) | bitcalc(2, row) | bitcalc(3, row))) { if (canCastle(board, player, row, { 4, 3, 2 })) { recurse(board, player, maxDepth, depth, Move(Piece::King, src, bitcalc(col - 2, row), Special::CastLong), max); } } } // castling otherside if (includes(me.pieces[Piece::Rook], bitcalc(7, row)) && excludes(board.moved, bitcalc(7, row))) { if (excludes(board.all, bitcalc(5, row) | bitcalc(6, row))) { if (canCastle(board, player, row, { 4, 5, 6 })) { recurse(board, player, maxDepth, depth, Move(Piece::King, src, bitcalc(col + 2, row), Special::CastShort), max); } } } } }
{ "domain": "codereview.stackexchange", "id": 42577, "lm_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++, chess", "url": null }
c++, chess bool canCastle(Board& board, int player, int row, std::array<int, 3> cols) { Player& opponent = board.players[!player]; for (int p = 0; p < Piece::Max; p++) { uint64 bits = opponent.pieces[p]; while (bits) { uint64 bit = bits & (0ul - bits); uint8 src = square(bit); for (int col : cols) { if (bitboard.check(!player, p, src, Cell(col, row).index(), board.all)) return false; } bits ^= bit; } } return true; } void moveDir(Board& board, int player, int maxDepth, int depth, uint64 src, Cell cell, int colInc, int rowInc, bool single, Piece piece, int& max) { Player& me = board.players[player]; Player& opponent = board.players[!player]; while (cell.move(colInc, rowInc)) { uint64 dst = cell.flag(); if (includes(me.all, dst)) break; recurse(board, player, maxDepth, depth, Move(piece, src, dst, 0), max); if (single || includes(board.all, dst)) break; } } public: BitBoard& bitboard; std::vector<Move> bestMoves; std::vector<Move> allMoves; }; // chess.cpp class GamePlayer { public: virtual std::optional<Move> play(AI& ai, Board& board, int side) = 0; }; class PlayerHuman : public GamePlayer { public: virtual std::optional<Move> play(AI& ai, Board& board, int side) override { for (;;) { // validate ai.move(board, side, 1); for (;;) { auto src = getSquare("Select source: "); if (src == std::nullopt) return std::nullopt;
{ "domain": "codereview.stackexchange", "id": 42577, "lm_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++, chess", "url": null }
c++, chess std::string seperator = ""; bool found = false; for (auto move : ai.allMoves) { if (move.src == *src) { if (found == false) { std::cout << "Valid destinations: "; found = true; } Cell cell(square(move.dst)); std::cout << seperator << (char)('a' + cell.col) << (char)('8' - cell.row); seperator = ", "; } } if (found == false) { std::printf("No valid moves found from source.\n"); continue; } else { std::cout << '\n'; } auto dst = getSquare("Select destination: "); if (dst == std::nullopt) return std::nullopt; for (auto move : ai.allMoves) { if (move.src == *src && move.dst == *dst) { if (move.special == Special::Promote) { auto piece = selectPiece(); if (piece == std::nullopt) return std::nullopt; move.piece = *piece; } return move; } } std::cout << "Invalid move.\n"; } } }
{ "domain": "codereview.stackexchange", "id": 42577, "lm_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++, chess", "url": null }
c++, chess private: std::optional<uint64> getSquare(std::string_view prompt) { for (;;) { std::cout << prompt; std::string line; std::getline(std::cin, line); if (std::cin.bad() || std::cin.eof()) return std::nullopt; if (line.length() == 2) { Cell cell(toupper(line[0]) - 'A', '8' - line[1]); if (cell.valid()) return cell.flag(); } std::cout << "Invalid square.\n"; } } std::optional<Piece> selectPiece() { std::string prompt = "Select Piece: (R)ook, k(N)ight, (B)ishop or (Q)ueen\n"; for (;;) { std::cout << prompt; std::string line; std::getline(std::cin, line); if (std::cin.bad() || std::cin.eof()) return std::nullopt; if (line.length() == 1) { auto index = pieces[0].find(std::toupper(line[0])); if (index != std::string::npos) return static_cast<Piece>(index); } std::cout << "Invalid square.\n"; } } }; class PlayerAI : public GamePlayer { public: virtual std::optional<Move> play(AI& ai, Board& board, int side) override { std::cout << "Thinking..."; auto move = ai.move(board, side, 5); Cell src(square(move.src)); Cell dst(square(move.dst)); std::cout << '\n' << char('a' + src.col) << char('8' - src.row) << " -> " << char('a' + dst.col) << char('8' - dst.row) << "\n"; return move; } }; void playGame(GamePlayer& pl1, GamePlayer& pl0) { Board board; board.init( "RNBQKBNR" "PPPPPPPP" " " " " " " " " "pppppppp" "rnbqkbnr" ); BitBoard bitboard; AI ai(bitboard); int side = 1; for (;;) { board.print();
{ "domain": "codereview.stackexchange", "id": 42577, "lm_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++, chess", "url": null }
c++, chess BitBoard bitboard; AI ai(bitboard); int side = 1; for (;;) { board.print(); GamePlayer& player = side ? pl1 : pl0; auto move = player.play(ai, board, side); if (move == std::nullopt) return; board.apply(side, *move); if ((*move).special == Special::Draw || (*move).score < -100) { bool check = ai.move(board, !side, 1).score > 100; std::cout << (check ? "Checkmate" : "Draw"); return; } board.apply(side, *move); side = !side; } } int main() { srand(static_cast<unsigned>(time(0))); PlayerHuman human; PlayerAI comp; playGame(human, comp); } Answer: There is a lot of code, so please forgive a very cursory look. Purely chess-related problems: Castling privileges require that neither King nor Rook ever moved End-of game is not detected (mate, three-fold repetition, 50 moves rule... the player cannot even resign!) Detecting transpositions is a must. Do not waste time to analyze the same position twice. I don't understand why bestMoves.empty() results in Special::Draw. In case of a mate on the board, bestMoves is certainly empty. That said, I am not sure that Board.apply() handles Special.Draw correctly. It is very surprising that PlayerHuman needs AI. Something is wrong at the design level. AI::moveDir line is \$152\$ characters long. This is a bit too much. recurse is being called from too many places. Consider building a list of legal moves, and recurse over it. Some of your braces are at the same line with a keyword, some are at the next. Stick to an uniform style. Of course eval is not to be reviewed
{ "domain": "codereview.stackexchange", "id": 42577, "lm_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++, chess", "url": null }
powershell Title: Powershell script to check for processes on remote systems and rename/copy files
{ "domain": "codereview.stackexchange", "id": 42578, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "powershell", "url": null }
powershell Question: Processing a set of conditions with 'Continue' I found the following more readable, opposed to trying to parse out if/elseif. What are your thoughts about this? Is there a better way? What The Code Does This code is a section of a for loop that does some testing on a file on a remote system (no need to check creds). I'm using Get-Process to see if we have access to the remote system which returns all of the running processes. If that fails continue to the next host. It does more tests against a particular file and after the test is complete it performs a rename and copy. Question Most of the time I see If then elseIf and so forth, seemingly my "continue" statements are easy to follow IMO and I wanted so feedback on this style of moving to the next item (ComputerName) in the list of systems in my array. UPDATE: I have included the entire "main" section of this script which I didn't want to do because of adding potential confusion but it was asked for. In more detail: *Even more detail Copy the IRR file to a remote system based on the right conditions and keep track of the results. Reruns of script should focus on the ones not done yet. Script determines if it has been installed before and if not, installs a IRR file if IRR_Application is not running etc.. It then keeps track of which systems it installed it on (in _success and _failed files). Next time the script runs it just checks the _failed list. It will continue this until they are all done. If you are to delete the temporary _success and _failed files that keep track of the progress, it simply starts over. The good thing is that it is smart enough to not install again on other systems because there is a text file it checks for on that system and sees that it has already been done. Hence you can run it as many times as you want with no impact. Later we can run a cleanup script if we care about a single text file etc. The text file contains the date the file was updated and the file name. CODE
{ "domain": "codereview.stackexchange", "id": 42578, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "powershell", "url": null }
powershell CODE Function Main { # Main: Check that host is reachable and such, then perform a rename (because if locked don't do anything) # of the file, then copy in the new one.
{ "domain": "codereview.stackexchange", "id": 42578, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "powershell", "url": null }
powershell $Success = @() $Failed = @() # -- Read list of computers # If there is a 'failed' list file, the assumption is to focus on those, if you delete # that 'failed' file (or it's empty), the script will to default to the all hosts $PCList = @() If (Test-Path -Path $global:FailedHostsFile -PathType Leaf) { $PCList = Get-SystemsFromFile -Filename $global:FailedHostsFile } if ($PCList.Count -lt 1) { Write-Host("No Failed list found, starting a new scan from all files.") $PCList = Get-SystemsFromFile -Filename $global:AllHostsFile } #$pclist = @("pcrpdvad415-001") Write-Host("IRR UPDATE`n----------------`n[" + [string]$PCList.Count + "] Systems found from file, starting install process. `n-------------------------------") Start-Sleep -Seconds 1 ForEach ($PCName in $PCList) { # Remote host file, remote folder, renamed file name $RemoteFilePath = [string]("\\" + $PCName + "\" + $global:RemoteDropFolder + "\" + $global:ReplaceFileName) $RemoteFolderPath = [string]("\\" + $PCName + "\" + $global:RemoteDropFolder) $BackupFileName = [string]($global:ReplaceFileName + "-Backup-" + (Get-Date).tostring("yyyyMMddhhmmss")) $IRRUpdateFilePath = $RemoteFolderPath + "\"+ $global:ReplaceFileName + "_updatelog.txt" if ($global:verbose) { "-------------------" "Remote File : " + $RemoteFilePath "Remote Folder : " + $RemoteFolderPath "Backup File Name : " + $BackupFileName "IRR Status File : " + $IRRUpdateFilePath "-------------------" }
{ "domain": "codereview.stackexchange", "id": 42578, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "powershell", "url": null }
powershell # Testing Section - Reachable? Already done? Vesta Process? Folder RW? etc. If ($true) { $ProcessList = Get-Process -ComputerName $PCname -ErrorAction SilentlyContinue if ($null -eq $ProcessList) { Log -Msg "Error - Get process list from host failed, Host down? Skipping." -PCname $PCName $Failed += $PCName Continue } If (Test-Path -Path $IRRUpdateFilePath -PathType Leaf) { $text = Get-Content $IRRUpdateFilePath -Raw $text = "*Success* - IRR Already Updated - "+$text Log -Msg $text -PCname $PCName $Success += $PCName Continue } $Process = $ProcessList | Where-Object { $_.ProcessName -match "IRRApplication$" } if ($SearchPss -eq [string]($Process.ProcessName)) { Log -Msg "Error - Process is still running. Skipping." -PCname $PCName $Failed += $PCName Continue } If (-Not (Test-RemoteFolderReadWrite -Path $RemoteFolderPath)) { Log -Msg "Error - Unable to Read/Write to remote filesystem. Skipping" -PCname $PCName $Failed += $PCName Continue } if (Test-FileLock -Path $RemoteFilePath) { Log -Msg "Error - Lock on remote file. Skipping." -PCname $PCName $Failed += $PCName Continue } } # Perform - File Replacement Steps -- if ($true) { Rename-Item -Path $RemoteFilePath -NewName $BackupFileName -Force if (Test-Path -Path $RemoteFolderPath+"\"+$BackupFileName -PathType Leaf) { Log -Msg "Error - Unable to move file to backup." -PCname $PCName $Failed += $PCName Continue }
{ "domain": "codereview.stackexchange", "id": 42578, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "powershell", "url": null }
powershell $Failed += $PCName Continue } Copy-Item -Path $global:NewReplacementFile -Destination $RemoteFilePath if (Test-Path -Path $RemoteFilePath -PathType Leaf) { [string]("FILE: "+$global:ReplaceFileName+" UPDATED (VIA SCRIPT) : " + (Get-Date).tostring("MM-dd-yyyy HH:mm:ss")) | Out-File $IRRUpdateFilePath if (Test-Path -Path $IRRUpdateFilePath -PathType Leaf) { Log -Msg "*Success* - Copy success, File has been installed on host." -PCname $PCName $Success += $PCName Continue } Else { Log -Msg "Error - Copy Failed." -PCname $PCName $Failed += $PCName Continue } } } }
{ "domain": "codereview.stackexchange", "id": 42578, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "powershell", "url": null }
powershell # - Tally Winners and Losers $Success | Out-File $global:SuccessHostsFile -Append Get-Content $global:SuccessHostsFile | Sort-Object -Unique | Set-Content $global:SuccessHostsFile $Failed | Out-File $global:FailedHostsFile "Failed : ["+$Failed.Count+"]" "Completed : ["+$Success.Count+"]" "-------------------" "Total Completed : [" + [string]((Get-Content $global:SuccessHostsFile).Count) + "]" } Answer: In a high level language one could write it even more terse and save a bit on repetitive code. Gramatical ... and-then ... and-then .... Collecting $PCName into $Failed as result. Parametrising with task step and log message. But we have PowerShell, and as such the code above is nice enough. The style reminds of if (...) { ...; return; } and the continue ensures that you need not read all remaining code to see whether an else was forgotten. So yes, an acceptable style with a readability advantage over else if chaining. But not that much better than else if chaining to forbid the alternative. But in PowerShell you can define functions for every step: Its name can describe the step in human readable wording. You can test the function isolated. (Unit tests!) With so many cases testing every branch of the control flow is tiresome. The loop becomes terser, a couple of lines. DRY: don't repeat yourself. Put some effort in high level functions & constructs. Maybe it is at least as good. Requested pseudo-code I have to admit not having programmed in PowerShell, and it has many features like result tuples (which can be used here). My attempt at coding shows one thing: it is ugly! Maybe someone with actual experience can brew a better solution. The first schematic attempt would be an expression with alternatives: GetProcessOnComputer -or TestPath($IRRUpdateFilePath) -or SearchIRRApplication -or CannotRemoteFolderReadWrite($RemoteFolderPath) -or TestFileLock($RemoteFilePath)
{ "domain": "codereview.stackexchange", "id": 42578, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "powershell", "url": null }
powershell The couple of in-/output parameters ($Failed, $Success, $PCname and of course true/false continuing) make it awkward. In OO one might use fields. Here you could use an array of functions typed with the correct parameters, to be called, which you then walk through, doing a call and then continue or stop when the boolean result is true. In the following () -> {...} stands for an anonymous function. [StepFunction] $StepFunctions = { () -> GetProcessOnComputer, () -> TestPath($IRRUpdateFilePath), () -> SearchIRRApplication, () -> CannotRemoteFolderReadWrite($RemoteFolderPath), () -> TestFileLock($RemoteFilePath), }; A high level utility function would be nice: function Step($ActionFunc, $TestFunc, $LogMsgFunc, $FailSuccFunc) { $r = $ActionFunc(); if ($TestFunc())) { Log -Msg $LogMsgFunc; $FailSuccFunc() += $Context.PCname; } } Then an actual step would look like: function GetProcessOnComputer($Context) { $ProcessList = Step( () -> {Get-Process -ComputerName $Context.PCname -ErrorAction SilentlyContinue; $ProcessList}, () -> {$null -eq $ProcessList}, () -> {"Error - Get process list from host failed, Host down? Skipping." -PCname $Context.$PCName}, () -> {$Context.$Failed}); In functional programming this would be okay, but here it might be a disappointment.
{ "domain": "codereview.stackexchange", "id": 42578, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "powershell", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 Title: Manhattan distance calculation between two images in C++ Question: This is a follow-up question for Two dimensional gaussian image generator in C++ and Image pixelwise operation function with multiple inputs in C++. For learning C++20 and researching purposes, I am attempting to implement a function manhattan_distance for calculating Manhattan distance between two images input. The foumula of Manhattan distance calculation is as below. Given two two-dimensional inputs X1 and X2 with size N1 x N2. The Manhattan distance of X1 and X2 is defined as $$ \begin{split} D_{Manhattan}(X_{1}, X_{2}) & = \left\|X_{1} - X_{2}\right\|_{1} \\ & = \sum_{k_{1} = 1}^{N_{1}} \sum_{k_{2} = 1}^{N_{2}} |{( X_{1}(k_{1}, k_{2}) - X_{2}(k_{1}, k_{2}) )}| \end{split} $$ The experimental implementation Image template class implementation (image.h): /* Developed by Jimmy Hu */ #ifndef Image_H #define Image_H #include <algorithm> #include <array> #include <cassert> #include <chrono> #include <complex> #include <concepts> #include <fstream> #include <functional> #include <iostream> #include <iterator> #include <list> #include <numeric> #include <string> #include <type_traits> #include <variant> #include <vector> namespace TinyDIP { template <typename ElementT> class Image { public: Image() = default; Image(const std::size_t width, const std::size_t height): width(width), height(height), image_data(width * height) { } Image(const std::size_t width, const std::size_t height, const ElementT initVal): width(width), height(height), image_data(width * height, initVal) {} Image(const std::vector<ElementT>& input, std::size_t newWidth, std::size_t newHeight): width(newWidth), height(newHeight) { assert(input.size() == newWidth * newHeight); this->image_data = input; // Deep copy }
{ "domain": "codereview.stackexchange", "id": 42579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 Image(const std::vector<std::vector<ElementT>>& input) { this->height = input.size(); this->width = input[0].size(); for (auto& rows : input) { this->image_data.insert(this->image_data.end(), std::begin(input), std::end(input)); // flatten } return; } constexpr ElementT& at(const unsigned int x, const unsigned int y) { checkBoundary(x, y); return this->image_data[y * width + x]; } constexpr ElementT const& at(const unsigned int x, const unsigned int y) const { checkBoundary(x, y); return this->image_data[y * width + x]; } constexpr std::size_t getWidth() const { return this->width; } constexpr std::size_t getHeight() const { return this->height; } constexpr auto getSize() { return std::make_tuple(this->width, this->height); } std::vector<ElementT> const& getImageData() const { return this->image_data; } // expose the internal data void print(std::string separator = "\t", std::ostream& os = std::cout) const { for (std::size_t y = 0; y < this->height; ++y) { for (std::size_t x = 0; x < this->width; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +this->at(x, y) << separator; } os << "\n"; } os << "\n"; return; }
{ "domain": "codereview.stackexchange", "id": 42579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 // Enable this function if ElementT = RGB void print(std::string separator = "\t", std::ostream& os = std::cout) const requires(std::same_as<ElementT, RGB>) { for (std::size_t y = 0; y < this->height; ++y) { for (std::size_t x = 0; x < this->width; ++x) { os << "( "; for (std::size_t channel_index = 0; channel_index < 3; ++channel_index) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +this->at(x, y).channels[channel_index] << separator; } os << ")" << separator; } os << "\n"; } os << "\n"; return; } friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs) { const std::string separator = "\t"; for (std::size_t y = 0; y < rhs.height; ++y) { for (std::size_t x = 0; x < rhs.width; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +rhs.at(x, y) << separator; } os << "\n"; } os << "\n"; return os; } Image<ElementT>& operator+=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(), image_data.begin(), std::plus<>{}); return *this; }
{ "domain": "codereview.stackexchange", "id": 42579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 Image<ElementT>& operator-=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(), image_data.begin(), std::minus<>{}); return *this; } Image<ElementT>& operator*=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(), image_data.begin(), std::multiplies<>{}); return *this; } Image<ElementT>& operator/=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(), image_data.begin(), std::divides<>{}); return *this; } bool operator==(const Image<ElementT>& rhs) const { /* do actual comparison */ if (rhs.width != this->width || rhs.height != this->height) { return false; } return rhs.image_data == this->image_data; } bool operator!=(const Image<ElementT>& rhs) const { return !(this == rhs); } Image<ElementT>& operator=(Image<ElementT> const& input) = default; // Copy Assign Image<ElementT>& operator=(Image<ElementT>&& other) = default; // Move Assign Image(const Image<ElementT> &input) = default; // Copy Constructor Image(Image<ElementT> &&input) = default; // Move Constructor private: std::size_t width; std::size_t height; std::vector<ElementT> image_data;
{ "domain": "codereview.stackexchange", "id": 42579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 void checkBoundary(const size_t x, const size_t y) const { assert(x < width); assert(y < height); } }; } #endif manhattan_distance template function implementation: template<TinyDIP::arithmetic ElementT = double> constexpr static ElementT manhattan_distance(const Image<ElementT>& input1, const Image<ElementT>& input2) { is_size_same(input1, input2); return TinyDIP::recursive_reduce(TinyDIP::difference(input1, input2).getImageData(), ElementT{}); } difference template function implementation: template<TinyDIP::arithmetic ElementT = double> constexpr static auto difference(const Image<ElementT>& input1, const Image<ElementT>& input2) { return TinyDIP::abs(TinyDIP::subtract(input1, input2)); } abs template function implementation: template<TinyDIP::arithmetic ElementT = double> constexpr static auto abs(const Image<ElementT>& input) { return TinyDIP::pixelwiseOperation([](auto&& element) { return std::abs(element); }, input); } subtract template function implementation: template<class InputT> constexpr static Image<InputT> subtract(const Image<InputT>& input1, const Image<InputT>& input2) { is_size_same(input1, input2); return TinyDIP::pixelwiseOperation(std::minus<>{}, input1, input2); }
{ "domain": "codereview.stackexchange", "id": 42579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 template<class InputT = RGB> requires (std::same_as<InputT, RGB>) constexpr static Image<InputT> subtract(const Image<InputT>& input1, const Image<InputT>& input2) { is_size_same(input1, input2); Image<InputT> output(input1.getWidth(), input1.getHeight()); for (std::size_t y = 0; y < input1.getHeight(); ++y) { for (std::size_t x = 0; x < input1.getWidth(); ++x) { for(std::size_t channel_index = 0; channel_index < 3; ++channel_index) { output.at(x, y).channels[channel_index] = std::clamp( input1.at(x, y).channels[channel_index] - input2.at(x, y).channels[channel_index], 0, 255); } } } return output; } pixelwiseOperation template function implementation: template<typename Op, class InputT, class... Args, std::size_t unwrap_level = 1> constexpr static auto pixelwiseOperation(Op op, const Image<InputT>& input1, const Args&... inputs) { auto output = TinyDIP::Image( recursive_transform<unwrap_level>( [&](auto&& element1, auto&&... elements) { return op(element1, elements...); }, (input1.getImageData()), (inputs.getImageData())...), input1.getWidth(), input1.getHeight()); return output; } template<class ExPo, typename Op, class InputT, std::size_t unwrap_level = 1> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) constexpr static auto pixelwiseOperation(ExPo execution_policy, Op op, const Image<InputT>& input1) { auto output = TinyDIP::Image( recursive_transform<unwrap_level>( execution_policy, [&](auto&& element1) { return op(element1); }, (input1.getImageData())), input1.getWidth(), input1.getHeight()); return output; }
{ "domain": "codereview.stackexchange", "id": 42579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 Full Testing Code Tests for manhattan_distance function: #include <algorithm> #include <array> #include <cassert> #include <cmath> #include <concepts> #include <execution> #include <fstream> #include <functional> #include <iostream> #include <iterator> #include <numeric> #include <ranges> #include <string> #include <type_traits> #include <utility> #include <vector> using BYTE = unsigned char; struct RGB { BYTE channels[3]; }; using GrayScale = BYTE; namespace TinyDIP { #define is_size_same(x, y) {assert(x.getWidth() == y.getWidth()); assert(x.getHeight() == y.getHeight());} // Reference: https://stackoverflow.com/a/58067611/6667035 template <typename T> concept arithmetic = std::is_arithmetic_v<T>; // recursive_depth function implementation template<typename T> constexpr std::size_t recursive_depth() { return 0; } template<std::ranges::input_range Range> constexpr std::size_t recursive_depth() { return recursive_depth<std::ranges::range_value_t<Range>>() + 1; } // recursive_reduce implementation // Reference: https://codereview.stackexchange.com/a/251310/231235 template<class T, class ValueType, class Function = std::plus<ValueType>> constexpr auto recursive_reduce(const T& input, ValueType init, const Function& f) { return f(init, input); } template<std::ranges::range Container, class ValueType, class Function = std::plus<ValueType>> constexpr auto recursive_reduce(const Container& input, ValueType init, const Function& f = std::plus<ValueType>()) { for (const auto& element : input) { auto result = recursive_reduce(element, ValueType{}, f); init = f(init, result); } return init; } // recursive_invoke_result_t implementation template<std::size_t, typename, typename> struct recursive_invoke_result { };
{ "domain": "codereview.stackexchange", "id": 42579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 template<typename T, typename F> struct recursive_invoke_result<0, F, T> { using type = std::invoke_result_t<F, T>; }; template<std::size_t unwrap_level, typename F, template<typename...> typename Container, typename... Ts> requires (std::ranges::input_range<Container<Ts...>> && requires { typename recursive_invoke_result<unwrap_level - 1, F, std::ranges::range_value_t<Container<Ts...>>>::type; }) struct recursive_invoke_result<unwrap_level, F, Container<Ts...>> { using type = Container<typename recursive_invoke_result<unwrap_level - 1, F, std::ranges::range_value_t<Container<Ts...>>>::type>; }; template<std::size_t unwrap_level, typename F, typename T> using recursive_invoke_result_t = typename recursive_invoke_result<unwrap_level, F, T>::type; // recursive_variadic_invoke_result_t implementation template<std::size_t, typename, typename, typename...> struct recursive_variadic_invoke_result { }; template<typename F, class...Ts1, template<class...>class Container1, typename... Ts> struct recursive_variadic_invoke_result<1, F, Container1<Ts1...>, Ts...> { using type = Container1<std::invoke_result_t<F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>>; };
{ "domain": "codereview.stackexchange", "id": 42579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 template<std::size_t unwrap_level, typename F, class...Ts1, template<class...>class Container1, typename... Ts> requires ( std::ranges::input_range<Container1<Ts1...>> && requires { typename recursive_variadic_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges struct recursive_variadic_invoke_result<unwrap_level, F, Container1<Ts1...>, Ts...> { using type = Container1< typename recursive_variadic_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>... >::type>; }; template<std::size_t unwrap_level, typename F, typename T1, typename... Ts> using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type; template<typename OutputIt, typename NAryOperation, typename InputIt, typename... InputIts> OutputIt transform(OutputIt d_first, NAryOperation op, InputIt first, InputIt last, InputIts... rest) { while (first != last) { *d_first++ = op(*first++, (*rest++)...); } return d_first; }
{ "domain": "codereview.stackexchange", "id": 42579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 // recursive_transform for the multiple parameters cases (the version with unwrap_level) template<std::size_t unwrap_level = 1, class F, class Arg1, class... Args> constexpr auto recursive_transform(const F& f, const Arg1& arg1, const Args&... args) { if constexpr (unwrap_level > 0) { static_assert(unwrap_level <= recursive_depth<Arg1>(), "unwrap level higher than recursion depth of input"); recursive_variadic_invoke_result_t<unwrap_level, F, Arg1, Args...> output{}; transform( std::inserter(output, std::ranges::end(output)), [&f](auto&& element1, auto&&... elements) { return recursive_transform<unwrap_level - 1>(f, element1, elements...); }, std::ranges::cbegin(arg1), std::ranges::cend(arg1), std::ranges::cbegin(args)... ); return output; } else { return f(arg1, args...); } } template <typename ElementT> class Image { public: Image() = default; Image(const std::size_t width, const std::size_t height): width(width), height(height), image_data(width * height) { } Image(const std::size_t width, const std::size_t height, const ElementT initVal): width(width), height(height), image_data(width * height, initVal) {} Image(const std::vector<ElementT>& input, std::size_t newWidth, std::size_t newHeight): width(newWidth), height(newHeight) { assert(input.size() == newWidth * newHeight); this->image_data = input; // Deep copy }
{ "domain": "codereview.stackexchange", "id": 42579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 Image(const std::vector<std::vector<ElementT>>& input) { this->height = input.size(); this->width = input[0].size(); for (auto& rows : input) { this->image_data.insert(this->image_data.end(), std::begin(input), std::end(input)); // flatten } return; } constexpr ElementT& at(const unsigned int x, const unsigned int y) { checkBoundary(x, y); return this->image_data[y * width + x]; } constexpr ElementT const& at(const unsigned int x, const unsigned int y) const { checkBoundary(x, y); return this->image_data[y * width + x]; } constexpr std::size_t getWidth() const { return this->width; } constexpr std::size_t getHeight() const { return this->height; } constexpr auto getSize() { return std::make_tuple(this->width, this->height); } std::vector<ElementT> const& getImageData() const { return this->image_data; } // expose the internal data void print(std::string separator = "\t", std::ostream& os = std::cout) const { for (std::size_t y = 0; y < this->height; ++y) { for (std::size_t x = 0; x < this->width; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +this->at(x, y) << separator; } os << "\n"; } os << "\n"; return; }
{ "domain": "codereview.stackexchange", "id": 42579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 // Enable this function if ElementT = RGB void print(std::string separator = "\t", std::ostream& os = std::cout) const requires(std::same_as<ElementT, RGB>) { for (std::size_t y = 0; y < this->height; ++y) { for (std::size_t x = 0; x < this->width; ++x) { os << "( "; for (std::size_t channel_index = 0; channel_index < 3; ++channel_index) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +this->at(x, y).channels[channel_index] << separator; } os << ")" << separator; } os << "\n"; } os << "\n"; return; } friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs) { const std::string separator = "\t"; for (std::size_t y = 0; y < rhs.height; ++y) { for (std::size_t x = 0; x < rhs.width; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +rhs.at(x, y) << separator; } os << "\n"; } os << "\n"; return os; } Image<ElementT>& operator+=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(), image_data.begin(), std::plus<>{}); return *this; }
{ "domain": "codereview.stackexchange", "id": 42579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 Image<ElementT>& operator-=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(), image_data.begin(), std::minus<>{}); return *this; } Image<ElementT>& operator*=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(), image_data.begin(), std::multiplies<>{}); return *this; } Image<ElementT>& operator/=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(), image_data.begin(), std::divides<>{}); return *this; } bool operator==(const Image<ElementT>& rhs) const { /* do actual comparison */ if (rhs.width != this->width || rhs.height != this->height) { return false; } return rhs.image_data == this->image_data; } bool operator!=(const Image<ElementT>& rhs) const { return !(this == rhs); } Image<ElementT>& operator=(Image<ElementT> const& input) = default; // Copy Assign Image<ElementT>& operator=(Image<ElementT>&& other) = default; // Move Assign Image(const Image<ElementT> &input) = default; // Copy Constructor Image(Image<ElementT> &&input) = default; // Move Constructor private: std::size_t width; std::size_t height; std::vector<ElementT> image_data;
{ "domain": "codereview.stackexchange", "id": 42579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 void checkBoundary(const size_t x, const size_t y) const { assert(x < width); assert(y < height); } }; template<typename Op, class InputT, class... Args, std::size_t unwrap_level = 1> constexpr static auto pixelwiseOperation(Op op, const Image<InputT>& input1, const Args&... inputs) { auto output = TinyDIP::Image( recursive_transform<unwrap_level>( [&](auto&& element1, auto&&... elements) { return op(element1, elements...); }, (input1.getImageData()), (inputs.getImageData())...), input1.getWidth(), input1.getHeight()); return output; } template<class ExPo, typename Op, class InputT, std::size_t unwrap_level = 1> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) constexpr static auto pixelwiseOperation(ExPo execution_policy, Op op, const Image<InputT>& input1) { auto output = TinyDIP::Image( recursive_transform<unwrap_level>( execution_policy, [&](auto&& element1) { return op(element1); }, (input1.getImageData())), input1.getWidth(), input1.getHeight()); return output; } template<class InputT> constexpr static Image<InputT> subtract(const Image<InputT>& input1, const Image<InputT>& input2) { is_size_same(input1, input2); return TinyDIP::pixelwiseOperation(std::minus<>{}, input1, input2); }
{ "domain": "codereview.stackexchange", "id": 42579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 template<class InputT = RGB> requires (std::same_as<InputT, RGB>) constexpr static Image<InputT> subtract(const Image<InputT>& input1, const Image<InputT>& input2) { is_size_same(input1, input2); Image<InputT> output(input1.getWidth(), input1.getHeight()); for (std::size_t y = 0; y < input1.getHeight(); ++y) { for (std::size_t x = 0; x < input1.getWidth(); ++x) { for(std::size_t channel_index = 0; channel_index < 3; ++channel_index) { output.at(x, y).channels[channel_index] = std::clamp( input1.at(x, y).channels[channel_index] - input2.at(x, y).channels[channel_index], 0, 255); } } } return output; } template<TinyDIP::arithmetic ElementT = double> constexpr static auto abs(const Image<ElementT>& input) { return TinyDIP::pixelwiseOperation([](auto&& element) { return std::abs(element); }, input); } template<TinyDIP::arithmetic ElementT = double> constexpr static auto difference(const Image<ElementT>& input1, const Image<ElementT>& input2) { return TinyDIP::abs(TinyDIP::subtract(input1, input2)); } template<TinyDIP::arithmetic ElementT = double> constexpr static ElementT manhattan_distance(const Image<ElementT>& input1, const Image<ElementT>& input2) { is_size_same(input1, input2); return TinyDIP::recursive_reduce(TinyDIP::difference(input1, input2).getImageData(), ElementT{}); } }
{ "domain": "codereview.stackexchange", "id": 42579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 template<class T> void manhattanDistanceTest() { std::size_t N1 = 10, N2 = 10; TinyDIP::Image<T> test_input(N1, N2); for (std::size_t y = 1; y <= N2; y++) { for (std::size_t x = 1; x <= N1; x++) { test_input.at(y - 1, x - 1) = x * 10 + y & 1; } } T expected = 0; auto actual = TinyDIP::manhattan_distance(test_input, test_input); assert(actual == expected); auto test_input2 = test_input; test_input2.at(1, 1) = test_input2.at(1, 1) + 1; expected = 1; actual = TinyDIP::manhattan_distance(test_input, test_input2); std::string message = "expected: " + std::to_string(expected) + ",\tactual:" + std::to_string(actual) + '\n'; std::cout << message; assert(actual == expected); return; } int main() { manhattanDistanceTest<int>(); manhattanDistanceTest<long>(); manhattanDistanceTest<float>(); manhattanDistanceTest<double>(); return 0; } The output of the testing code above: expected: 1, actual:1 expected: 1, actual:1 expected: 1.000000, actual:1.000000 expected: 1.000000, actual:1.000000 A Godbolt link is here. TinyDIP on GitHub All suggestions are welcome. The summary information: Which question it is a follow-up to? Two dimensional gaussian image generator in C++ and Image pixelwise operation function with multiple inputs in C++ What changes has been made in the code since last question? The implementation of manhattan_distance function is the main idea here. Why a new review is being asked for? If there is any possible improvement, please let me know.
{ "domain": "codereview.stackexchange", "id": 42579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 Answer: It's nice to see some of the code you've posted previously at Code Review come together. Unnecessary use of this-> You almost never need to write this-> in C++. I would omit it if possible. An exception to the rule would be in the implementation of binary operators, where it's more clear and symmetric to write something like return this->value == rhs.value. Unnecessary use of TinyDIP:: Inside namespace TinyDIP you don't need to use the prefix TinyDIP::. I would remove it, since if you ever want to change the name of the namespace, you then only have to do it in one line. Consider using std::span Since you tagged the question C++20, consider using std::span for things like the argument to the constructors of TinyDIP::Image. That way, the caller can have the image constructed from data that is either in a std::vector, std::array or anything else that has the elements sequentially in memory. Incorrect constructor for vectors of vectors In the constructor of TinyDIP::Image that takes a vector of vectors as an argument, you have a for-loop that has an iteration variable rows, but you never use that inside the loop. Unnecessary wrapping of functions In pixelwiseOperation(), you have the function op that you want to apply to all elements of the images. However, you wrap this inside a lambda before passing it to recursive_transform(). But the wrapper doesn't do anything, it just in turn calls op. So why not pass op directly? See below for an example. Simplify variadic templates
{ "domain": "codereview.stackexchange", "id": 42579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, reinventing-the-wheel, template, c++20", "url": null }