body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I am new to writing unit tests and i am facing some difficult writing unit tests for this class.
I am using Xunit and moq.</p>
<pre><code>public class WriteFileOutput: IWriteFileOutput
{
public string File { get; set; }
public WriteFileOutput(string fileName)
{
File = fileName;
}
public void writeFile(List<CustomerDistanceRecord> invitees)
{
var result = JsonConvert.SerializeObject(invitees, Formatting.Indented);
if (System.IO.File.Exists(File))
{
System.IO.File.Delete(File);
using(var tw = new StreamWriter(File, true))
{
tw.WriteLine(result.ToString());
tw.Close();
}
}
else if (!System.IO.File.Exists(File))
{
using(var tw = new StreamWriter(File, true))
{
tw.WriteLine(result.ToString());
tw.Close();
}
}
}
}
</code></pre>
<p>The code below tests that the writefileoutput writes out a file. I am not sure if this is a good unit test and I was wondering if someone could show me a better way of testing it class. Also I am not sure it deleting the file in the constructor before it is called is a good idea either. Thanks for the help.</p>
<pre><code> private readonly string _path = "../../../TestOutput/CustomerRecords.json";
public WriteFileTests()
{
if (File.Exists(_path))
{
File.Delete(_path);
}
}
[Fact]
public void WriteFileOuput_should_be_called()
{
var fileWriteFileOutput = new WriteFileOutput($"{_path}");
fileWriteFileOutput.writeFile(It.IsAny<List<CustomerDistanceRecord>>());
Assert.True(File.Exists($"{_path}"));
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T23:01:54.563",
"Id": "478649",
"Score": "1",
"body": "IMHO I don't see the point of testing built-in functionality. If you can't trust the framework..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T00:00:50.883",
"Id": "478651",
"Score": "0",
"body": "This is an integration test that is targeting implementation concerns. the subject class is also tightly coupled to implementation details."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T09:57:54.947",
"Id": "478667",
"Score": "0",
"body": "So you are saying it is tighly coupled . How do I make it loosely coupled. Have a method that checks if the file exists and return a bool ?"
}
] |
[
{
"body": "<p>IMHO there is nothing in this class that requires integration testing. At most you should be able to mock it, but all of its functionality is calling methods that are presented by the framework (or by a NuGet package, e.g. the JSON serialization). If you feel the need to test those, then why not write a test to check that the return value of some method that returns a string is actually a string and not some other type of object?</p>\n<p>You could argue that perhaps it might fail to create a file because it needs to do so on a share and that share is inaccessible, but then it is perfectly possible that this happens on production and not a single integration test will catch it. That's why exceptions exist and logging etc.</p>\n<p>And that's where your code really fails: at no point do you apply a <code>try...catch</code> and do you log any possible IO exceptions. Sure, maybe your exception will bubble up and get caught elsewhere and reported, but you need to be sure about that. For instance: it is entirely possible an existing file cannot be deleted because another process has it locked.</p>\n<p>Perhaps you should catch any IO exceptions here and return a bool to report back whether the file was written without issues (if you care about that, if other code depends on the file existing,...).</p>\n<hr />\n<p>Your <code>WriteFileOutput</code> class is also pretty bad in other ways. Its name sounds like a method and is fairly undescriptive anyway. Moreover, you've obviously copy-pasted code instead of thinking through its logic. This does exactly the same while using far less lines and has no duplication:</p>\n<pre><code> if (System.IO.File.Exists(File))\n {\n System.IO.File.Delete(File);\n }\n\n using(var tw = new StreamWriter(File, true))\n {\n tw.WriteLine(result.ToString());\n tw.Close();\n }\n</code></pre>\n<hr />\n<p>Some quick remarks:</p>\n<ul>\n<li><p>What is even the point of <code>else if (!System.IO.File.Exists(File))</code>? What else could the <code>else</code> to <code>if (System.IO.File.Exists(File))</code> even be?</p>\n</li>\n<li><p><code>public void writeFile</code> doesn't follow the standards WRT naming (methods should be PascalCase).</p>\n</li>\n<li><p>Why is this public: <code>public string File { get; set; }</code>? Why can it be set from outside?</p>\n</li>\n<li><p>Both <code>File</code> and <code>fileName</code> are incorrect names. You're clearly passing a path to a file, not the name of a file (and "File" is even less descriptive).</p>\n</li>\n<li><p><code>result</code> is too generic a name.</p>\n</li>\n<li><p>Are you saving other objects in much the same way as <code>List<CustomerDistanceRecord> invitees</code>? If so, do you have a specialized class for each of those? Because that seems overkill to me when the logic of <code>writeFile</code> (except for <code>var result = JsonConvert.SerializeObject(invitees, Formatting.Indented);</code>) can easily be reused.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T13:21:29.837",
"Id": "478816",
"Score": "0",
"body": "Thanks for the comments.\nThe reason why I wanted to test it is because I want high code coverage. \nI was using public string File {get;set} because i was setting the value using DI property injection.\nI changed the logic of the code to have a datetimestamp in it so that I dont need to delete the file."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T10:58:10.493",
"Id": "243853",
"ParentId": "243822",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "243853",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T16:11:17.090",
"Id": "243822",
"Score": "4",
"Tags": [
"c#",
"xunit"
],
"Title": "c# writing tests for WriteFileOuput"
}
|
243822
|
<p>I've created a method that groups <code>Item</code> entities below based on their <code>Value</code> property. The idea is to produce groups that also includes possible "edge duplicates", i.e.</p>
<pre><code>[{ Value: 9 }, { Value: 10 }, { Value: 11 }]
</code></pre>
<p>With <code>rangeSize</code> set to <code>10</code> yields two groups:</p>
<pre><code>[ [{ Value: 9 }, { Value: 10 }], [{ Value: 10 }, { Value: 11 }] ]
</code></pre>
<pre><code>public IEnumerable<IEnumerable<DTO.Item>> GroupByValueRange(int rangeSize)
{
var items = _itemRepository.GetAll().ToList();
var steps = Math.Ceiling(items.Max(p => p.Value) / rangeSize);
var groups = new List<IEnumerable<DTO.Item>>();
for (var i = 1; i <= steps; i++)
{
var max = i * rangeSize;
var min = (i - 1) * rangeSize;
var currentGroup = items.Where(p => p.Value >= min && p.Value <= max);
groups.Add(currentGroup.Select(p => _mapper.Map<DTO.Item>(p)));
}
return groups;
}
</code></pre>
<p>So the idea is to create groups with values like <code>0-10, 10-20, 20-30</code> etc...</p>
|
[] |
[
{
"body": "<p>There is a room for improvement:</p>\n<ol>\n<li><code>var items = _itemRepository.GetAll().ToList();</code>: Try to separate methods based on their responsibilities. Data retrieval and data processing should be not be in the same method.</li>\n<li>List is treated as IEnumerable: List's <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.enumerator?view=netcore-3.1\" rel=\"nofollow noreferrer\">Enumerator is a struct</a> but because you are accessing via the interface an implicit hidden boxing is happening unnecessarily. <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.enumerator?view=netcore-3.1\" rel=\"nofollow noreferrer\">Further details</a></li>\n<li><code>List<IEnumerable<T>></code> and <code>IEnumerable<IEnumerable<T>></code>: IEnumerable is a forward only iterator. This enables you construct the elements one-by-one (using <code>yield return</code>) so you don't have to compute all values upfront (into the <code>groups</code>) and then return it as an iterator of iterators.</li>\n<li>Depending on the size of the source an <strong>ascending ordering</strong> and the use of the <code>ArraySegment</code> can cause significant performance improvement.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T15:19:16.353",
"Id": "243924",
"ParentId": "243826",
"Score": "2"
}
},
{
"body": "<h3>Can there be empty groups?</h3>\n<p>If you pass in a <code>rangeSize</code> of <code>5</code>, your current code will have an empty group. Is this desired?</p>\n<h3>Iterating over entire collection for each group</h3>\n<p>In addition to <a href=\"https://codereview.stackexchange.com/a/243924/20416\">Peter Csala's recommendations</a>, there is a possible performance issue here: <strong>you are iterating over the entire source for each group</strong>. The delegate passed to <code>Where</code> must be evaluated against all the <code>items</code>, to determine the contents of each group.</p>\n<pre><code>for (var i = 1; i <= steps; i++)\n{\n ...\n var currentGroup = items.Where(p => p.Value >= min && p.Value <= max);\n groups.Add(currentGroup.Select(p => _mapper.Map<DTO.Item>(p)));\n}\n</code></pre>\n<p>If you have few <code>items</code>, or only a small number of groups, this might not be an issue.</p>\n<p>The following might be more efficient. Create a sequence of mapped-item / group-index pairs:</p>\n<pre><code>public IEnumerable<(DTO.Item mappedItem, int groupIndex)> GroupIndexes(int rangeSize) {\n foreach (var item in _itemRepository.GetAll()) {\n var groupIndex = Math.Floor(item.Value / rangeSize);\n var mapped = _mapper.Map<DTO.Item>(item);\n yield return (mapped, groupIndex);\n if (item.Value > 0 && item.Value % rangeSize == 0) {\n yield return (mapped, groupIndex - 1);\n }\n }\n}\n</code></pre>\n<p>which you could then use to group:</p>\n<pre><code>var grouped = GroupIndexes(10).GroupBy(x => x.groupIndex, x => x.mappedItem);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T17:18:22.827",
"Id": "243994",
"ParentId": "243826",
"Score": "3"
}
},
{
"body": "<p>I would generalize it as an extension method:</p>\n<pre><code>public static IEnumerable<IEnumerable<U>> GroupByValueRange<T, U>(\n this IEnumerable<T> items,\n int rangeSize,\n Func<T, double> getValue,\n Func<T, U> map)\n{\n items = items.ToList();\n\n double steps = Math.Ceiling(items.Max(getValue) / rangeSize);\n\n for (int i = 1; i <= steps; i++)\n {\n int max = i * rangeSize;\n int min = (i - 1) * rangeSize;\n\n yield return items\n .Where(p => getValue(p) >= min && getValue(p) <= max)\n .Select(map);\n }\n}\n</code></pre>\n<p>Your code to call it would look like:</p>\n<pre><code>var grouped = _itemRepository.GetAll().GroupByValueRange(10, p => p.Value, p => _mapper.Map<RepoistoryItem, DTO.Item>(p));\n</code></pre>\n<p>(I made up <code>RepositoryItem</code> for this)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T19:51:09.963",
"Id": "244000",
"ParentId": "243826",
"Score": "3"
}
},
{
"body": "<p>As others pointed out you are iterating over the source a lot. Once ToList and every loop in the step. Your grouping method is tied to repository and GetAll method. It would be better to pass that into the method instead of having how to access data as part of the grouping. I would also recommend removing the mapping from this method as well and use the standard Select afterwards. Every method should just have one responsibility and right now your method gets data, groups data and projects the data. This would make it hard to unit test and maintain down the road.</p>\n<p>Typically when dealing with IEnumerable we want to try to avoid multiple iterations. We can do this here but does make the code more complicated. It's always a fine line between complex code and maintenance.</p>\n<p>Can see in this method signature it takes in the source, rangeSize and how we determine the grouping value.</p>\n<pre><code>public static class IEnumerableExtensions\n{\n public static ILookup<(int start, int end), TSource> GroupByRange<TSource>(this IEnumerable<TSource> source, int rangeSize, Func<TSource, decimal> valueFunc)\n {\n</code></pre>\n<p>You could just update your method to be that signature and fix it but you would still have the issue of multiple iterations, but at least it would be testable and responsible for one thing only.</p>\n<p>Like I said before we want to just iterate over the source once it does get more complex but we can go step by step into it and only you will know if it's worth it.</p>\n<p>Starters I'm return an <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.ilookup-2?view=netcore-3.1\" rel=\"nofollow noreferrer\">ILookup</a> as that will act like across between a dictionary and grouping and it's readonly. I'm also using the ValueTuple and if using a version of .net that doesn't have that I would recommend creating a struct that would hold the range.</p>\n<pre><code>public static ILookup<(int start, int end), TSource> GroupByRange<TSource>(this IEnumerable<TSource> source, int rangeSize, Func<TSource, decimal> valueFunc)\n{\n var grouping = new Dictionary<(int start, int end), List<TSource>>();\n var maxValue = 0m;\n foreach (var item in source)\n {\n var value = valueFunc(item);\n CheckIfNeedToResize(value, maxValue, rangeSize, grouping, valueFunc);\n foreach (var group in grouping.Where(grp => grp.Key.start <= value && grp.Key.end >= value))\n {\n group.Value.Add(item);\n }\n }\n\n // not in love with iterating over the dictionary to convert to lookup\n // if don't want to do this could return IReadOnlyDictionary\n // also because of SelectMany this will exclude key ranges that don't have values\n // if we do return readonly dictionary it will include "empty" key ranges\n // if return readonly dictionary should make it value IEnumerable or and array as well\n return grouping.SelectMany(x => x.Value.Select(v => new { x.Key, Value = v }))\n .ToLookup(x => x.Key, x => x.Value);\n}\n</code></pre>\n<p>As you can see this part of the code isn't that complicated. For the return value if you need the "empty" result sets then I would return a ReadOnlyDictionary instead of LookUp. Again only you know if that's a requirement or not.</p>\n<p>Now for the complicated code. We can storing the maxValue so we can see if we need to add more slots when we hit the next value. We are going to calculate the slots as we move through the collection instead of up front.</p>\n<pre><code>private static void CheckIfNeedToResize<TSource>(decimal currentValue, decimal maxValue, int rangeSize, IDictionary<(int, int), List<TSource>> grouping, Func<TSource, decimal> valueFunc)\n{\n if (currentValue > maxValue)\n {\n maxValue = currentValue;\n // check if we need to add ranges\n var groupCount = grouping.Count;\n var steps = Math.Ceiling(currentValue / rangeSize);\n if (steps > int.MaxValue)\n {\n throw new IndexOutOfRangeException();\n }\n if (steps > groupCount)\n {\n // add in extra "rows" into dictionary\n foreach (var key in Enumerable.Range(groupCount, (int)steps - groupCount)\n .Select(x => (x * rangeSize, (x + 1) * rangeSize)))\n {\n grouping.Add(key, new List<TSource>());\n }\n\n // have an edge case if previous end group had the ending range values in it we need\n // to add it into the next range that we added\n if (groupCount > 0)\n {\n var endRange = groupCount * rangeSize;\n var lastList = grouping[((groupCount - 1) * rangeSize, endRange)];\n var items = lastList.Where(x => valueFunc(x) == endRange);\n grouping[(endRange, (groupCount + 1) * rangeSize)].AddRange(items);\n }\n }\n }\n}\n</code></pre>\n<p>This could be merged up in the main method but because there is a lot going on I moved it to its own. That is personal choice but I feel its easier to read and understand this way. We first check if the current value greater than the max value if so we calculate if we need to add another slot or multiple slots. For each slot we calculate we need to add it to the dictionary and initialize the list of values. There is an edge case where we need to iterate of the last value list to see if we need to add any to the new slot. While if each slot did contain one value each time in theory we would end up iterating over the source twice, I would guess in practice this wouldn't be as much as twice the collection but still that's worst case of n*3.</p>\n<p>Now for testing I just used a console app but you could see how easy it would be to convert to unit test.</p>\n<pre><code>static void Main(string[] args)\n{\n var testData = new[] { new { Value = 14 }, new { Value = 30 }, new { Value = 11 }};\n var lookup = testData.GroupByRange(5, x => x.Value);\n foreach (var items in lookup)\n {\n Console.WriteLine($"Start: {items.Key.start} End: {items.Key.end}");\n foreach (var data in items)\n {\n Console.Write($" Value {data.Value} ");\n }\n Console.WriteLine();\n }\n\n Console.WriteLine("---------------");\n\n testData = new[] { new { Value = 9 }, new { Value = 10 }, new { Value = 11 } };\n lookup = testData.GroupByRange(10, x => x.Value);\n foreach (var items in lookup)\n {\n Console.WriteLine($"Start: {items.Key.start} End: {items.Key.end}");\n foreach (var data in items)\n {\n Console.Write($" Value {data.Value} ");\n }\n Console.WriteLine();\n }\n\n\n Console.WriteLine("done" );\n \n Console.ReadLine();\n}\n</code></pre>\n<p>The first one I wanted to show how it will skip "empty" ranges and the second one was just showing the same results you posted with yours.</p>\n<p>Again this doesn't do the projection and I would just do <code>_itemRepository.GetAll().GroupByRange(10, x => x.Value).Select(_mapper.Map<DTO.Item>)</code> as I don't think adding a projection parameter gains much. With this way now you have a method that is unit testable and can be reused.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T00:34:19.967",
"Id": "244147",
"ParentId": "243826",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T18:38:49.357",
"Id": "243826",
"Score": "7",
"Tags": [
"c#"
],
"Title": "Group by range and include edge duplicates"
}
|
243826
|
<p>JavaScript beginner here! I have written a Tic Tac Toe game is JS that seems to be unbeatable (Title says 'almost' because I'm not sure if it's really unbeatable or just I can't beat it :) ). <br> I really appreciate any help to improve my code and learn from my mistakes. <br>
Project's CodePen = <a href="https://codepen.io/MiladM1715/full/ZEQOLmZ" rel="nofollow noreferrer">https://codepen.io/MiladM1715/full/ZEQOLmZ</a></p>
<pre><code> // Tic Tac Toe Win figures
var gameCtrl = (function () {
var winningConditions, corners, randomCorner;
winningConditions = [
[3, 4, 5],
[2, 4, 6],
[0, 4, 8],
[0, 1, 2],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
];
corners = [0, 2, 6, 8];
randomCorner = corners[Math.floor(Math.random() * 4)];
// If win possible? Win! if not? Block
function winOrBlock(arr, marker, winCondition) {
var status;
// Count number of founded markers (first user & then opponent) if more the two, win or block
var count = 0;
if (arr[0] === marker) count++;
if (arr[1] === marker) count++;
if (arr[2] === marker) count++;
if (count >= 2 && arr.includes("")) {
// Return empty marker to use
if (arr[0] === "") status = winCondition[0];
if (arr[1] === "") status = winCondition[1];
if (arr[2] === "") status = winCondition[2];
return status;
}
}
// Don't put marker somewhere that there's no chance to win
function noStupidMove(arr, marker, winCondition) {
var checkCorners;
var count = 0;
if (arr[0] === '') count++;
if (arr[1] === '') count++;
if (arr[2] === '') count++;
if (arr.includes(marker) && count > 1) {
return winCondition[arr.indexOf("")];
}
}
// If none of others work
function neturalMove(arr, marker, winCondition) {
// If win figures include marker, and there
if(arr.includes(marker) && arr.includes('')) {
return winCondition[arr.indexOf("")];
}
}
//Function to add moves id to game board structure
return {
addToBoard: function (id, marker, board) {
board[id] = marker;
},
// Works for first and 2nd move
firstMoves: function (board, counter, moves) {
var result;
// after opponent's first move, if Center is empty, place it in center, If not? random corner
if (counter === 1) {
return board[4] === "" ? 4 : randomCorner;
} else {
// If it's opponent's second move, check moves array and decide. If none of conditions met, then return false and let winOrBlock or neturalMove do it's job
if (moves[0] === 0 && moves[1] === 7) result = 6;
if (moves[0] === 6 && moves[1] === 5) result = 1;
if (moves[0] === 4 && moves[1] === 8) result = 2;
if (moves[0] === 4 && moves[1] === 2) result = 8;
return board[result] === "" ? result : false;
}
},
// Check if there is a chance for win, block or netural move || check win too
checkStatus: function (board, type, marker, counter) {
var a, b, c, winCondition, callback, check, opMarker;
// Set oponet marker based on currnt marker
marker === "O" ? (opMarker = "X") : (opMarker = "O");
if (type === "check" && counter !== 0) {
// Call functions based on stategy 1.win 2.block 3.netural
callback = [
[winOrBlock, marker],
[winOrBlock, opMarker],
[noStupidMove, marker],
[neturalMove, marker],
];
} else if (type === "check" && counter === 0) {
return randomCorner;
} else if (type === "win") {
callback = "1";
}
for (var x = 0; x < callback.length; x++) {
for (var i = 0; i < winningConditions.length; i++) {
winCondition = winningConditions[i];
a = board[winCondition[0]];
b = board[winCondition[1]];
c = board[winCondition[2]];
// Check win or place number?
if (type === "check") {
check = callback[x][0]([a, b, c], callback[x][1], winCondition);
if (check || check === 0) {
return check;
}
// if check 'type' is "win" only check for win
} else if (type === "win") {
// If a,b,c are same and not empty then it's a win
if (a === b && b === c && c !== "") {
return true;
}
}
}
}
},
// If there is no empty cell, it's a draw (called after win check)
isDraw: function (board) {
return !board.includes("");
},
};
})();
// Takes care of UI
var UICtrl = (function () {
return {
DOMstrings: {
startBtn: '.start-btn',
userScore: '.sc-',
gameResult: '.result',
finalMsg: '.msg',
gameCells: '.cells',
gameCell: '.cell',
},
clearUI: function () {
var cells, cellArr;
cells = document.querySelectorAll(this.DOMstrings.gameCell);
cellArr = Array.prototype.slice.call(cells);
cellArr.forEach(function (cur) {
cur.textContent = "";
});
},
// Add marker to UI
addMarkerUI: function (id, marker) {
var color;
marker === "X" ? (color = "black") : (color = "white");
document.getElementById(
id
).innerHTML = `<span style="color: ${color}">${marker}</span>`;
},
// disable start btn afte start and Enable it after draw or win
disableStartBtn: function (state) {
document.querySelector(this.DOMstrings.startBtn).disabled = state;
},
// Display score on UI
displayScore: function (player, score) {
document.querySelector(this.DOMstrings.userScore + player).textContent = score[player];
},
// display Win or Draw result
displayResult: function (win, draw, player) {
var msg, resultDiv;
player === 0 ? (player = "YOU WIN!") : (player = "YOU LOSE!");
if (win) msg = player;
if (draw) msg = "DRAW";
resultDiv = document.querySelector(this.DOMstrings.gameResult);
resultDiv.style.display = "flex";
document.querySelector(this.DOMstrings.finalMsg).textContent = msg;
setTimeout(function () {
resultDiv.style.display = "none";
}, 2000);
},
};
})();
// Control game behavior
var controll = (function () {
var gameBoard,
isActive,
playerMarker,
currentPlayer,
score,
counter,
twoMoveArr,
DOM;
gameBoard = ["", "", "", "", "", "", "", "", ""];
isActive = true;
playerMarker = ["X", "O"];
currentPlayer = 0;
score = [0, 0];
twoMoveArr = [];
counter = 0;
whoIsPlayingFirst = 0;
DOM = UICtrl.DOMstrings;
// Game Start
document.querySelector(DOM.startBtn).addEventListener("click", function () {
// 1.hide start btn
UICtrl.disableStartBtn(true);
// 2 Reset game UI
UICtrl.clearUI();
// 3 Active game
isActive = true;
// 4. Decide who's playing first
changePlayer();
});
// changes player after hitting start btn and invokes functions
function changePlayer() {
whoIsPlayingFirst === 1 ? (whoIsPlayingFirst = 0) : (whoIsPlayingFirst = 1);
whoIsPlayingFirst === 1 ? userPlay() : AIplay();
}
function userPlay() {
document.querySelector(DOM.gameCells).addEventListener("click", function (e) {
// Works only if clicked cell is empty and game is active
if (isActive && e.target.textContent === "") {
// 1. Get clicked cell and set marker
var cellID = parseInt(e.target.id);
var marker = playerMarker[0];
// Add Selected cell to board and UI
handleDataUI(cellID, marker, gameBoard);
// increase counter to findout play count
counter++;
// Push first two moves into an array to use it later fo blocking
counter < 2 ? twoMoveArr.push(cellID) : (twoMoveArr = false);
// Check for Win or Draw
var win, draw;
win = resultChecker(score, currentPlayer);
draw = resultChecker(score, currentPlayer);
if (!win && !draw) {
AIplay();
}
}
});
}
function AIplay() {
// Change player id to 1
currentPlayer = 1;
// Set Marker
marker = playerMarker[1];
// If User plays first
if (whoIsPlayingFirst === 1) {
// check for first and second moves
firstTwo = gameCtrl.firstMoves(gameBoard, counter, twoMoveArr);
if (counter < 3 && typeof firstTwo === "number") {
cellID = firstTwo;
} else {
// If itsn't two first moves or it returned False, Try to win, block or netural move
cellID = gameCtrl.checkStatus(gameBoard, "check", marker, counter);
}
// If AI plays first, if it's first move then, place marker on random corner. if not first move then try to win or block or do netural move
} else {
cellID = gameCtrl.checkStatus(gameBoard, "check", marker, counter);
}
// Add it to Data strucure and UI
handleDataUI(cellID, marker, gameBoard);
// Check result
resultChecker(score, currentPlayer);
currentPlayer = 0;
}
// adds moves to data and UI
function handleDataUI(id, marker, board) {
gameCtrl.addToBoard(id, marker, board);
UICtrl.addMarkerUI(id, marker);
}
// Checks for win and draw
function resultChecker(score, currentPlayer) {
var win = gameCtrl.checkStatus(gameBoard, "win");
var draw = gameCtrl.isDraw(gameBoard);
if (win) {
score[currentPlayer] += 1;
UICtrl.displayScore(currentPlayer, score);
UICtrl.displayResult(win, false, currentPlayer);
resetGame();
return true;
}
if (draw) {
UICtrl.displayResult(false, draw, currentPlayer);
resetGame();
return true;
}
return false;
}
// Resets game after every game
function resetGame() {
document.querySelector(DOM.startBtn).textContent = "Play Again";
gameBoard = ["", "", "", "", "", "", "", "", ""];
currentPlayer = 0;
isActive = false;
counter = 0;
twoMoveArr = [];
// Enables start btn
UICtrl.disableStartBtn(false);
}
return {
init: function () {
UICtrl.clearUI();
},
};
})(gameCtrl, UICtrl);
controll.init();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T21:43:33.773",
"Id": "478647",
"Score": "0",
"body": "Eyup it is totally unbeatable I actually can't remember the name of the algorithm but what you did right there is a proper algorithm founded by someone I don't remember right now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T11:56:49.190",
"Id": "478669",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>It's not unbeatable.</p>\n<p>I beat it with the following series of moves (though I see you have some randomness so some tries may be required to replicate it)</p>\n<p>I went first, then played middle bottom, ai responded middle middle, I played middle left, ai responded top right, I played bottom left, ai played bottom right, I played top left, and won.</p>\n<p>This will inform my review of your code.</p>\n<p>First of all I would say that if you suspect something like 'this is unbeatable', but you can't prove it. Then that's a brilliant impetus to rewrite your code so that it's easier to reason about and prove is unbeatable.</p>\n<p>Some comments on your code, you shouldn't be using var in JavaScript. It has funny scoping, for example what do you believe the following example prints</p>\n<pre><code>function f() {\n for (var i = 0; i < 10; i++) {\n setTimeout(() => console.log(i));\n }\n}\n\nf();\n</code></pre>\n<p>You should prefer let and const.</p>\n<p>In terms of structure, it would be good for you to separate the logic of playing the game, and the logic of representing the game. For example, the function for the AI deciding what it should play shouldn't concern itself with the representation of the board. Instead have a sensible structure which is an abstract representation of the board (say, an array of arrays), have a function which takes this representation and works out the next move, and another function which translates that move to the UI representation. This will make your code much easier to reason about.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T03:10:24.010",
"Id": "478661",
"Score": "0",
"body": "I've blocked every possible way that i know, that's why i call it \"Almost Unbeatable\" because maybe there's some strategies that i don't know about.\n\nAbout using let : I'm an a beginner. So i started by learning ES5 first and as i know const and let interduced in ES6. That's why I didn't used them."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T22:14:02.820",
"Id": "243835",
"ParentId": "243827",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T18:41:35.723",
"Id": "243827",
"Score": "5",
"Tags": [
"javascript",
"tic-tac-toe"
],
"Title": "Almost unbeatable Tic Tac Toe"
}
|
243827
|
<p>I wrote this hashcons data structure in C and it works correctly. It uses larger twin primes as the capacity and double hashing (open addressing). <a href="https://i.stack.imgur.com/wug8H.png" rel="nofollow noreferrer">Page 614 of "Data Structures and Other Objects Using C++ (4th Edition)" describes the approach</a>.</p>
<p>I am wondering if I can get some feedback on whether I followed the standards and conventions.</p>
<h2>hashcons.h</h2>
<pre><code>#ifndef HASHCONS_H
#define HASHCONS_H
#include <stddef.h>
typedef long (*HASH_CONS_HASH)(void *);
typedef int (*HASH_CONS_EQUAL)(void *, void *);
typedef struct hash_cons_table {
int size;
int capacity;
void **table;
HASH_CONS_HASH hashf;
HASH_CONS_EQUAL equalf;
} *HASH_CONS_TABLE;
/**
* Get item if there is one otherwise create one
* @param temp_item it is a temporary or perhaps stack allocated creation of item
* @param temp_size how many bytes it is
* @param table
*/
void *hash_cons_get(void *temp_item, size_t temp_size, HASH_CONS_TABLE table);
#endif
</code></pre>
<h2>hashcons.c</h2>
<pre><code>#include <stdlib.h>
#include <string.h>
#include "common.h"
#include "prime.h"
#include "hashcons.h"
#define HC_INITIAL_BASE_SIZE 61
// if it's bigger, we need to rehash
// if size > capacity * MAX_DENSITY then rehash
#define MAX_DENSITY 0.5
void hc_insert(HASH_CONS_TABLE hc, void *item);
void hc_initialize(HASH_CONS_TABLE hc, const int base_size) {
hc->capacity = base_size;
// hc->table = malloc(hc->capacity * sizeof(void *));
hc->table = calloc(hc->capacity, sizeof(void *));
hc->size = 0;
int i;
for (i = 0; i < hc->capacity; i++) {
hc->table[i] = NULL;
}
}
/**
* Resizes the table by creating a temporary hash table for values to go off of.
*/
static void hc_resize(HASH_CONS_TABLE hc, const int capacity) {
HASH_CONS_TABLE temp_hc = malloc(sizeof(struct hash_cons_table));
hc_initialize(temp_hc, capacity);
temp_hc->equalf = hc->equalf;
temp_hc->hashf = hc->hashf;
for (int i = 0; i < hc->capacity; i++) {
void *item = hc->table[i];
if (item != NULL) {
hc_insert(temp_hc, item);
}
}
hc->table = temp_hc->table;
hc->capacity = capacity;
free(temp_hc);
}
/**
* Increases the table size based on the "base size" by a factor of 2 + 1
*/
static void hc_resize_up(HASH_CONS_TABLE hc) {
const int new_capacity = next_twin_prime((hc->capacity << 1) + 1);
hc_resize(hc, new_capacity);
}
static int hc_get_index(const int index1, const int index2, const int attempt, const int capacity) {
return (index1 + attempt * index2) % capacity;
}
static int hash1(HASH_CONS_TABLE hc, void *item) {
return labs(hc->hashf(item)) % hc->capacity;
}
static int hash2(HASH_CONS_TABLE hc, void *item) {
return labs(hc->hashf(item)) % (hc->capacity - 2);
}
/**
* Inserts a key/value pair into the hash table.
*/
void hc_insert(HASH_CONS_TABLE hc, void *item) {
if (hc->size > hc->capacity * MAX_DENSITY) {
hc_resize_up(hc);
}
int h1 = hash1(hc, item);
int h2 = hash2(hc, item);
// if collision occurs
if (hc->table[h1] != NULL) {
int attempt = 1;
while (TRUE) {
// get new index
int index = hc_get_index(h1, h2, attempt, hc->capacity);
// if no collision occurs, store
if (hc->table[index] == NULL) {
hc->table[index] = item;
break;
}
attempt++;
}
}
// if no collision occurs
else {
hc->table[h1] = item;
}
hc->size++;
}
/**
* Searches through the hash table for the value of the corresponding key. If nothing is found, NULL
* is returned.
*/
void *hc_search(HASH_CONS_TABLE hc, void *item) {
int h1 = hash1(hc, item);
int h2 = hash2(hc, item);
int attempt = 0;
while (attempt < hc->capacity) {
int index = hc_get_index(h1, h2, attempt, hc->capacity);
// Failed to find
if (hc->table[index] == NULL) {
break;
} else if (hc->equalf(hc->table[index], item)) {
return hc->table[index];
}
attempt++;
}
return NULL;
}
void *hash_cons_get(void *item, size_t temp_size, HASH_CONS_TABLE hc) {
// Initialize data-structure
if (hc->table == NULL) {
hc_initialize(hc, HC_INITIAL_BASE_SIZE);
}
void *search_result = hc_search(hc, item);
if (search_result == NULL) {
// memcopy item before insert
void *copied_item = malloc(temp_size);
memcpy(copied_item, item, temp_size);
hc_insert(hc, copied_item);
return item;
} else {
return search_result;
}
}
</code></pre>
<h2>prime.h</h2>
<pre><code>#ifndef PRIME_H
#define PRIME_H
int next_prime(int x);
int next_twin_prime(int x);
#endif
</code></pre>
<h2>prime.c</h2>
<pre><code>#include "common.h"
#include <math.h>
/*
* Returns whether x is prime or not.
* 1 if prime
* 0 if not prime
* -1 if undefined.
*/
int is_prime(const int x)
{
if (x < 2)
{
return -1;
}
if (x < 4)
{
return 1;
}
if ((x % 2) == 0)
{
return 0;
}
for (int i = 3; i <= floor(sqrt((double)x)); i += 2)
{
if ((x % i) == 0)
{
return 0;
}
}
return 1;
}
/**
* Returns next possible prime
*/
int next_prime(int x)
{
while (is_prime(x) != 1)
{
x++;
}
return x;
}
/**
* Return the next prime greater than parameter such that -2 is also a prime
*/
int next_twin_prime(int x)
{
int attempts = 0;
while (TRUE)
{
int prime = next_prime(x);
if (is_prime(prime - 2))
{
return prime;
}
attempts++;
x = prime + 1;
}
}
</code></pre>
<p>I could not attach the complete code here but this is the <a href="https://github.com/amir734jj/hashcons/tree/0752cb784544f6bd65963aa5ff2ad0214722063b" rel="nofollow noreferrer">repository link</a></p>
|
[] |
[
{
"body": "<p><strong>General Observations</strong><br />\nThe code displays some good programming habits already, such as include guards, good indentation, and wrapping all in <code>if</code> statements, <code>else</code> clauses and loops in braces (<code>{</code> and <code>}</code>). The file structure is good and it is easy to find which files need to be modified in maintenance. Many of the private sub functions are already removed from the global namespace using the keyword <code>static</code>. The comments are appropriate and don’t require a lot of maintenance.</p>\n<p>The areas for improvement are C library functions (don’t reinvent the wheel), memory allocation in C, function complexity, function naming due to complexity, possible performance issues, and C programming conventions.\nThe rest of this review is organized by listing the items that can be improved in descending order from most major to most minor.</p>\n<p>The question would have gotten more attention and wouldn’t have needed a bounty if the following were improved or added:</p>\n<ol>\n<li>A definition of what a hash cons is, I had to google it:</li>\n</ol>\n<blockquote>\n<p>In computer science, particularly in functional programming, <a href=\"https://en.wikipedia.org/wiki/Hash_consing\" rel=\"nofollow noreferrer\">hash consing</a> is a technique used to share values that are structurally equal. The term hash consing originates from implementations of Lisp that attempt to reuse cons cells that have been constructed before, avoiding the penalty of memory allocation.</p>\n</blockquote>\n<ol start=\"2\">\n<li>Rather than just providing a link to a PDF file for the definition of It uses larger twin primes as the capacity and double hashing (open addressing) put at least some of the text in the PDF in the question and make that a link to the PDF for more information.</li>\n<li>Include the entire program in the embedded code.</li>\n<li>Remove commented out code before a code review, it shows that the code may not be ready for a code review.</li>\n</ol>\n<p>Contrary to Code Review rules, the review does cover code in the repository that is not included in the code embedded in the question. FYI I know for a fact that 3000 or more can be included in the question, because I have posted questions with more than 3000 lines. Unlike Stack Overflow on Code Review we encourage more of the code to be posted so that we have a really good idea of what the code does, this helps us give a better review.</p>\n<p><strong>Improve the Unit Test</strong><br />\nThe second <code>for</code> loop in <code>main()</code> does not really test if the items were found in the hash cons table. The loop should have a void pointer that receives the value from ``.</p>\n<pre><code>printf("starting to get stuff\\n");\nfor (i = 0; i < count; i++) {\n void *item = create_dummy(i);\n hash_cons_get(item, sizeof(struct dummy), hc);\n}\n</code></pre>\n<p>The test should be something like this:</p>\n<pre><code>printf("starting to get stuff\\n");\nfor (i = 0; i < count; i++) {\n void *item = create_dummy(i);\n if (hash_cons_get(item, sizeof(struct dummy), hc) == NULL)\n {\n printf("Item %d not found\\n", i);\n }\n}\n</code></pre>\n<p><strong>Memory Allocation in the C Programming Language</strong><br />\nUnlike some more high level and modern languages, there is no garbage collection of memory that is no longer used. The C programming language provides a library function called <code>free</code> that is used for deallocating memory when it isn’t needed anymore. There is only one call to <code>free()</code> in the code and that is in <code>static void hc_resize(HASH_CONS_TABLE hc, const int capacity)</code>. Since the hash cons table itself is allocated as well as the <code>table</code> field within the hash cons table the code currently contains a huge memory leak. The table needs to be deallocated as well.</p>\n<p>In the function <code>static void hc_resize(HASH_CONS_TABLE hc, const int capacity)</code> most of the code is unnecessary if the C library function <a href=\"http://www.cplusplus.com/reference/cstdlib/realloc/?kw=realloc\" rel=\"nofollow noreferrer\">realloc(void *ptr, size_t new_size)</a> is used.\nThe <code>realloc()</code> function automatically copies the contents of the memory of the original block allocated.</p>\n<p>All the calls to <code>malloc()</code> and <code>calloc()</code> are missing necessary error checking. While it is uncommon with modern computers, the C programming memory allocation functions can fail. If they do fail they return <code>NULL</code>. Every call to <code>malloc()</code>, <code>calloc()</code> or <code>realloc()</code> should test that there was a block of memory returned immediately after the call before using the pointer returned. This is especially true in embedded programming where memory might be restricted. The following would be more appropriate in the code, in <code>main()</code></p>\n<pre><code> HASH_CONS_TABLE hc = malloc(sizeof(hc));\n if (hc == NULL)\n {\n fprintf(stderr, "Memory allocation of the hashcons table failed, program exiting.\\n");\n return EXIT_FAILURE;\n }\n</code></pre>\n<p>In the function <code>void hc_initialize(HASH_CONS_TABLE hc, const int base_size)</code> the for loop is unnecessary after you change the code from <code>malloc()</code> to <code>calloc()</code>. Since <code>calloc()</code> was created to allocate arrays the function zeros out the memory during the allocation. If you stayed with the <code>malloc()</code> call it would have been better to use <a href=\"http://www.cplusplus.com/reference/cstring/memset/?kw=memset\" rel=\"nofollow noreferrer\">void * memset ( void * ptr, int value, size_t num )</a>. The function <code>memset()</code> is optimized and it should before better than the for loop.</p>\n<p><strong>Function Complexity</strong><br />\nThere are several functions in the program that are too complex (do too much), and their names don't necessarily indicate the complexity. Some of these functions are <code>main()</code>, <code>void hc_insert(HASH_CONS_TABLE hc, void *item)</code> and <code>static void hc_resize(HASH_CONS_TABLE hc, const int capacity)</code>. While the C programming language is not object oriented, there are some object oriented principles that can be applied.\nThe programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<p>There is possible recursion in the functions <code>void hc_insert(HASH_CONS_TABLE hc, void *item)</code>, <code>static void hc_resize_up(HASH_CONS_TABLE hc)</code> and <code>static void hc_resize(HASH_CONS_TABLE hc, const int capacity)</code>, although I don’t think the recursion is intended.\nOne possible change in the design would be to have a function that just does an insert into the table and have that function called by <code>void hc_insert(HASH_CONS_TABLE hc, void *item)</code>, <code>static void hc_resize_up(HASH_CONS_TABLE hc)</code> and <code>static void hc_resize(HASH_CONS_TABLE hc, const int capacity)</code>.</p>\n<pre><code>static void private_insert(HASH_CONS_TABLE hc, void *item)\n{\n int h1 = hash1(hc, item);\n int h2 = hash2(hc, item);\n\n // if collision occurs\n if (hc->table[h1] != NULL) {\n int attempt = 1;\n while (true) {\n // get new index\n int index = hc_get_index(h1, h2, attempt, hc->capacity);\n\n // if no collision occurs, store\n if (hc->table[index] == NULL) {\n hc->table[index] = item;\n break;\n }\n attempt++;\n }\n }\n // if no collision occurs\n else {\n hc->table[h1] = item;\n }\n\n hc->size++;\n}\n\nstatic void hc_resize(HASH_CONS_TABLE hc, const int capacity) {\n\n HASH_CONS_TABLE temp_hc = malloc(sizeof(struct hash_cons_table));\n hc_initialize(temp_hc, capacity);\n temp_hc->equalf = hc->equalf;\n temp_hc->hashf = hc->hashf;\n\n for (int i = 0; i < hc->capacity; i++) {\n void *item = hc->table[i];\n if (item != NULL) {\n private_insert(temp_hc, item);\n }\n }\n\n hc->table = temp_hc->table;\n hc->capacity = capacity;\n free(temp_hc);\n}\n\nvoid hc_insert(HASH_CONS_TABLE hc, void *item) {\n if (hc->size > hc->capacity * MAX_DENSITY) {\n hc_resize_up(hc);\n }\n private_insert(hc, item);\n}\n</code></pre>\n<p>Another concept we can use from object oriented programming is Data Hiding and private functions. For instance the function<code>hc_insert()</code> above should be a static function since it isn’t exported by the <code>hashcons.h</code> header file.\nA good constructor function for the <code>*HASH_CONS_TABLE</code> struct might be added to <code>hashcons.c</code> and exported by <code>hashcons.h</code> as well as a destructor for the table.</p>\n<p>hashcons.h:</p>\n<pre><code>extern HASH_CONS_TABLE hash_cons_table_create(HASH_CONS_HASH hashf, HASH_CONS_EQUAL equalf);\nextern HASH_CONS_TABLE hash_cons_table_delete(HASH_CONS_TABLE table);\n</code></pre>\n<p>hashcons.c</p>\n<pre><code>Hash_Cons_Table_Ptr hash_cons_table_create(Hash_Cons_Hash hashf, Hash_Cons_Equal equalf)\n{\n Hash_Cons_Table_Ptr hc = malloc(sizeof(*hc));\n if (hc == NULL)\n {\n fprintf(stderr, "Memory allocation of the hashcons table failed, program exiting.\\n");\n return NULL;\n }\n\n memset(hc, 0, sizeof(*hc));\n hc->hashf = hashf;\n hc->equalf = equalf;\n\n return hc;\n}\n\nHASH_CONS_TABLE hash_cons_table_delete(HASH_CONS_TABLE hc)\n{\n for (size_t i = 0; i < hc->capacity)\n {\n if (hc->table[i])\n {\n free(hc->table[i]);\n }\n }\n free(hc->table);\n free(hc);\n return NULL;\n}\n</code></pre>\n<p>main.c:</p>\n<pre><code>static int test_adding_items(HASH_CONS_TABLE hc, int test_sample)\n{\n printf("starting to add stuff\\n");\n int failure_count = 0;\n for (int i = 0; i < test_sample; i++) {\n void *item = create_dummy(i);\n if (!hash_cons_get(item, sizeof(struct dummy), hc))\n {\n failure_count++;\n }\n }\n printf("finished adding stuff\\n");\n\n return failure_count;\n}\n\nstatic int test_getting_times(HASH_CONS_TABLE hc, int test_sample)\n{\n printf("starting to get stuff\\n");\n int failure_count = 0;\n for (size_t i = 0; i < test_sample; i++) {\n void *item = create_dummy(i);\n\n if (hash_cons_get(item, sizeof(struct dummy), hc) == NULL)\n {\n failure_count++;\n printf("Item %d not found\\n", i);\n }\n }\n printf("finished getting stuff\\n");\n\n return failure_count;\n}\n\nint main() {\n HASH_CONS_TABLE hc = hash_cons_table_create(hash, equal);\n if (hc == NULL)\n {\n fprintf(stderr, "Memory allocation of the hashcons table failed, program exiting.\\n");\n return EXIT_FAILURE;\n }\n int count = 30000;\n\n printf("There were %d failures in test_adding_items", test_adding_items(hc, count));\n printf("There were %d failures in test_getting_times", test_getting_times(hc, count));\n\n hc = hash_cons_table_delete(hc);\n\n printf("Done!");\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n<p>It might be better to add a max_density field to the HASH_CONS_TABLE struct so that it could be set by flags during creation. Once the table is actually in use, the user may want to increase the density.</p>\n<p><strong>Possible Performance Improvements</strong><br />\nRather than performing a search for the proper primes when resizing the table, it would be better to build a table of paired primes when the hash cons table is constructed using the Sieve of Eratosthenes. When the table needs to be resized just index to the next pair of primes in the table and use those. This will prevent large overhead during item insert and improve performance. There will be a performance hit when the hash cons table is created, but that will be once rather than many times during execution.</p>\n<p><strong>Portability (Don’t Reinvent the Wheel)</strong><br />\nThe code would be much more portable if the standard header file <code>stdbool.h</code> was include instead of the symbolic constants defined in <code>common.h</code>. This would allow the code to have Boolean types and use <code>true</code> and <code>false</code> rather than <code>TRUE</code> and <code>FALSE</code>. This will come in handy if the code is ported to C++ as some point, and <code>stdbool.h</code> should be available wherever C90 is available.</p>\n<p><strong>Conventions</strong><br />\nRather than using int as an index into a table, prefer unsigned values such as <code>unsigned int</code>, <code>unsigned long</code> or <code>size_t</code>. This will prevent negative indexes in a table, especially when it is possible for integer overflow to happen (integers can go negative if they are incremented too far.</p>\n<p>Capitalize types rather than making them all capitals, all capitals is generally reserved for macros and constants (the code is already doing this).</p>\n<pre><code>#include <stdbool.h>\n\ntypedef long (*Hash_Cons_Hash)(void *item);\n\ntypedef bool (*Hash_Cons_Equal)(void *item1, void *item2);\n\ntypedef struct hash_cons_table {\n int size;\n int capacity;\n void **table;\n Hash_Cons_Hash hashf;\n Hash_Cons_Equal equalf;\n} *Hash_Cons_Table_Ptr;\n</code></pre>\n<p>Include the variable names in the function prototypes so that users have some idea of what should be passed in. (self-documenting code)</p>\n<p>The header file <code>stdlib.h</code> includes 2 symbolic constants for C program exit status. These are <code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code>. These symbolic constants make <code>main()</code> easier to read and understand.</p>\n<p>In main.c it might be better if 13, 17 and 3000 were symbolic constants that would make the code more self-documenting, it is unclear why those numbers were chosen.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T17:08:08.230",
"Id": "479682",
"Score": "1",
"body": "_functions are already removed from the global namespace using the keyword static_ - This is C; there are no namespaces. `static` narrows symbols to their own translation unit instead of being visible in other translation units. In other words, it's a linker mechanism moreso than a language scoping mechanism."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T17:11:08.703",
"Id": "479683",
"Score": "1",
"body": "p.s. it will still be a \"global\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T17:23:06.223",
"Id": "479685",
"Score": "1",
"body": "@Reinderien Agreed, it will still be \"global\" to the translation unit (FILE.c) it just won't impact linking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T22:21:32.020",
"Id": "480269",
"Score": "0",
"body": "@pacmaninbw I asked a follow-up question: https://codereview.stackexchange.com/questions/244639/follow-up-to-c-simple-hashcons-data-structure"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T18:37:11.107",
"Id": "244130",
"ParentId": "243831",
"Score": "7"
}
},
{
"body": "<p>I have one comment about for loops. According to standard, for loop condition is evaluated on every iteration. In function <code>is_prime</code> expression <code>floor(sqrt((double)x))</code> will be evaluated several times which will cause performance penalty. It is better rewrite this loop. For example:</p>\n<pre><code>int condition = floor(sqrt((double)x));\nfor (int i = 3; i <= condition; i += 2)\n{\n if ((x % i) == 0)\n {\n return 0;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T16:06:09.653",
"Id": "244332",
"ParentId": "243831",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244130",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T19:40:45.127",
"Id": "243831",
"Score": "5",
"Tags": [
"c",
"homework",
"hash-map"
],
"Title": "C simple hashcons data structure"
}
|
243831
|
<p>I'm exploring String relativity and comparison techniques, and I found Hamming distance algorithm in my search so I give a try to implement that approach in Java and below I'm sharing my implementation.</p>
<p>Please let me know if this approach is correct or I need to improve it more.</p>
<p>HammingDistance.java</p>
<pre><code>public interface HammingDistance {
public int distance(String first,String second);
}
</code></pre>
<p>HammingDistanceImpl.java</p>
<pre><code>public class HammingDistanceImpl implements HammingDistance {
@Override
public int distance(String first, String second) {
first = first.trim().toLowerCase();
first = flipFyString(first);
second = second.trim().toLowerCase();
second = flipFyString(second);
// System.out.println(first + " " + second);
if (first.length() - second.length() == 1 || first.length() - second.length() == 2
|| first.length() - second.length() == 3) {
// System.out.println("Second String bit shorter in length to First String");
return calculatedDistance(second, first);
}
if (second.length() - first.length() == 1 || second.length() - first.length() == 2
|| second.length() - first.length() == 3) {
// System.out.println("First String bit shorter in length to Second String");
return calculatedDistance(first, second);
}
if (first.length() == second.length()) {
// System.out.println("Both String Are Equals");
return calculatedDistance(first, second);
}
if (first.length() == second.length() / 2) {
// System.out.println("First String is Half of Second String");
int result = calculatedDistance(first, second.substring(0, second.length() / 2));
return result;
}
if (first.length() == second.length() / 2) {
int result2 = calculatedDistance(first, second.substring(second.length() / 2, second.length()));
return result2;
}
if (second.length() == first.length() / 2) {
// System.out.println("Second String is Half of First String");
int result = calculatedDistance(second, first.substring(0, first.length() / 2));
return result;
}
if (second.length() == first.length() / 2) {
int result2 = calculatedDistance(second, first.substring(first.length() / 2, first.length()));
return result2;
}
return 0;
}
private int calculatedDistance(String first, String second) {
int messasureDistance = 0;
char[] firstStrCharArray = first.toCharArray();
char[] secondStrCharArray = second.toCharArray();
// System.out.println(first + " " + second);
for (int i = 0; i < firstStrCharArray.length; i++) {
if (firstStrCharArray[i] != secondStrCharArray[i]) {
messasureDistance++;
}
}
return messasureDistance;
}
private String flipFyString(String str) {
StringBuffer word = new StringBuffer();
char[] charArray = str.toCharArray();
for (int i = 0; i <= charArray.length; i++) {
int j = i + 1;
if (j <= charArray.length - 1 && charArray[i] != charArray[j]) {
word.append(charArray[i]);
}
}
word.append(charArray[charArray.length - 1]);
return word.toString();
}
}
</code></pre>
<p>HammingImplTest.java</p>
<pre><code>import java.util.ArrayList;
import java.util.List;
import java.util.OptionalInt;
public class HammingImplTest {
public static void main(String... strings) {
List<Boolean> resultlist = new ArrayList<>();
resultlist.add(testHammingAlgo("India is near to pakistan.", "India is neighbour of pakistan."));
resultlist.add(testHammingAlgo("India is near to pakistan.", "India is neighbour of nepal."));
resultlist.add(testHammingAlgo("Simmant Yadav", "Seemant Yadav"));
resultlist.add(testHammingAlgo("I love code in java", "I love coding in java"));
/*
* Specific result count
*
* System.out.println(resultlist.stream().filter(data->!data).count());
* if(resultlist.stream().filter(data->data).count()==3 &&
* resultlist.stream().filter(data->!data).count()==1) {
* System.out.println("Test cases satisfied"); }
*/
resultlist.forEach(data -> System.out.println(data));
}
private static boolean testHammingAlgo(String first, String second) {
boolean result = false;
HammingDistanceImpl hamingImpl = new HammingDistanceImpl();
String[] sentenceFirst = first.split(" ");
String[] sentenceTwo = second.split(" ");
ArrayList<Integer> distance = new ArrayList<>();
for (int i = 0; i <= sentenceFirst.length - 1; i++) {
distance.add(hamingImpl.distance(sentenceFirst[i], sentenceTwo[i]));
}
OptionalInt maxD = distance.stream().mapToInt(v -> v).max();
if (maxD.getAsInt() <= 3) {
result = true;
}
return result;
}
}
</code></pre>
<p>Test Results :</p>
<pre><code>true
false
true
true
</code></pre>
|
[] |
[
{
"body": "<p>I have some suggestions.</p>\n<h2>Don’t edit the parameter values, create your own instance / copy</h2>\n<p>In my opinion, this is a bad habit, since some objects in Java are not immutable (Collections, Date, ect) when passed as parameters, you will edit the original instance of the caller. In your code, since the string is immutable, you are fine, but keep this in mind.</p>\n<h3>HammingDistanceImpl#distance</h3>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public int distance(String first, String second) {\n first = first.trim().toLowerCase();\n //[...]\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public int distance(String first, String second) {\n String firstValue = first.trim().toLowerCase();\n //[...]\n}\n</code></pre>\n<h2>Move the conversion of the string in the method <code>flipFyString</code></h2>\n<p>Since this method seems to need the trimmed and lowered case version of it, I suggest that you do this in the method.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public int distance(String first, String second) {\n first = first.trim().toLowerCase();\n first = flipFyString(first);\n //[...]\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public int distance(String first, String second) {\n first = flipFyString(first);\n //[...]\n}\n\nprivate String flipFyString(String str) {\n String value = str.trim().toLowerCase();\n //[...]\n}\n</code></pre>\n<h2>Use <code>java.lang.StringBuilder</code> instead of <code>java.lang.StringBuffer</code> (<code>flipFyString</code>)</h2>\n<p>As stated in the <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/StringBuffer.html\" rel=\"nofollow noreferrer\">java documentation</a>, the <code>java.lang.StringBuilder</code> class is recommended over the <code>java.lang.StringBuffer</code> since it performs no synchronization and is generally faster.</p>\n<h2>Extract the result of <code>.length()</code> in variables</h2>\n<p>In your code, instead of calling multiples times the method, I suggest that you extract the result in a variable and reuse it.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nif (first.length() - second.length() == 1 || first.length() - second.length() == 2\n || first.length() - second.length() == 3) {\n return calculatedDistance(second, first);\n}\n//[...]\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nint firstLength = firstValue.length();\nint secondLength = secondValue.length();\n\nif (firstLength - secondLength == 1 || firstLength - secondLength == 2 || firstLength - secondLength == 3) {\n return calculatedDistance(secondValue, firstValue);\n}\n//[...]\n</code></pre>\n<h2>Instead of using a variable to store the value, return the result directly</h2>\n<p>In your code, you can directly return the result, instead of storing it into a variable and then, returning it. This will make the code shorter and easier to read.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nif (first.length() == second.length() / 2) {\n int result2 = calculatedDistance(first, second.substring(second.length() / 2, second.length()));\n return result2;\n}\n//[...]\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nif (first.length() == second.length() / 2) {\n return calculatedDistance(first, second.substring(second.length() / 2, second.length()));\n}\n//[...]\n</code></pre>\n<h2>Review your logic, since you have duplicated condition 'first.length() == second.length() / 2'</h2>\n<p>You have two <code>if</code> with the same condition, the second one is dead code at the moment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T15:45:31.767",
"Id": "487953",
"Score": "0",
"body": "I'm fine with your comments on design approach, but I'm more concern about implementation, so just like the way I implemented this algorithm is correct or not?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T01:20:44.927",
"Id": "243838",
"ParentId": "243833",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243838",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-13T20:21:36.030",
"Id": "243833",
"Score": "4",
"Tags": [
"java",
"algorithm",
"strings"
],
"Title": "Hamming distance implementation in Java"
}
|
243833
|
<p>I have a function that I created in Codepen. It does what I want, where the div that you select gets a blue border and changes its text. But I would like to know if there is any way to make the JavaScript that actually makes this work more compact/efficient.</p>
<p><a href="https://codepen.io/JosephChunta/pen/RwrRpeB" rel="nofollow noreferrer">Codepen</a></p>
<p>JavaScript</p>
<pre><code>function toggle(el) {
const contentReference = document.querySelectorAll('.content');
for (div of contentReference) { div.className = 'content'; }
el.className = 'content selected';
const selectedContentReference = document.querySelectorAll('.selectedContent');
for (div of selectedContentReference) {
if (div.parentNode.className == 'content') {
div.className = 'selectedContent contentThatShouldBeHidden';
}
else if (div.parentNode.className == 'content selected') {
div.className = 'selectedContent';
}
}
const notselectedContentReference = document.querySelectorAll('.notselectedContent');
for (div of notselectedContentReference) {
if (div.parentNode.className == 'content') {
div.className = 'notselectedContent';
}
else if (div.parentNode.className == 'content selected') {
div.className = 'notselectedContent contentThatShouldBeHidden';
}
}
}
const selectedContentReference = document.querySelectorAll('.selectedContent');
for (div of selectedContentReference) {
if (div.parentNode.className == 'content') {
div.className = 'selectedContent contentThatShouldBeHidden';
}
else if (div.parentNode.className == 'content selected') {
div.className = 'selectedContent';
}
}
const notselectedContentReference = document.querySelectorAll('.notselectedContent');
for (div of notselectedContentReference) {
if (div.parentNode.className == 'content') {
div.className = 'notselectedContent';
}
else if (div.parentNode.className == 'content selected') {
div.className = 'notselectedContent contentThatShouldBeHidden';
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T10:32:07.407",
"Id": "478668",
"Score": "0",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>To be honest this is very over-engineered. The same can be done with very little to no JavaScript by taking advantange of the features of CSS. But one by one.</p>\n<hr />\n<p>First off the class name <code>content</code> is bad choice. It is very generic. It runs into the danger to be used in some other context on the same page and it doesn't describe what you are using it for. Something like <code>selectable</code> would be better.</p>\n<hr />\n<p>Using <code>className</code> to identify elements is for one verbose, for the other unrelatiabe. An element, for example, that has both the classes <code>content</code> and <code>selected</code> could have a <code>className</code> <code>"content selected"</code> or <code>"selected content"</code> or <code>"content selected someOtherClass"</code>, etc. Just because you set it to <code>"content selected"</code> there is no guarantee that it will stay that.</p>\n<p>Instead you should use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/classList\" rel=\"nofollow noreferrer\"><code>classList</code></a> property. It allows you the set, remove, toggle and check for separate classes (and more).</p>\n<p>So, for example, the block</p>\n<pre><code>const selectedContentReference = document.querySelectorAll('.selectedContent');\nfor (div of selectedContentReference) {\n if (div.parentNode.className == 'content') {\n div.className = 'selectedContent contentThatShouldBeHidden';\n }\n else if (div.parentNode.className == 'content selected') {\n div.className = 'selectedContent';\n }\n}\n</code></pre>\n<p>can become:</p>\n<pre><code>const selectedContentReference = document.querySelectorAll('.selectedContent');\nfor (div of selectedContentReference) {\n const parentIsSelected = div.parentNode.classList.contains("selected");\n div.classList.toggle("contentThatShouldBeHidden", !parentIsSelected);\n}\n</code></pre>\n<hr />\n<p>There is more that could be said to the JavaScript, however all this class toggling is unnecessary. By using, for example, the CSS <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator\" rel=\"nofollow noreferrer\">child combinator</a> and the <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:not\" rel=\"nofollow noreferrer\"><code>:not</code> pseudo class</a> you can show and hide the approprate texts depending on the <code>selected</code> class on the parent element alone.</p>\n<p>Using the same HTML and limiting the <code>toggle</code> function to:</p>\n<pre><code>// Moving the list of elements outside the function, because the list doesn't change\nconst contentReference = document.querySelectorAll('.content');\n\nfunction toggle(el) {\n for (div of contentReference) { div.classList.remove("selected"); }\n el.classList.add("selected");\n}\n</code></pre>\n<p>and following CSS:</p>\n<pre><code>.content:not(.selected) > .selectedContent, \n.content.selected > .notselectedContent {\n display: none;\n}\n</code></pre>\n<hr />\n<p>And as I mentioned at the beginning it is possible to do this without JavaScript. HTML has such a toggling feature built in: radio buttons. And CSS can be used to style elements depending on if a radio button is selected (<code>:checked</code>) or not, even if the radio button isn't visible.</p>\n<p><a href=\"https://jsfiddle.net/27kw8qe1/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/27kw8qe1/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T09:54:07.360",
"Id": "243850",
"ParentId": "243837",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243850",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T01:20:25.057",
"Id": "243837",
"Score": "3",
"Tags": [
"javascript",
"html",
"css"
],
"Title": "Selecting a div with a blue border and changing its text"
}
|
243837
|
<p>According to LeetCode, the following question is one of the most frequent interview questions asked by companies such as Facebook and Google. Here, I'm posting C++/Java codes, if you'd like to review, please do so.</p>
<h2><a href="https://leetcode.com/problems/subarray-sum-equals-k/" rel="nofollow noreferrer">LeetCode 560</a></h2>
<blockquote>
<p>Given an array of integers and an integer <code>target</code> (K), you need to find the
total number of continuous subarrays whose sum equals to <code>target</code>.</p>
<h3>Example 1:</h3>
<p>Input:nums = [1,1,1], target = 2 Output: 2</p>
<h3>Constraints:</h3>
<p>The length of the array is in range [1, 20,000].<br />
The range of numbers in the array is [-1000, 1000] and the range of the integer <code>target</code> is [-1e7,
1e7].</p>
</blockquote>
<h3>C++</h3>
<pre><code>class Solution {
public:
int subarraySum(vector<int> &nums, int target) {
map<int, int> prefix_sum;
int sum = 0, subarrays = 0;
prefix_sum[0]++;
for (int index = 0; index < nums.size(); index++) {
sum += nums[index];
subarrays += prefix_sum[sum - target];
prefix_sum[sum]++;
}
return subarrays;
}
};
</code></pre>
<h3>Java</h3>
<pre><code>class Solution {
public int subarraySum(int[] nums, int target) {
int sum = 0, subarrays = 0;
Map<Integer, Integer> prefixSum = new HashMap<>();
prefixSum.put(0, 1);
for (int index = 0; index != nums.length; index++) {
sum += nums[index];
if (prefixSum.get(sum - target) != null)
subarrays += prefixSum.get(sum - target);
prefixSum.put(sum, -~prefixSum.getOrDefault(sum, 0));
}
return subarrays;
}
}
</code></pre>
<h3>Reference</h3>
<ul>
<li><a href="https://leetcode.com/problems/subarray-sum-equals-k/solution/" rel="nofollow noreferrer">LeetCode 560</a></li>
<li><a href="https://leetcode.com/problems/subarray-sum-equals-k/discuss/?currentPage=1&orderBy=most_votes&query=" rel="nofollow noreferrer">LeetCode 560 Discussion Board</a></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T15:34:20.303",
"Id": "478692",
"Score": "2",
"body": "Please do not update the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T15:55:26.970",
"Id": "495565",
"Score": "3",
"body": "For future questions, I recommend separate questions per language; see [Are you allowed to ask for reviews of the same program written in two languages?](//codereview.meta.stackexchange.com/q/10574/75307)"
}
] |
[
{
"body": "<p>I have some suggestion for the Java version</p>\n<h2>Always try to pass the size of the maximum size to the Collection / Map constructor when known</h2>\n<p>The map has a default size of 16 elements, if you have more elements, the map will have to resize its internal cache. By setting the size, you can prevent the resize and make your code faster.</p>\n<p>In this case, you can set the maximum size since it's based on the size of the array + 1.</p>\n<pre class=\"lang-java prettyprint-override\"><code>Map<Integer, Integer> prefixSum = new HashMap<>(nums.length + 1);\n</code></pre>\n<h2>Extract the expression to variables when used multiple times</h2>\n<p>In your code, when you check if the key is present, you can extract the value to a variable to reuse it when present.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if (prefixSum.get(sum - target) != null)\n subarrays += prefixSum.get(sum - target);\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>Integer currentValue = prefixSum.get(sum - target);\nif (currentValue != null)\n subarrays += currentValue;\n</code></pre>\n<p>This will be better, since this will prevent the rechecking and the rehashing in the map.</p>\n<h2>Always add curly braces to <code>loop</code> & <code>if</code></h2>\n<p>In my opinion, it's a bad practice to have a block of code not surrounded by curly braces; I saw so many bugs in my career related to that, if you forget to add the braces when adding code, you break the logic / semantic of the code.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if (prefixSum.get(sum - target) != null)\n subarrays += prefixSum.get(sum - target);\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if (prefixSum.get(sum - target) != null) {\n subarrays += prefixSum.get(sum - target);\n}\n</code></pre>\n<h2>Extract some of the logic to methods.</h2>\n<p>In this case, I suggest to extract the map creation to a method; this will allow to group the logic and make the main code shorter.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public int subarraySum(int[] nums, int target) {\n Map<Integer, Integer> prefixSum = buildMap(lengthOfNums + 1);\n //[...]\n}\n\nprivate Map<Integer, Integer> buildMap(int defaultSize) {\n Map<Integer, Integer> prefixSum = new HashMap<>(defaultSize);\n prefixSum.put(0, 1);\n return prefixSum;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T11:08:21.983",
"Id": "479636",
"Score": "1",
"body": "About those curly braces: you know what happens when you *don't* do that? [Heartbleed](https://blog.codecentric.de/en/2014/02/curly-braces/). Very good advice to add those braces indeed. It doesn't fix everything (as indicated by that article), but it does make the bug more obvious."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T13:52:22.057",
"Id": "243861",
"ParentId": "243843",
"Score": "3"
}
},
{
"body": "\n<p>This will be a review of the C++ code. Some of this applies to the Java version as well, but my Java expertise is very much in the 20th century!</p>\n<h1>Algorithm</h1>\n<p>A good choice of algorithm. It may be worth adding some comments to indicate why you've chosen this one. From my reading, it scales well with the size of the input array: O(<em>n</em>) in time and O(<em>n</em>) in additional storage.</p>\n<h1>Unnecessary class</h1>\n<p>There is no need in C++ for your function to be a member of a class. Just make it a free function. If the interface is imposed on you, I still recommend a free function, which can be called from a small adapter, like this:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>int count_subarrays_matching_sum(const vector<int> &nums, int target);\n\n// Adapter for user that expects a class object\nclass Solution {\npublic:\n int subarraySum(vector<int> &nums, int target) const {\n return count_subarrays_matching_sum(nums, target);\n }\n};\n</code></pre>\n<h1>Unit tests</h1>\n<p>It's disappointing that you haven't included any tests for this code, particularly since the description gives at least one example of input and output. You could create a simple <code>main()</code> that exercises the function and verifies the output, or use one of the many available test frameworks to take care of the details. For example, using Google Test:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>#include <gtest/gtest.h>\n\nTEST(count_subarrays, empty)\n{\n EXPECT_EQ(0, count_subarrays_matching_sum({}, 0));\n EXPECT_EQ(0, count_subarrays_matching_sum({}, 0));\n}\n\nTEST(count_subarrays, three_ones)\n{\n EXPECT_EQ(0, count_subarrays_matching_sum({1, 1, 1}, 0));\n EXPECT_EQ(3, count_subarrays_matching_sum({1, 1, 1}, 1));\n EXPECT_EQ(2, count_subarrays_matching_sum({1, 1, 1}, 2));\n}\n</code></pre>\n<p>Let's also include some tests of the tricky case when the elements are all zero:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>TEST(count_subarrays, zeros)\n{\n EXPECT_EQ(1, count_subarrays_matching_sum({0}, 0));\n EXPECT_EQ(6, count_subarrays_matching_sum({0, 0, 0}, 0));\n}\n</code></pre>\n<h1><code>namespace std</code></h1>\n<p>You've not shown the <code>#include <map></code> and <code>#include <vector></code> that are necessary for compilation. Also, we have <code>std::map</code> and <code>std::vector</code> in the global namespace due to a <code>using</code> that's not shown. That's a bad habit to get into; it's best to get used to writing the <code>std</code> qualifier where necessary. (In fact, since it's only needed twice here, that's the easy approach anyway!).</p>\n<h1>Data types</h1>\n<p>If you're mainly a Java programmer, you're probably used to the integer types having the same range on all platforms, but C++ adapts to the target processor in a way that Java doesn't.</p>\n<p>Let's look again at the constraints in the question. The elements in the array may range from -1000 to +1000, so using <code>int</code> for those is reasonable (<code>int</code> must be able to represent at least the range [-32768,32767]). However, the target may be as large as ±10,000,000, so <code>int</code> isn't suitable for that. Thankfully, we can include <code><cstdint></code> for some suitable large-enough types:</p>\n<ul>\n<li><code>std::int32_t</code> - exact 32-bit type (only if possible on this platform)</li>\n<li><code>std::int_least32_t</code> - smallest 32-bit (or more) type available</li>\n<li><code>std::int_fast32_t</code> - fastest 32-bit (or more) type available</li>\n</ul>\n<p>We don't need exactly 32-bit range, so the obvious choice here is <code>std::int_fast32_t</code>.</p>\n<p>For the sum and count of matching subarrays, we'll need to think about the extreme cases. Since the array may hold up to 20,000 elements, then the sum can be as large as ±1000 * 20000 = ±20,000,000. Again <code>std::int_fast32_t</code> is suitable here. For the number of subarrays, the extreme case would be an input of 20,000 zeros, and a target of zero, making ½ * 20000 * 10000 = 100,000,000 matching subarrays. Again, we can use <code>std::int_fast32_t</code> for this, but given that this is a count of elements, it's probably more appropriate to use an unsigned type: <code>std::uint_fast32_t</code>.</p>\n<p>It's a good idea to give names to the types we'll use, so that it's clear what's going on in the code, and to make it easier for us to adapt it to changes in the constraints:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>#include <cstdint>\n#include <map>\n#include <vector>\n\nusing element_type = int;\nusing target_type = std::int_fast32_t;\nusing count_type = std::uint_fast32_t;\n\ncount_type count_subarrays_matching_sum(const std::vector<element_type> &nums,\n target_type target)\n</code></pre>\n<h1>Increment and decrement operators</h1>\n<p>It's a good habit to get used to using the prefix forms of <code>++</code> and <code>--</code> when you don't use the result. For the integer types used here, the resulting code will be identical, but classes that overload these operators generally need to make a copy for the postfix form, making that less efficient. Example:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code> ++prefix_sum[sum];\n</code></pre>\n<h1>Range-based <code>for</code></h1>\n<p>I get a warning due to the mismatched types in the <code>for</code> loop:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>243843.cpp:14:31: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::vector<int>::size_type’ {aka ‘long unsigned int’} [-Wsign-compare]\n for (int index = 0; index < nums.size(); ++index) {\n ~~~~~~^~~~~~~~~~~~~\n</code></pre>\n<p>Although this isn't a problem given that we know the size will be less than 20000 elements, it's easy to use the correct type for <code>index</code>. Even better, since we only use it for accessing the elements, we can eliminate the arithmetic there entirely:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>for (auto element: nums) {\n sum += element;\n</code></pre>\n<p>With the above changes, I now have:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>#include <cstdint>\n#include <map>\n#include <vector>\n\nusing element_type = int;\nusing target_type = std::int_fast32_t;\nusing count_type = std::uint_fast32_t;\n\ncount_type count_subarrays_matching_sum(const std::vector<element_type> &nums,\n target_type target)\n{\n using sum_type = std::int_fast32_t;\n\n // Maps each prefix sum to the number of times previously seen\n std::map<sum_type, count_type> prefix_sum;\n\n sum_type sum = 0;\n count_type matched_count = 0;\n\n ++prefix_sum[0];\n for (auto element: nums) {\n sum += element;\n matched_count += prefix_sum[sum - target];\n ++prefix_sum[sum];\n }\n\n return matched_count;\n}\n</code></pre>\n<h1>Generic interface</h1>\n<p>Slightly more advanced, we can consider accepting a pair of iterators instead of a <code>std::vector</code>. This allows the use of other containers without conversion.</p>\n<p>Significantly, it also allows us to read from a stream iterator without having to store all the values at once, which is a useful technique for larger problems with a single-pass algorithm such as this.</p>\n<p>Here's what that would look like (using <code>std::enable_if</code>, but it's somewhat easier to read if your compiler supports Concepts):</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>#include <cstdint>\n#include <iterator>\n#include <map>\n#include <type_traits>\n#include <vector>\n\nusing element_type = int;\nusing target_type = std::int_fast32_t;\nusing count_type = std::uint_fast32_t;\n\ntemplate<typename Iter, typename EndIter>\nstd::enable_if_t<std::is_same_v<element_type, typename std::iterator_traits<Iter>::value_type>, count_type>\ncount_subarrays_matching_sum(Iter first, EndIter last, target_type target)\n{\n using sum_type = std::int_fast32_t;\n\n // Maps each prefix sum to the number of times previously seen\n std::map<sum_type, count_type> prefix_sum;\n\n sum_type sum = 0;\n count_type matched_count = 0;\n\n ++prefix_sum[0];\n for (auto it = first; it != last; ++it) {\n sum += *it;\n matched_count += prefix_sum[sum - target];\n ++prefix_sum[sum];\n }\n\n return matched_count;\n}\n\ncount_type count_subarrays_matching_sum(const std::vector<element_type> &nums,\n target_type target)\n{\n return count_subarrays_matching_sum(nums.begin(), nums.end(), target);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T11:36:08.770",
"Id": "495534",
"Score": "1",
"body": "You might want to add something about `std::span` to your types part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T11:57:20.440",
"Id": "495537",
"Score": "2",
"body": "I hadn't even considered `std::span`, and I don't actually see where one would be useful here. What were you suggesting? As an alternative to the `std::vector` of inputs? If so, then it probably belongs in the \"Generic interface\" section instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T12:01:14.010",
"Id": "495539",
"Score": "1",
"body": "Yes, that's the better place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T12:06:14.557",
"Id": "495541",
"Score": "1",
"body": "Probably not a good choice for the interface: einpoklem [recommends](//stackoverflow.com/a/45723820/4850040) \"_Don't use it in code that could just take any pair of start & end iterators, like `std::sort`, `std::find_if`, `std::copy` and all of those super-generic templated functions._\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T12:13:11.560",
"Id": "495542",
"Score": "1",
"body": "If you want to template it, sure. But that would be an additional step further."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T09:52:57.877",
"Id": "251646",
"ParentId": "243843",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243861",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T04:25:39.557",
"Id": "243843",
"Score": "1",
"Tags": [
"java",
"c++",
"beginner",
"algorithm"
],
"Title": "LeetCode 560: Subarray Sum Equals K - C++/Java"
}
|
243843
|
<p>What I want is to do is to extract min/max range of salary from a text which contains either hourly or annual salary.</p>
<pre><code>import re
# either of the following inputs should work
input1 = "$80,000 - $90,000 per annum"
input2 = "$20 - $24.99 per hour"
salary_text = re.findall("[<span class="math-container">\$0-9,\. ]*-[\$</span>0-9,\. ]*", input1)
if salary_text and salary_text[0]:
range_list = re.split("-", salary_text[0])
if range_list and len(range_list) == 2:
low = range_list[0].strip(' $').replace(',', '')
high = range_list[1].strip(' $').replace(',', '')
<span class="math-container">````</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T01:47:14.100",
"Id": "478744",
"Score": "1",
"body": "you could create list with inputs `all_examples = [input1, input2]` and run `for input in all_examples:` - this way you can test code with all inputs without changing code. Eventually you could create list with input and expected outputs `all_examples = [(input1, \"80000\", \"90000\"), (input2, \"20\", \"24.99\")]` and automatically check if results are correct `for input, expected_low, expected_hight in all_examples: ... low == expected_low ... high == expected_hight ...`"
}
] |
[
{
"body": "<p>The <code>,</code> commas are a nice twist.\nI feel you are stripping them a bit late,\nas they don't really contribute to the desired solution.\nBetter to lose them from the get go.</p>\n<p>Calling <code>.findall</code> seems to be overkill for your problem specification --\nlikely <code>.search</code> would suffice.</p>\n<blockquote>\n<pre><code>salary_text = re.findall("[<span class=\"math-container\">\\$0-9,\\. ]*-[\\$</span>0-9,\\. ]*", input1)\n</code></pre>\n</blockquote>\n<p>The dollar signs, similarly, do not contribute to the solution,\nyour regex could probably just ignore them if your inputs are fairly sane.\nOr even scan for lines starting with <code>$</code> dollar, and <em>then</em> the regex ignores them.</p>\n<blockquote>\n<pre><code>range_list = re.split("-", salary_text[0])\n</code></pre>\n</blockquote>\n<p>There is no need for this <code>.split</code> -- the regex could have done this for you already.\nHere is what I recommend:</p>\n<pre><code>def find_range(text):\n if text.startswith('$'):\n m = re.search(r'([\\d\\.]+) *- *\\$?([\\d\\.]+)', text.replace(",", ""))\n if m:\n lo, hi = m.groups()\n return float(lo), float(hi)\n return None, None\n\n\nprint(find_range('$80,000 - $90,000 per annum'))\nprint(find_range('$20 - $24.99 per hour'))\n</code></pre>\n<p>The raw string regex <code>r'[\\d\\.]+'</code> picks out one or more numeric characters,\nwhich can include decimal point.\nAnd putting <code>(</code> <code>)</code> parens around a regex makes it a capturing group --\nwe have two such groups here.\nFinally, <code> *- *\\$?</code> lets us skip a single <code>-</code> dash with optional whitespace\nand at most one optional <code>$</code> dollar sign.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T21:54:28.997",
"Id": "479029",
"Score": "0",
"body": "Thanks a lot, this is an excellent solution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T02:41:23.467",
"Id": "243890",
"ParentId": "243846",
"Score": "3"
}
},
{
"body": "<h2>Good job</h2>\n<p>And there is already a good answer <a href=\"https://codereview.stackexchange.com/q/243846/190910\">here</a>!</p>\n<p>I'm only commenting on your regular expression, even though I'm not so sure how your input ranges may look like. But, it would probably miss some edge cases. I'm assuming that these are all acceptable:</p>\n<pre><code>$80,000,000,000.00 - $90,000,000,000.00 per annum\n$80,000,000 - $90,000,000 per annum\n$80,000 - $90,000 per annum\n$20 - $24.99 per hour\n $20 - $24.99 per hour\n$20 - $24.99 per hour\n $20.00 - $24.99 per hour\n</code></pre>\n<p>and these are unacceptable:</p>\n<pre><code> $20.00 - $24.99 per day\n $111,120.00 - $11,124.99 per week\n $111,222,120.00 - $111,111,124.99 per month\n</code></pre>\n<p>You can see your own expression in this link:</p>\n<h2><a href=\"https://regex101.com/r/uDc4dd/1/\" rel=\"nofollow noreferrer\">Demo</a></h2>\n<ul>\n<li>It would pass some cases that may not be desired, I guess.</li>\n<li>You also do not need to escape <code>.</code> and <code>$</code> inside a character class:</li>\n</ul>\n<h2><a href=\"https://regex101.com/r/fYQ3Bz/1/\" rel=\"nofollow noreferrer\">Demo</a></h2>\n<h3>Code</h3>\n<pre><code>import re\n\ndef find_range(text: str) -> dict:\n expression = r'^\\s*<span class=\"math-container\">\\$([0-9]{1,3}(?:,[0-9]{1,3})*(?:\\.[0-9]{1,2})?)\\s*-\\s*\\$</span>([0-9]{1,3}(?:,[0-9]{1,3})*(?:\\.[0-9]{1,2})?)\\s*per\\s+(?:annum|hour)\\s*$'\n return re.findall(expression, text)\n\n\ninput_a = '$80,000 - $90,000 per annum'\ninput_b = '$20 - $24.99 per hour'\nprint(find_range(input_a))\n\n</code></pre>\n<hr />\n<p>If you wish to simplify/update/explore the expression, it's been explained on the top right panel of <a href=\"https://regex101.com/r/n2UdOg/1/\" rel=\"nofollow noreferrer\">regex101.com</a>. You can watch the matching steps or modify them in <a href=\"https://regex101.com/r/n2UdOg/1/debugger\" rel=\"nofollow noreferrer\">this debugger link</a>, if you'd be interested. The debugger demonstrates that how <a href=\"https://en.wikipedia.org/wiki/Comparison_of_regular_expression_engines\" rel=\"nofollow noreferrer\">a RegEx engine</a> might step by step consume some sample input strings and would perform the matching process.</p>\n<hr />\n<h3>RegEx Circuit</h3>\n<p><a href=\"https://jex.im/regulex/#!flags=&re=%5E(a%7Cb)*%3F%24\" rel=\"nofollow noreferrer\">jex.im</a> visualizes regular expressions:</p>\n<p><a href=\"https://i.stack.imgur.com/4atKk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4atKk.png\" alt=\"enter image description here\" /></a></p>\n<h2><a href=\"https://regex101.com/r/UREOgi/1/\" rel=\"nofollow noreferrer\">Demo</a></h2>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T11:10:04.087",
"Id": "478970",
"Score": "1",
"body": "Thanks for this, especially those corner cases are very good points."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T03:08:50.320",
"Id": "243891",
"ParentId": "243846",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243890",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T08:52:53.297",
"Id": "243846",
"Score": "2",
"Tags": [
"python",
"regex"
],
"Title": "Extracting min and max salary from string"
}
|
243846
|
<p>Write a function that takes an array of integers (Both Positive and negative) and return the maximum sum of non adjacent elements. Note that even if all values are negative, I don't have an option to choose empty subset and return sum as 0.</p>
<p>Recursive solution that I wrote:</p>
<pre><code>public static int maxSubsetSumNoAdjacent(int[] array) {
if (array.length == 0) return 0;
else if (array.length == 1) return array[0];
else if (array.length == 2) return Math.max(array[0], array[1]);
return Math.max(
array[0] + maxSubsetSumNoAdjacent(Arrays.copyOfRange(array, 2, array.length)),
array[1] + maxSubsetSumNoAdjacent(Arrays.copyOfRange(array, 3, array.length))
);
}
</code></pre>
<p>The recursive solution works. I've tried an iterative solution, but that didn't work.</p>
<p>Test cases</p>
<p>Positive Numbers:</p>
<blockquote>
<p>75, 105, 120, 75, 90, 135<br />
Ans : 330 (75 + 120 + 135)</p>
</blockquote>
<p>Negative Numbers:</p>
<blockquote>
<p>-1, -10, -10, -1, -2<br />
Ans: -2 (-1 + -1)</p>
</blockquote>
<p>I'd like a review of the code provided.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T13:54:58.170",
"Id": "478676",
"Score": "1",
"body": "`But the iterative solution does not work for negative numbers`\n\nHello, the second snippet is off-topic, since the code is not working as intended; I suggest that you read the [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic) `Code Review aims to help improve working code. If you are trying to figure out why your program crashes or produces a wrong result, ask on Stack Overflow instead. Code Review is also not the place to ask for implementing new features.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T04:47:10.457",
"Id": "478754",
"Score": "0",
"body": "You said you cannot choose empty subset. But in your negative numbers example you dont choose 1 element subset either. Shouldn't the answer be -1? Or effectively minimum input size is 3? But that doesnt seem to correspond with your code, where you return greater of the two elements if array length is 2."
}
] |
[
{
"body": "<p>Many folks find that tacking on <code>{</code> <code>}</code> braces\nto even a single-line <code>if</code> body is a useful way of preventing future bugs.</p>\n<hr />\n<p>You wrote:</p>\n<blockquote>\n<pre><code> array[0] + maxSubsetSumNoAdjacent(Arrays.copyOfRange(array, 2, array.length)),\n array[1] + maxSubsetSumNoAdjacent(Arrays.copyOfRange(array, 3, array.length))\n</code></pre>\n</blockquote>\n<p>The pair of copy statements is wasteful.\nYou're allocating temp storage (for GC to collect)\nand consuming memory bandwidth.\nIt turns what <em>could</em> be a linear algorithm into a quadratic one (O(n) → O(n^2)).</p>\n<p>The caller is going to simply hand you an array,\nso you <em>have</em> to conform to that public API, accepting a single argument.\nBut nothing stops you from overloading, from writing a private helper.\nYour public function should immediately ask the helper about the array,\nfrom index <code>0</code> onward to end of array.\nThen all the work happens in the helper.</p>\n<p>Note that recursive calls that pass array plus a starting index\nwill never <strong>copy</strong> the array.\nThey merely pass a pointer to start of original array, in O(1) time,\nindependent of how enormous that array happens to be.</p>\n<p>You have an opportunity to dramatically improve the implemented algorithm,\nby passing index to the "as yet unsolved" portion of the array.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T04:54:40.600",
"Id": "478755",
"Score": "0",
"body": "That's a good point. didn't thought of cost associated with array copy."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T02:15:33.817",
"Id": "243889",
"ParentId": "243847",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243889",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T09:14:20.807",
"Id": "243847",
"Score": "1",
"Tags": [
"java",
"dynamic-programming"
],
"Title": "Maximum subset sum with no adjacent elements"
}
|
243847
|
<p>I have created an simple elevator design for 100 floors building with just one elevator.</p>
<p>I have dependency between classes which I want to eliminate, any thoughts/suggestion to make it more better in-terms of SOLID principles?</p>
<p>I have created following set of classes and detailed their purpose</p>
<p><code>class Request</code>: This holds all the request made from the 'floor' keypad and inside the keypad. 'm_floor' represent the floor to which Elevator need to travel i.e. If floor keypad pressed from 7th floor then m_floor set as 7.</p>
<p><code>m_direction</code> represent the DIrection in which lift need to travel after boarding. That means 0th floor can have Direction as 'UP' only and 100th floor can have direction 'DOWN' only</p>
<p><code>class RequestData</code>: Holds all the previous request made and stored in down or up queue based on the intended direction to go.</p>
<p>...</p>
<pre><code>#pragma once
#include<queue>
#include<memory>
#include<chrono>
#include<mutex>
#include <fstream>
#include <sstream>
#include <iostream>
#include <thread>
using namespace std::chrono;
std::mutex mu;
std::condition_variable cond;
constexpr int MAX_REQ_SIZE = 100;
enum class Direction {
UP, DOWN
};
enum class State {
MOVING, STOPPED
};
enum class Door {
OPEN, CLOSED
};
class Request
{
public:
milliseconds m_time;
int m_floor;
Direction m_direction;
Request(const Request&) = default;
Request& operator=(const Request&) = default;
Request(milliseconds time, int floor, Direction direction)
{
m_time = time;
m_floor = floor;
m_direction = direction;
}
};
using UNIQUE_REQ = std::shared_ptr<Request>;
struct UpComparator {
bool operator()(UNIQUE_REQ r1, UNIQUE_REQ r2)
{
// return "true" if r1 floor value is less than r2
return r1->m_floor < r2->m_floor;
}
};
struct DownComparator {
bool operator()(UNIQUE_REQ r1, UNIQUE_REQ r2)
{
// return "true" if r1 floor value greater than r2
return r1->m_floor > r2->m_floor;
}
};
class RequestData
{
public:
void AddToDownQueu(UNIQUE_REQ req)
{
downQueue.emplace(req);
if (down_request_time == milliseconds::zero())
{
down_request_time = req->m_time;
}
}
void AddToUpQueu(UNIQUE_REQ req)
{
upQueue.emplace(req);
if (up_request_time == milliseconds::zero())
{
up_request_time = req->m_time;
}
}
milliseconds up_request_time{ milliseconds::zero() };
milliseconds down_request_time{ milliseconds::zero() };
std::priority_queue<UNIQUE_REQ, std::vector<UNIQUE_REQ>, UpComparator> upQueue;
std::priority_queue<UNIQUE_REQ, std::vector<UNIQUE_REQ>, DownComparator> downQueue;
};
class ElevatorStatus
{
public:
State m_elevator_state{ State::STOPPED };
Door m_door_state{Door::CLOSED};
Direction m_current_direction{ Direction::UP };
std::queue<UNIQUE_REQ> m_current_queue;
float m_current_location{ 0 };
};
class ElevatorProcessor
{
public:
ElevatorProcessor() : m_request_data{ std::make_unique<RequestData>() },
current_elevator_status{ std::make_unique<ElevatorStatus>() }
{
}
void ProcessCurrentRequests()
{
while (true)
{
std::unique_lock<std::mutex> locker(mu);
cond.wait(locker, [this]() {return (!current_elevator_status->m_current_queue.empty() ||
!m_request_data->upQueue.empty() ||
!m_request_data->downQueue.empty()); });
if (!current_elevator_status->m_current_queue.empty())
{
auto r = current_elevator_status->m_current_queue.front();
goToFloor(r->m_floor);
current_elevator_status->m_current_queue.pop();
}
else
{
preProcessNextQueue();
}
}
}
std::unique_ptr<RequestData> m_request_data;
std::unique_ptr<ElevatorStatus> current_elevator_status;
private:
void goToFloor(int floor) {
std::cout << "Navigating to the floor: " << floor << std::endl;
current_elevator_status->m_elevator_state = State::MOVING;
for (float i = current_elevator_status->m_current_location;
i <= floor; i = (float)(i + 0.1))
{
std::this_thread::sleep_for(0.02s);
}
current_elevator_status->m_current_location = floor;
current_elevator_status->m_door_state = Door::OPEN;
current_elevator_status->m_elevator_state = State::STOPPED;
std::this_thread::sleep_for(5s);
current_elevator_status->m_door_state = Door::CLOSED;
}
void preProcessNextQueue()
{
if (m_request_data->up_request_time > m_request_data->down_request_time)
{
current_elevator_status->m_current_direction = Direction::UP;
while (!m_request_data->upQueue.empty())
{
current_elevator_status->m_current_queue.push(m_request_data->upQueue.top());
m_request_data->upQueue.pop();
}
m_request_data->up_request_time = milliseconds::zero();
}
else
{
current_elevator_status->m_current_direction = Direction::DOWN;
while (!m_request_data->downQueue.empty())
{
current_elevator_status->m_current_queue.push(m_request_data->downQueue.top());
m_request_data->downQueue.pop();
}
m_request_data->down_request_time = milliseconds::zero();
}
}
};
class ElevatorUser
{
public:
ElevatorUser(std::shared_ptr<ElevatorProcessor> proc) :m_elevator_proc{ proc }
{
}
void ReadInputData(const std::string filepath)
{
std::string line{};
std::ifstream infile(filepath);
while (std::getline(infile, line))
{
std::istringstream iss(line);
int floor;
std::string str_direction;
if (!(iss >> floor >> str_direction)) { break; } // error
Direction dir = (str_direction == "up") ? Direction::UP : Direction::DOWN;
if (dir == Direction::UP)
{
std::cout << "Placing reuest for goin UP to floor: " << floor << std::endl;
}
else
{
std::cout << "Placing reuest for goin DOWN to floor: " << floor << std::endl;
}
call(floor, dir);
std::this_thread::sleep_for(1s);
}
}
private:
void call(int to_floor, Direction direction)
{
std::unique_lock<std::mutex> locker(mu);
cond.wait(locker, [this]() {return m_elevator_proc->current_elevator_status->m_current_queue.size() < MAX_REQ_SIZE; });
milliseconds current_time = duration_cast<milliseconds>(
system_clock::now().time_since_epoch());
UNIQUE_REQ new_req = std::make_shared<Request>(current_time, to_floor, direction);
if (direction == Direction::UP)
{
if (to_floor >= m_elevator_proc->current_elevator_status->m_current_location)
{
m_elevator_proc->current_elevator_status->m_current_queue.emplace(new_req);
}
else
{
m_elevator_proc->m_request_data->AddToUpQueu(new_req);
}
}
else
{
if (to_floor <= m_elevator_proc->current_elevator_status->m_current_location)
{
m_elevator_proc->current_elevator_status->m_current_queue.emplace(new_req);
}
else
{
m_elevator_proc->m_request_data->AddToDownQueu(new_req);
}
}
locker.unlock();
cond.notify_one();
}
std::shared_ptr<ElevatorProcessor> m_elevator_proc;
};
int main(void)
{
std::shared_ptr<ElevatorProcessor> elevator_proc = std::make_shared<ElevatorProcessor>();
std::unique_ptr<ElevatorUser> elevator_user = std::make_unique<ElevatorUser>(elevator_proc);
const std::string path = "D:\\hacker_input\\elevator_input.txt";
std::thread t1(&ElevatorUser::ReadInputData, elevator_user.get(), path);
std::thread t2(&ElevatorProcessor::ProcessCurrentRequests, elevator_proc.get());
t1.join();
t2.join();
return 0;
}
</code></pre>
<p>...</p>
|
[] |
[
{
"body": "<p>I see some things that may help you improve your program.</p>\n<h2>Don't use <code>#pragma once</code></h2>\n<p>The use of <code>#pragma once</code> is a common extension, but it's not in the standard and thus represents at least a potential portability problem. It's also completely unnecessary in a <code>.cpp</code> file. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf8-use-include-guards-for-all-h-files\" rel=\"nofollow noreferrer\">SF.8</a></p>\n<h2>Use the required <code>#include</code>s</h2>\n<p>The code uses <code>std::condition_variable</code> which means that it should <code>#include <condition_variable></code>. It was not difficult to infer, but it helps reviewers if the code is complete.</p>\n<h2>Use consistent formatting</h2>\n<p>The code as posted has inconsistent spacing for the <code>#include</code> files. Most people find the version with a space to be more easily readable. Pick a style and apply it consistently.</p>\n<h2>Don't hardcode file names</h2>\n<p>Generally, it's not a good idea to hardcode a file name in software, and generally especially bad if it's an absolute file name (as contrasted with one with a relative path). Instead, it would be better to allow the user of the program to specify the name, as with a command line parameter.</p>\n<h2>Don't use std::endl unless you really need to flush the stream</h2>\n<p>The difference between <code>std::endl</code> and <code>'\\n'</code> is that <code>std::endl</code> actually flushes the stream. This can be a costly operation in terms of processing time, so it's best to get in the habit of only using it when flushing the stream is actually required. It's not for this code.</p>\n<h2>Separate interface from implementation</h2>\n<p>It makes the code somewhat longer for a code review, but it's often very useful to separate the interface from the implementation. In C++, this is usually done by putting the interface into separate <code>.h</code> files and the corresponding implementation into <code>.cpp</code> files. It helps users (or reviewers) of the code see and understand the interface and hides implementation details. The other important reason is that you might have multiple source files including the <code>.h</code> file but only one instance of the corresponding <code>.cpp</code> file. In other words, split your existing <code>.h</code> file into a <code>.h</code> file and a <code>.cpp</code> file.</p>\n<h2>Fix spelling errors</h2>\n<p>The code has <code>AddToUpQueu()</code> instead of <code>AddToUpQueue()</code> and <code>"Placing reuest for goin UP to floor: "</code> instead of <code>"Placing request for going UP to floor: "</code>. These kinds of typos don't bother the compiler at all, but they will bother human readers of the code and human users of the code and make it a little more difficult to understand and maintain.</p>\n<h2>Gracefully exit the program</h2>\n<p>Right now, the program has no way to end. That's not a good design. Instead, consider some special values such as "9999 quit" that would signal to both threads that it's time to end.</p>\n<h2>Remember to lock all shared resources</h2>\n<p>There are calls to print on <code>std::cout</code> from both threads without any locks. This means that output could be interleaved. Instead, I'd recommend either using the C++20 <code>std::osyncstream</code> or create your own as in <a href=\"https://codereview.stackexchange.com/questions/243640/multithreaded-console-based-monster-battle-with-earliest-deadline-first-schedule\">Multithreaded console-based monster battle with earliest-deadline-first scheduler</a></p>\n<h2>Don't abuse pointers</h2>\n<p>There is an abundance of <code>std::shared_ptr</code> and <code>std::unique_ptr</code> which is dubious. For example, there is no reason that the <code>elevator_user</code> in <code>main</code> shouldn't simply be this:</p>\n<pre><code>ElevatorUser elevator_user{elevator_proc};\nstd::thread t1(&ElevatorUser::ReadInputData, std::ref(elevator_user), path);\n</code></pre>\n<p>Similarly, within <code>class ElevatorProcessor</code> the member variables don't need to be <code>std::unique_ptr</code>. They should just be simple variables.</p>\n<h2>Rethink the class design</h2>\n<p>Having all data members of the <code>ElevatorProcessor</code> class as public should be a red flag that causes you to re-examine the class design. In real life an <code>ElevatorUser</code> has no view into the state of an elevator processor except indicators to show what floors the elevators are on. The user makes a request and it's up to the processor, not the user, to figure out how to act on that request. Also, why is there a separate <code>ElevatorStatus</code> class when this information could simply be put into the <code>ElevatorProcessor</code> class? Also, it seems to me that <code>ElevatorProcessor</code> could and should be named <code>Elevator</code> instead, unless you are planning to have multiple elevators being controlled by a single <code>ElevatorProcessor</code>.</p>\n<p>Also, the way the code is currently written, the user is synchronized to the elevator and requests are made no more often than once every 5 seconds. That's an inaccurate use of threads. What should happen instead is that the <code>ElevatorProcessor</code> class should not sleep at all so that it can instantly respond to a button press, but keep track of where the elevator is at any instant of time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T16:51:31.123",
"Id": "480020",
"Score": "0",
"body": "Hi Edward, Thanks for detailed review. I will work on it and re-submit the code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T14:19:39.903",
"Id": "243863",
"ParentId": "243848",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T09:45:30.283",
"Id": "243848",
"Score": "7",
"Tags": [
"c++",
"multithreading",
"design-patterns"
],
"Title": "Design elevator to get user commands and execute request based on current elevator moving direction (UP/Down)"
}
|
243848
|
<p>I believe I'm writing in the correct place. However, I'm not fully sure, and I am relatively new to Stack Exchange. If it is not, and can be moved by an admin/moderator in the correct place, please do so. Or else let me know where and why, and I'll fix it.</p>
<p>PS: Sorry for any grammar mistakes. I'm a dad of a newborn. So my time is all over the place.</p>
<p>Since I'm an amateur programmer, learning MEAN stack by my self, I've concluded that the best way to exercise vanilla CSS is by cloning stuff on Pinterest. Bare in mind that this is my first true exercise (actually a problem, not exercise, since I had to wrap my hand around it, not just practice).</p>
<p>About 2 weeks ago I started to clone the image linked below. I've done that whenever a I had some spare time, either if I had a PC at hand, or just doing it on my phone or tablet.</p>
<p>Although I haven't managed to clone it 100%, I'd say it's at least 95% successfully. What I'd love and appreciate are reviews for my efort as well as advices for future implementations of methodology and techniques.</p>
<p>I don't have a specific question, as I'm sure anything from within my code could have been done better, so feel free to jump on anything.</p>
<p>However, I've like to point out a few difficulties I had:</p>
<ul>
<li>The "pillars" of light have been a particular pain. It took me at least 50% of the time invested. That is because, as you can see, the margins of the pillars have a specific shape that widens at the ends. I've tried SVG, but learned that I had to drop shadows in HTML for them, as the box-shadow property or drop-shadow filter do not work on SVGs. I've tried the html code for SVG shadows, but gave up on it since I decided I should use the div box-shadow split between more parts (up, mid and down parts). Then I had issues with the shadows spaning on the other parts, but fixed them with propper x-y positioning.</li>
<li>The "item" circular shape was a problem as well. I've tried linear gradient border with another specific shaped div, but the transition between the 2 were rough. So I've ended up using only 1 shaped din, but with 2 radial gradients. I know there should be more work on the orange gradient, since is not that luminous as in the pinterest image, but I'm out of options.</li>
</ul>
<p>Exercise source:
<a href="https://ro.pinterest.com/pin/784470828832524047/" rel="nofollow noreferrer">https://ro.pinterest.com/pin/784470828832524047/</a></p>
<p>Resulted code:
<a href="https://jsitor.com/i5iAlhRIC" rel="nofollow noreferrer">https://jsitor.com/i5iAlhRIC</a></p>
<p>HTML:</p>
<pre><code><head>
<title>ABE1</title>
</code></pre>
<pre><code><body>
<article id="bgSpace">
<div class="overlay"></div>
<section id="bgGround" class="bgSpace__member ground">
<div class="bgMember__ground__texture">
<div class="pin"></div>
</div>
</section>
<section id="bgFloor" class="bgSpace__member floor">
<div class="bgMember__floor__left">
<div class="delimiter_left"></div>
<div class="pillars"></div>
<div class="dip ld">
<div class="liner liner_left">
<div class="liner-up left"></div>
<div class="liner-mid left"></div>
<div class="liner-down left"></div>
</div>
<div class="liner liner_right">
<div class="liner-up right"></div>
<div class="liner-mid right"></div>
<div class="liner-down right"></div>
</div>
</div>
</div>
<div class="bgMember__floor__right">
<div class="delimiter_right"></div>
<div class="pillars"></div>
<div class="dip rd">
<div class="liner liner_left">
<div class="liner-up left"></div>
<div class="liner-mid left"></div>
<div class="liner-down left"></div>
</div>
<div class="liner liner_right">
<div class="liner-up right"></div>
<div class="liner-mid right"></div>
<div class="liner-down right"></div>
</div>
</div>
</div>
</section>
<section id="bgItem" class="bgSpace__member item">
<div class="bgMember__item__field"></div>
</section>
</article>
</body>
</code></pre>
<p>CSS:</p>
<pre><code>body {
margin: 0;
box-sizing: border-box;
width: 100vw;
height: calc(100vw * 1.65);
--pillar_color_line: rgba(255, 140, 0, 1);
--pillar_color_rod: rgba(255, 165, 0, 1);
--pillar_color_ray: rgba(255,140,0,1);
--dip_rays: rgba(255,110,0,1);
--pillars_position: 20%;
--viewport: 100vw;
--pillars__effect_size_ref: calc(var(--viewport) * 0.33 / 71.28);
--refwidth: var(--pillars__effect_size_ref);
--bg_color: rgba(73,73,73, 1);
}
/* Used for overall vignete effect */
.overlay {
width: 100%;
height: 100%;
z-index: 2;
position: absolute;
top: 0;
background-image: radial-gradient(circle closest-corner at center, rgba(255,255,255,0) 70%, rgba(0,0,0,1) 100%);
}
/*_______*/
/* Everything is split in 3 major layers:
- First is the #bgGround, the most basal, as the name suggests;
- Second is the #bgFloor, and consists of the 2 rectangles of 90% height on each side of the bg;
- the light Pillars ar in it, with relative-absolute positioning
- Third is the bgItem, and is the circular shape at the center of it.
- this was second in effort after the pillars, since I had to learn the hard way how to use radial gradient borders. Had 2 circular "items" for that. But ended up with 1 item with 2 bg-image properties due to technical limitations in the radial border technique.
*/
/* Overal measurements of the bg - bgSpace */
#bgSpace {
margin: 0;
width: 100vw;
height: calc(100vw * 1.65);
position: relative;
}
/*___*/
/* 1st layer - bgGround */
.bgMember__ground__texture {
position: absolute;
margin: 0;
height: 100%;
width: 100%;
background-image: radial-gradient(ellipse farthest-corner at center, rgba(73,73,73,1) 0%, rgba(0,0,0,1) 100%);
}
.pin {
width: 0%;
height: 50%;
z-index: 0;
position: absolute;
top: 26%;
left: 50%;
display: flex;
justify-content: center;
align-items: center;
box-shadow: 0 0
calc(var(--refwidth) * 50)
calc(var(--refwidth) * 40)
black;
}
/*___*/
/* 2nd layer - bgFloor, with pillars */
.bgMember__floor__left {
position: absolute;
left: 0;
width: 33%;
height: 90%;
margin-top: calc(10% - 5px);
box-shadow: calc(var(--refwidth) * 30) 0 calc(var(--refwidth) * 35) calc(0px - var(--refwidth) * 20);
}
.delimiter_left, .delimiter_right {
position: absolute;
right: 0;
width: 5px;
height: 100%;
background-color: var(--bg_color);
border-radius: 100% 100%;
}
.delimiter_right {
left: 0;
}
.bgMember__floor__right {
position: absolute;
right: 0;
height: 90%;
width: 33%;
margin-top: calc(10% - 5px);
box-shadow: calc(0px - var(--refwidth) * 30) 0 calc(var(--refwidth) * 35) calc(0px - var(--refwidth) * 20);
}
/* Pillars */
/* - Pillar Lighting-Shadows Layout */
.bgMember__floor__left > .pillars{
right: var(--pillars_position);
}
.bgMember__floor__right > .pillars{
left: var(--pillars_position);
}
.pillars {
position: absolute;
height: 100%;
width: calc(var(--refwidth) * 2);
box-shadow:
inset
0 0 calc(var(--refwidth) * 5)
calc(var(--refwidth) * 2)
var(--pillar_color_rod),
0 0 calc(var(--refwidth) * 3)
calc(var(--refwidth) * 2)
var(--pillar_color_rod),
0 0 calc(var(--refwidth) * 2)
calc(var(--refwidth) * 1)
var(--pillar_color_rod);
border-radius: 50% 50%;
filter: drop-shadow(0px 0px calc(var(--pillars__effect_size_ref) * 3) var(--pillar_color_line));
}
.dip {
width: 43%;
right: 0;
height: 100%;
overflow: hidden;
}
.ld{
position: absolute;
right: 0;
height: 100%;
}
.rd {
position: absolute;
left: 0;
height: 100%;
}
/*_____*/
/* Liners - the transparent shapes required for the rays inside the pillars */
/* Liner Shadows */
.liner-up.left, .liner-mid.left, .liner-down.left {
box-shadow: calc(var(--refwidth) * 6)
0px
calc(var(--refwidth) * 6)
var(--dip_rays);
overflow: hidden;
}
.liner-up.right, .liner-mid.right, .liner-down.right {
box-shadow: calc(0px - var(--refwidth) * 6)
0px
calc(var(--refwidth) * 6)
var(--dip_rays);
overflow: hidden;
}
/*___*/
/* Liners - General */
.liner {
width: 50%;
height: 100%;
}
.liner-up {
width: 10%;
height: 20%;
}
.liner-mid {
top: 20%;
width: 10%;
height: 60%;
}
.liner-down {
top: 80%;
width: 10%;
height: 20%;
}
/*___*/
/* Liner - Left */
.liner-left {
position: absolute;
left: 0;
}
.liner-up.left {
position: absolute;
left: 0;
border-radius: 0 100% 0 0;
}
.liner-mid.left {
position: absolute;
left: 0;
}
.liner-down.left {
position: absolute;
left: 0;
border-radius: 0 0 100% 0;
}
/*___*/
/* Liner - Right */
.liner-right {
position: absolute;
right: 0;
}
.liner-up.right {
position: absolute;
right: calc(0px - var(--refwidth) * 0);
top: 0;
border-radius: 100% 0 0 0;
}
.liner-mid.right {
position: absolute;
right: 0;
}
.liner-down.right {
position: absolute;
right: 0;
border-radius: 0 0 0 100%;
}
/*___*/
/*_____*/
/*_______*/
/*_________*/
/* 3rd layer - bgItem */
.item {
height: 100%;
position: relative;
z-index: initial;
}
.bgMember__item__field {
height: auto;
width: 80%;
left: 10%;
top: 25%;
position: absolute;
padding-top: 80%;
border-radius: 50%;
z-index: 3;
background-image: radial-gradient(100% 95% at center, rgba(0,0,0,0) 51%, rgba(255,170,0,1) 52.5%),
radial-gradient(100% 90% at left, rgba(73,73,73, 1) 0%, rgba(0,0,0, 1) 95%);
box-shadow: calc(0px - var(--refwidth) * 8) 0 calc(var(--refwidth) * 10) calc(var(--refwidth) * 0);
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p><strong>First</strong><br />\nYou need beautify your html and css code, you can do this manually, or use extensions of vscode like: Beautify from HookyQR.<br />\n<a href=\"https://marketplace.visualstudio.com/items?itemName=HookyQR.beautify\" rel=\"nofollow noreferrer\">This is link of HookyQR</a></p>\n<p><strong>second</strong><br />\nBro, in your css code, it is better that you follow the law of parenthood and child and write as father and child in your css.<br />\nfor example for one of them i can write for you:</p>\n<pre><code>#bgSpace .bgSpace__member item .bgMember__item__field {\n height: auto;\n width: 80%;\n left: 10%;\n top: 25%;\n position: absolute;\n padding-top: 80%;\n border-radius: 50%;\n z-index: 3;\n background-image: radial-gradient(100% 95% at center, rgba(0,0,0,0) 51%, rgba(255,170,0,1) 52.5%), \n radial-gradient(100% 90% at left, rgba(73,73,73, 1) 0%, rgba(0,0,0, 1) 95%);\n box-shadow: calc(0px - var(--refwidth) * 8) 0 calc(var(--refwidth) * 10) calc(var(--refwidth) * 0);\n}\n</code></pre>\n<p>You should write all of your css like above.</p>\n<p><strong>Important note</strong></p>\n<p>If you want use id and class or css selector together in your code, you have to learn about cascade and inheritance in css, or you will run into cascade and inheritance problems, because you did not read about them but used them.<br />\n<a href=\"https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance\" rel=\"nofollow noreferrer\">This is link of cascade and inheritanc</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T13:02:40.453",
"Id": "488617",
"Score": "0",
"body": "Your second suggestion is in direct violation of [BEM](http://getbem.com/naming/), which protoCoding is obviously implementing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-15T12:58:59.547",
"Id": "488814",
"Score": "0",
"body": "Not exactly, but yes, I talked about the structure and architecture of CSS, but very basic"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T09:10:05.757",
"Id": "247888",
"ParentId": "243849",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T09:48:59.737",
"Id": "243849",
"Score": "4",
"Tags": [
"css"
],
"Title": "CSS exercise of cloning background image"
}
|
243849
|
<p>I would like to obtain some feedback on a simple code I wrote to
implement an easy and hopefully fast way to generate a large number of floats
with CURAND and use them one at a time.</p>
<p>This is achieved by switching between two large buffers that get generated and copied onto host memory asyncronously while the other buffer is used by the main program.</p>
<p>I tried to implement a naive lock system in order to ensure that the buffers may get reused only when they have been filled by newly generated numbers.</p>
<p>The code seems to work, but at the present stage I am not convinced about the performance of it, with particular emphasis on the <code>getrandom</code> function, which in my original intent was meant to be extremely fast 99,9999% of the time when no generation has to be started.</p>
<pre><code>#include <cuda.h>
#include <curand.h>
#include "threads.h"
#define CUDA_CALL(x) do { if((x)!=cudaSuccess) { \
printf("Error at %s:%d\n",__FILE__ ,__LINE__);\
return EXIT_FAILURE ;}} while (0)
#define CURAND_CALL(x) do { if((x)!=CURAND_STATUS_SUCCESS) { \
printf("Error at %s:%d\n",__FILE__ ,__LINE__);\
return EXIT_FAILURE ;}} while (0)
// 123456789 -> 4 bytes -> 4 gigabytes
#define bufsize 1000000000ul
thrd_t thrd[2];
int* foo;
float *devbuff , *hostbuffONE, *hostbuffTWO;
size_t i;
curandGenerator_t gen;
int currentbuffer; // 1 -> buffONE, 2 -> buffTWO
unsigned long int counter=1;
int lock=0;
int genONE(void* arg);
int genONE(void* arg)
{
CURAND_CALL(curandGenerateUniform(gen, devbuff, bufsize));
CUDA_CALL(cudaMemcpy(hostbuffONE , devbuff , bufsize*sizeof(float),cudaMemcpyDeviceToHost));
lock=0;
return(0);
}
int genTWO(void* arg);
int genTWO(void* arg)
{
CURAND_CALL(curandGenerateUniform(gen, devbuff, bufsize));
CUDA_CALL(cudaMemcpy(hostbuffTWO , devbuff , bufsize*sizeof(float),cudaMemcpyDeviceToHost));
lock=0;
return(0);
}
static inline float getrandom();
float getrandom()
{
switch (currentbuffer)
{
case 1:
if (counter==bufsize-1)
{
currentbuffer=2;
if (lock==0)
{
lock=1;
thrd_create(&thrd[0], genONE, foo);
}
else
{
// wait for lock release
// on thread 2
thrd_join(thrd[1], 0);
lock=1;
thrd_create(&thrd[0], genONE, foo);
}
counter=1;
return(hostbuffTWO[0]);
}
else{
counter++;
return(hostbuffONE[counter]);
}
default:
if (counter==bufsize-1)
{
currentbuffer=1;
if (lock==0)
{
lock=1;
thrd_create(&thrd[1], genTWO, 0);
}
else
{
// wait for lock release
// on thread 1
thrd_join(thrd[0], 0);
lock=1;
thrd_create(&thrd[1], genTWO, 0);
}
counter=1;
return(hostbuffONE[0]);
}
else{
counter++;
return(hostbuffTWO[counter]);
}
}
}
int main(){
CURAND_CALL(curandCreateGenerator(&gen,CURAND_RNG_PSEUDO_DEFAULT));
CURAND_CALL(curandSetPseudoRandomGeneratorSeed(gen,1234ULL));
CUDA_CALL(cudaMallocHost((void **)&hostbuffONE, bufsize*sizeof(float)));
CUDA_CALL(cudaMallocHost((void **)&hostbuffTWO, bufsize*sizeof(float)));
CUDA_CALL(cudaMalloc((void **)&devbuff, bufsize*sizeof(float)));
CURAND_CALL(curandGenerateUniform(gen, devbuff, bufsize));
CUDA_CALL(cudaMemcpy(hostbuffONE , devbuff , bufsize*sizeof(float),cudaMemcpyDeviceToHost));
CURAND_CALL(curandGenerateUniform(gen, devbuff, bufsize));
CUDA_CALL(cudaMemcpy(hostbuffTWO , devbuff , bufsize*sizeof(float),cudaMemcpyDeviceToHost));
currentbuffer=1; counter=0;
unsigned long long int ite;
float useless;
for (ite=0;ite<(10*bufsize);ite++)
{
useless=getrandom();
if (i%1000000000lu==0)
{
//printf("%f\n",useless);
useless=useless-1.0;
}
}
// checks we are out of the generating loops
thrd_join(thrd[1], 0);
thrd_join(thrd[0], 0);
CUDA_CALL(cudaFree(devbuff));
CUDA_CALL(cudaFree(hostbuffONE));
CUDA_CALL(cudaFree(hostbuffTWO));
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-24T09:02:40.487",
"Id": "494127",
"Score": "0",
"body": "May you please format your program in an appropriate way? It makes no joy to look at this. PS why do you use a switch for your `getrandom()`? PPS why are you declaring `int genONE(void* arg);` and `int genTWO(void* arg);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-27T20:26:12.223",
"Id": "494495",
"Score": "0",
"body": "@paladin sorry for getting back to you so late. I have tried my best to reformat the code appearance, but I am not too informed in this subject. I am declaring two functions to separate the generation on the two buffers, but it's not optimal"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T09:58:44.913",
"Id": "243851",
"Score": "3",
"Tags": [
"c",
"random",
"pthreads",
"cuda",
"c11"
],
"Title": "Async generation of large buffers of random numbers on the GPU"
}
|
243851
|
<p>I'm building a platform like Rundeck/AWX but for server reliability testing.</p>
<p>People could log into a web interface upload scripts, run them on servers and get statistics on them ( failure / success).</p>
<p>Each script is made up of three parts, probes to check if the server is fine, methods to do stuff in the server, and rollback to reverse what we did to the server.</p>
<p>First we run the probes, if they past we run the methods, wait a certain time the user that created the method put, then run the probes again to check if the server self healed, if not then we run the rollbacks and probes again, then send the data to the db.</p>
<p>I have limited experience with programming as a job and am very unsure if what I’m doing is good let alone efficient so I would love to get some really harsh criticism.</p>
<p>This is the micro-service that is in charge of running the scripts of the user’s request, it gets a DNS and the fault name (fault is the whole object of probes/methods/rollbacks).</p>
<pre><code>#injector.py
import requests
from time import sleep
import subprocess
import time
import script_manipluator as file_manipulator
class InjectionSlave():
def __init__(self,db_api_url = "http://chaos.db.openshift:5001"):
self.db_api_url = db_api_url
def initiate_fault(self,dns,fault):
return self._orchestrate_injection(dns,fault)
def _orchestrate_injection(self,dns,fault_name):
try :
# Gets fault full information from db
fault_info = self._get_fault_info(fault_name)
except Exception as E :
return { "exit_code":"1" ,"status": "Injector failed gathering facts" }
try :
# Runs the probes,methods and rollbacks by order.
logs_object = self._run_fault(dns, fault_info)
except :
return { "exit_code":"1" ,"status": "Injector failed injecting fault" }
try :
# Sends logs to db to be stored in the "logs" collection
db_response = self._send_result(dns,logs_object,"logs")
return db_response
except Exception as E:
return { "exit_code":"1" ,"status": "Injector failed sending logs to db" }
def _get_fault_info(self,fault_name):
# Get json object for db rest api
db_fault_api_url = "{}/{}/{}".format(self.db_api_url, "fault", fault_name)
fault_info = requests.get(db_fault_api_url).json()
# Get the names of the parts of the fault
probes = fault_info["probes"]
methods = fault_info["methods"]
rollbacks = fault_info["rollbacks"]
name = fault_info["name"]
fault_structure = {'probes' : probes , 'methods' : methods , 'rollbacks' : rollbacks}
# fault_section can be the probes/methods/rollbacks part of the fault
for fault_section in fault_structure.keys():
fault_section_parts = []
# section_part refers to a specific part of the probes/methods/rollbacks
for section_part in fault_structure[fault_section]:
section_part_info = requests.get("{}/{}/{}".format(self.db_api_url,fault_section,section_part)).json()
fault_section_parts.append(section_part_info)
fault_structure[fault_section] = fault_section_parts
fault_structure["name"] = name
return fault_structure
def _run_fault(self,dns,fault_info):
try:
# Gets fault parts from fault_info
fault_name = fault_info['name']
probes = fault_info['probes']
methods = fault_info['methods']
rollbacks = fault_info['rollbacks']
except Exception as E :
logs_object = {'name': "failed_fault" ,'exit_code' : '1' ,
'status' : 'expirement failed because parameters in db were missing ', 'error' : E}
return logs_object
try :
method_logs = {}
rollback_logs = {}
probe_after_method_logs = {}
# Run probes and get logs and final probes result
probes_result,probe_logs = self._run_probes(probes,dns)
# If probes all passed continue
if probes_result is True :
probe_logs['exit_code'] = "0"
probe_logs['status'] = "Probes checked on victim server successfully"
# Run methods and get logs and how much time to wait until checking self recovery
methods_wait_time, method_logs = self._run_methods(methods, dns)
# Wait the expected recovery wait time
sleep(methods_wait_time)
probes_result, probe_after_method_logs = self._run_probes(probes, dns)
# Check if server self healed after injection
if probes_result is True:
probe_after_method_logs['exit_code'] = "0"
probe_after_method_logs['status'] = "victim succsessfully self healed after injection"
else:
probe_after_method_logs['exit_code'] = "1"
probe_after_method_logs['status'] = "victim failed self healing after injection"
# If server didnt self heal run rollbacks
for rollback in rollbacks:
part_name = rollback['name']
part_log = self._run_fault_part(rollback, dns)
rollback_logs[part_name] = part_log
sleep(methods_wait_time)
probes_result, probe_after_method_logs = self._run_probes(probes, dns)
# Check if server healed after rollbacks
if probes_result is True:
rollbacks['exit_code'] = "0"
rollbacks['status'] = "victim succsessfully healed after rollbacks"
else:
rollbacks['exit_code'] = "1"
rollbacks['status'] = "victim failed healing after rollbacks"
else :
probe_logs['exit_code'] = "1"
probe_logs['status'] = "Probes check failed on victim server"
logs_object = {'name': fault_name ,'exit_code' : '0' ,
'status' : 'expirement ran as expected','rollbacks' : rollback_logs ,
'probes' : probe_logs , 'method_logs' : method_logs,
'probe_after_method_logs' : probe_after_method_logs}
if logs_object["probe_after_method_logs"]["exit_code"] == "0" :
logs_object["successful"] = True
else:
logs_object["successful"] = False
except Exception as E:
logs_object = {'name': fault_name ,'exit_code' : '1' ,
'status' : 'expirement failed because of an unexpected reason', 'error' : E}
return logs_object
def _inject_script(self,dns,script_path):
# Run script
proc = subprocess.Popen("python {} -dns {}".format(script_path,dns), stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, shell=True)
# get output from proc turn it from binary to ascii and then remove /n if there is one
output = proc.communicate()[0].decode('ascii').rstrip()
return output
def _run_fault_part(self,fault_part,dns):
script, script_name = file_manipulator._get_script(fault_part)
script_file_path = file_manipulator._create_script_file(script, script_name)
logs = self._inject_script(dns, script_file_path)
file_manipulator._remove_script_file(script_file_path)
return logs
def _str2bool(self,output):
return output.lower() in ("yes", "true", "t", "1")
def _run_probes(self,probes,dns):
probes_output = {}
# Run each probe and get back True/False boolean result
for probe in probes :
output = self._run_fault_part(probe, dns)
result = self._str2bool(output)
probes_output[probe['name']] = result
probes_result = probes_output.values()
# If one of the probes returned False the probes check faild
if False in probes_result :
return False,probes_output
return True,probes_output
def _get_method_wait_time(self,method):
try:
return method['method_wait_time']
except Exception as E :
return 0
def _get_current_time(self):
current_time = time.strftime('%Y%m%d%H%M%S')
return current_time
def _run_methods(self,methods,dns):
method_logs = {}
methods_wait_time = 0
for method in methods:
part_name = method['name']
part_log = self._run_fault_part(method, dns)
method_wait_time = self._get_method_wait_time(method)
method_logs[part_name] = part_log
methods_wait_time += method_wait_time
return methods_wait_time,method_logs
def _send_result(self,dns,logs_object,collection = "logs"):
# Get current time to timestamp the object
current_time = self._get_current_time()
# Creating object we will send to the db
db_log_object = {}
db_log_object['date'] = current_time
db_log_object['name'] = "{}-{}".format(logs_object['name'],current_time)
db_log_object['logs'] = logs_object
db_log_object['successful'] = logs_object['successful']
db_log_object['target'] = dns
# Send POST request to db api in the logs collection
db_api_logs_url = "{}/{}".format(self.db_api_url,collection)
response = requests.post(db_api_logs_url, json = db_log_object)
return response.content.decode('ascii')
</code></pre>
<pre><code>#script_manipulator.py
import os
import requests
def _get_script(fault_part):
file_share_url = fault_part['path']
script_name = fault_part['name']
script = requests.get(file_share_url).content.decode('ascii')
return script, script_name
def _create_script_file(script, script_name):
injector_home_dir = "/root"
script_file_path = '{}/{}'.format(injector_home_dir, script_name)
with open(script_file_path, 'w') as script_file:
script_file.write(script)
return script_file_path
def _remove_script_file( script_file_path):
os.remove(script_file_path)
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>This is a bit much to go through all at once. It would be better if you could separate out the general concept illustrated by examples as a single review, and then specific implementation of components for other reviews.</p>\n<p>I'm afraid I can't give much feedback on the overall concept, but I will highlight some areas that stood out to me.</p>\n<p><strong>Configuration</strong></p>\n<p>You have hardcoded configuration scattered throughout your code. This not only makes it more difficult to update, but also makes it inflexible. There are a <a href=\"https://stackoverflow.com/questions/49643793/what-is-the-best-method-for-setting-up-a-config-file-in-python\">range of options</a>, but it will depend on your specific preferences and needs.</p>\n<pre><code>def __init__(self,db_api_url = "http://chaos.db.openshift:5001"):\n</code></pre>\n<pre><code>current_time = time.strftime('%Y%m%d%H%M%S')\n</code></pre>\n<pre><code>def _str2bool(self,output):\n return output.lower() in ("yes", "true", "t", "1")\n</code></pre>\n<p><strong>Path manipulation</strong></p>\n<p>Don't do it manually! Trying to use string manipulation to concatenate file paths is <a href=\"https://medium.com/@ageitgey/python-3-quick-tip-the-easy-way-to-deal-with-file-paths-on-windows-mac-and-linux-11a072b58d5f\" rel=\"nofollow noreferrer\">full of pitfalls</a>. Instead, you should use the <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\">pathlib</a> standard library which removes all the headaches of worrying about getting the correct separator characters etc.</p>\n<p>You should also not hard code configuration into your functions, at least provide a means of overriding it. For example your <code>_create_script_file</code> function:</p>\n<pre><code>def _create_script_file(script, script_name):\n injector_home_dir = "/root"\n script_file_path = '{}/{}'.format(injector_home_dir, script_name)\n with open(script_file_path, 'w') as script_file:\n script_file.write(script)\n return script_file_path\n</code></pre>\n<p>Could be rewritten:</p>\n<pre><code>def _create_script_file(script, script_name, injector_home_dir = "/root"):\n script_file_path = Path(injector_home_dir).joinpath(injector_home_dir, script_name)\n with open(script_file_path, 'w') as script_file:\n script_file.write(script)\n return script_file_path\n</code></pre>\n<p>Even better, load your <code>injector_home_dir</code> from configuration or load as a <code>Path</code> object in an initializer or somewhere.</p>\n<p><strong>String literals</strong></p>\n<p>This may be more of a personal preference, but I think <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#f-strings\" rel=\"nofollow noreferrer\">fstrings</a> are far more readable than string formatting:</p>\n<pre><code>db_fault_api_url = "{}/{}/{}".format(self.db_api_url, "fault", fault_name)\n</code></pre>\n<p>vs</p>\n<pre><code>db_fault_api_url = f"{self.db_api_url}/fault/{fault_name}")\n</code></pre>\n<p><strong>List/dictionary comprehension</strong></p>\n<p>In this section you appear to be essentially filtering a dictionary. This can be greatly simplified since you're reusing the keys:</p>\n<pre><code> # Get the names of the parts of the fault\n probes = fault_info["probes"]\n methods = fault_info["methods"]\n rollbacks = fault_info["rollbacks"]\n name = fault_info["name"]\n\n fault_structure = {'probes' : probes , 'methods' : methods , 'rollbacks' : rollbacks}\n</code></pre>\n<pre><code> # Get the names of the parts of the fault\n parts = ["probes", "methods", "rollbacks", "name"]\n fault_structure = {key: value for key, value in fault_info.items() if key in parts}\n</code></pre>\n<p>The keys used in <code>parts</code> appear to be reused in various places so they are a good candidate for storing in configuration.</p>\n<p><strong>Exception handling</strong></p>\n<p>I'm not keen on this section. There is a lot of repeated code, I would much prefer to return a value based on the exception. You also have what is essentially a <a href=\"https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except\">bare exception</a> where you catch any type of exception.</p>\n<pre><code> def _orchestrate_injection(self,dns,fault_name):\n try :\n # Gets fault full information from db\n fault_info = self._get_fault_info(fault_name)\n except Exception as E :\n return { "exit_code":"1" ,"status": "Injector failed gathering facts" }\n try :\n # Runs the probes,methods and rollbacks by order.\n logs_object = self._run_fault(dns, fault_info)\n except :\n return { "exit_code":"1" ,"status": "Injector failed injecting fault" }\n try :\n # Sends logs to db to be stored in the "logs" collection\n db_response = self._send_result(dns,logs_object,"logs")\n return db_response\n except Exception as E:\n return { "exit_code":"1" ,"status": "Injector failed sending logs to db" }\n</code></pre>\n<p>Use a single try/catch block, store the response and then finally return at the end:</p>\n<pre><code>\n def _orchestrate_injection(self,dns,fault_name):\n try :\n # Gets fault full information from db\n fault_info = self._get_fault_info(fault_name)\n # Runs the probes,methods and rollbacks by order.\n logs_object = self._run_fault(dns, fault_info)\n # Sends logs to db to be stored in the "logs" collection\n db_response = self._send_result(dns,logs_object,"logs")\n except SpecificExceptionType as E:\n # Examine exception and determine return message\n if e.args == condition:\n exception_message = ""\n else:\n exception_message = str(E)\n db_response = { "exit_code":"1" ,"status": exception_message }\n return db_response\n</code></pre>\n<p><strong>Repetition and encapsulation</strong></p>\n<p>Consider where you're repeating code or large functions can be broken down into smaller, reusable parts. Your <code>run_fault</code> method is large, with a lot of branching. An obvious repetition is where you update the exit code:</p>\n<pre><code># Check if server healed after rollbacks\nif probes_result is True:\n rollbacks['exit_code'] = "0"\n rollbacks['status'] = "victim succsessfully healed after rollbacks"\nelse:\n rollbacks['exit_code'] = "1"\n rollbacks['status'] = "victim failed healing after rollbacks"\n</code></pre>\n<p>This makes for a nice little function:</p>\n<pre><code>def update_exit_status(log, exit_code, status_message = ""):\n if not status_message:\n if exit_code:\n status_message = "victim successfully healed after rollbacks"\n else:\n status_message = "victim failed healing after rollbacks"\n \n log["exit_code"] = "1" if exit_code else "0"\n log["status"] = status_message\n return log\n</code></pre>\n<p>You use a lot a dictionary manipulation throughout, it could be worthwhile to make a small class to contain this information. This would have the benefit of removing the need for so many magic strings where you retrieve information by keys, instead you could use the properties of your class. You could also then contain some of the data handling logic within you class, instead of spread throughout the rest of your methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T19:02:27.530",
"Id": "478856",
"Score": "0",
"body": "thats exactly what I was looking for ! do you have any more comments on the run fault function ?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T12:15:09.293",
"Id": "243917",
"ParentId": "243854",
"Score": "2"
}
},
{
"body": "<p>@erik-white covered a lot of good ground, but a couple of other things jumped out at me:</p>\n<ol>\n<li><p><code>if <x> is True:</code> should be written as just <code>if <x>:</code></p>\n</li>\n<li>\n<pre><code> if logs_object["probe_after_method_logs"]["exit_code"] == "0" :\n logs_object["successful"] = True\n else:\n logs_object["successful"] = False\n</code></pre>\n<p>could be better written as just:</p>\n<pre><code> logs_object["successful"] = probe_after_method_logs["exit_code"] == "0"\n</code></pre>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T19:01:37.083",
"Id": "478855",
"Score": "0",
"body": "Thank you so much !,"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T17:53:49.700",
"Id": "243933",
"ParentId": "243854",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243917",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T11:52:22.583",
"Id": "243854",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"mongodb",
"automation"
],
"Title": "Simple automation executing platform in Python"
}
|
243854
|
<p>I want to calculate the hitting time of a sequence of prices. I define a log price corridor by for forming a double barrier, <code>up_threshold</code> and <code>down_threshold</code>.
When one of the barriers is touched, I note the time and reset the barriers around the last price</p>
<p><a href="https://i.stack.imgur.com/Kr9ed.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Kr9ed.png" alt="enter image description here" /></a></p>
<p>My script looks as follows:</p>
<pre><code>import pandas as pd
def speed(prices: pd.DataFrame, threshold: float=0.05):
times = []
up_threshold, down_threshold = threshold, -threshold
returns = (prices['Price'] / prices['Price'].shift(1)).apply(np.log)
cum_returns = returns.cumsum(axis=0)
for cum_return in cum_returns:
if -threshold < cum_return < threshold:
# this possibility will probably occur the most frequently
continue
elif cum_return > threshold:
times.append(cum_return)
up_threshold += threshold
down_threshold += threshold
else:
times.append(cum_return)
up_threshold -= threshold
down_threshold -= threshold
if __name__ == '__main__':
prices = np.random.random_integers(10, 25, 100)
prices = pd.DataFrame(prices, columns=['Price'])
speed(prices=prices, threshold=0.05)
</code></pre>
<p>How can I improve this script? Is it wise to also use an apply function for the <code>cum_returns</code>-part? The speed of the script is important. Thanks in advance</p>
|
[] |
[
{
"body": "<h2>else-after-continue</h2>\n<p>This:</p>\n<pre><code> if -threshold < cum_return < threshold:\n # this possibility will probably occur the most frequently\n continue\n elif cum_return > threshold:\n times.append(cum_return)\n up_threshold += threshold\n down_threshold += threshold\n else:\n times.append(cum_return)\n up_threshold -= threshold\n down_threshold -= threshold\n</code></pre>\n<p>can be</p>\n<pre><code> if -threshold < cum_return < threshold:\n # this possibility will probably occur the most frequently\n continue\n\n times.append(cum_return)\n\n if cum_return > threshold:\n up_threshold += threshold\n down_threshold += threshold\n else:\n up_threshold -= threshold\n down_threshold -= threshold\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T00:58:20.963",
"Id": "244296",
"ParentId": "243855",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T12:25:18.133",
"Id": "243855",
"Score": "4",
"Tags": [
"python",
"performance",
"pandas"
],
"Title": "Calculate the first passage time of a sequence consisting of prices"
}
|
243855
|
<p>I'm have recyclerView which is needed for displayed for show list of my audio records. I added the ability to sort my audio records. Please take a look at the code that I use for sorting and tell me how it can be improved.</p>
<pre><code>enum class AudioRecordSort {
SortByDate {
override fun sort(empties: List<AudioRecordEmpty>) {
Collections.sort(empties, AudioRecordDateComparator())
if (!isIncrease)
empties.reversed()
}
},
SortByName {
override fun sort(empties: List<AudioRecordEmpty>) {
Collections.sort(empties, AudioRecordNameComparator())
if (!isIncrease)
empties.reversed()
}
},
SortBySize {
override fun sort(empties: List<AudioRecordEmpty>) {
Collections.sort(empties, AudioRecordSizeComparator())
if (!isIncrease)
empties.reversed()
}
},
SortByTime {
override fun sort(empties: List<AudioRecordEmpty>) {
Collections.sort(empties, AudioRecordTimeComparator())
if (!isIncrease)
empties.reversed()
}
};
val isIncrease: Boolean = true
abstract fun sort(empties: List<AudioRecordEmpty>)
}
</code></pre>
<p>I would also like to say that I do not like that in each method I have to call</p>
<pre><code> if (! IsIncrease)
empties.reversed ().
</code></pre>
<p>Could this be done in a separate place for everyone?</p>
|
[] |
[
{
"body": "<p>You're right that the duplicate code in the sorters looks bad.</p>\n<p>To solve this, each sorter should only define the <em>compare</em> function, and all the rest should be done by the enum class. Or not even this. It took me a little while of experimenting until the code compiled, but here it is:</p>\n<pre class=\"lang-kotlin prettyprint-override\"><code>enum class AudioRecordSort(\n private val cmp: Comparator<AudioRecordEmpty>\n) {\n SortByDate(AudioRecordDateComparator()),\n SortByName(AudioRecordNameComparator()),\n SortBySize(AudioRecordSizeComparator()),\n SortByTime(AudioRecordTimeComparator());\n\n fun sort(empties: MutableList<AudioRecordEmpty>, asc: Boolean) {\n val cmp = if (asc) cmp else cmp.reversed()\n empties.sortWith(cmp)\n }\n}\n</code></pre>\n<p>I don't think it can get any simpler than this.</p>\n<p>I also fixed the type of the <code>empties</code> parameter. You had <code>List<></code>, which in Kotlin is an <em>immutable</em> list. I changed that to <code>MutableList<></code>.</p>\n<p>I also fixed the <code>reversed</code> call to be <code>reverse</code>. I bet your IDE has warned you about the "unused result of <code>reversed</code>". This in turn means that you didn't test your code thoroughly before posting it here, since otherwise you would have noticed that it doesn't work for <code>isIncrease == false</code>.</p>\n<p>Next time please post complete, compilable code. The missing parts for this question are:</p>\n<pre class=\"lang-kotlin prettyprint-override\"><code>class AudioRecordEmpty\n\nclass AudioRecordDateComparator : Comparator<AudioRecordEmpty> {\n override fun compare(o1: AudioRecordEmpty?, o2: AudioRecordEmpty?) = 0\n}\n\nclass AudioRecordNameComparator : Comparator<AudioRecordEmpty> {\n override fun compare(o1: AudioRecordEmpty?, o2: AudioRecordEmpty?) = 0\n}\n\nclass AudioRecordSizeComparator : Comparator<AudioRecordEmpty> {\n override fun compare(o1: AudioRecordEmpty?, o2: AudioRecordEmpty?) = 0\n}\n\nclass AudioRecordTimeComparator : Comparator<AudioRecordEmpty> {\n override fun compare(o1: AudioRecordEmpty?, o2: AudioRecordEmpty?) = 0\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T16:19:54.517",
"Id": "478705",
"Score": "0",
"body": "How about reversing the `Comparator` instead of the list?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T16:33:58.907",
"Id": "478707",
"Score": "0",
"body": "Thanks for the reminder, I updated the code. I had planned to do that anyway. Do you know whether this is just a stylistic issue or if there is any measurable benefit? If any, I'd expect it to be quite small."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T13:36:35.227",
"Id": "243860",
"ParentId": "243856",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "243860",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T12:48:42.917",
"Id": "243856",
"Score": "4",
"Tags": [
"sorting",
"android",
"enum",
"kotlin"
],
"Title": "Code for sorting items in recyclerView"
}
|
243856
|
<p>So, I've tried to extend my <a href="https://flatassembler.github.io/compiler.html" rel="nofollow noreferrer">compiler</a> so that it can target GNU Assembler. And I've made a simple program to demonstrate that.</p>
<pre><code>Syntax GAS
;So, this is an example of how to target GNU Assembler (GAS) using AEC, and how to target Linux.
AsmStart ;What follows is the assembly code produced by CLANG 9.0 on Linux, I don't understand it either, and it's not important.
.text
.file "sierpinski.c"
.globl main # -- Begin function main
.p2align 4, 0x90
.type main,@function
main: # @main
# %bb.0:
pushl %ebp
movl %esp, %ebp
subl $24, %esp
movl $0, -4(%ebp)
leal .L.str, %eax
movl %eax, (%esp)
calll printf
leal .L.str.1, %ecx
movl %ecx, (%esp)
leal n, %ecx
movl %ecx, 4(%esp)
movl %eax, -8(%ebp) # 4-byte Spill
calll __isoc99_scanf
AsmEnd ;And here goes a program written in AEC, finally.
i:=0
While i<n ;This loop will fill the array "new_array" with zeros, except the point right in the middle, which will be filled with 1.
If i=n/2-mod(n/2,1) ;So, if i=floor(n/2), except that I didn't put "floor" in my programming language, so I need to paraphrase it.
new_array(i):=1
Else
new_array(i):=0
EndIf
i:=i+1
EndWhile
i:=0
While i<n
j:=0
While j<n | j=n ;Printing the current state and the new line.
If j=n
AsmStart
.intel_syntax noprefix #Because I don't know anything about att_syntax assembly.
mov byte ptr [esp+4],'\n' #'\n' is, of course, the new line character (in FlatAssembler, you would need to write 10, the ASCII of '\n').
.att_syntax #Not important here (my compiler switches to Intel Syntax before outputting anything except inline Assembly), but added for consistency.
AsmEnd
ElseIf new_array(j)=1
AsmStart
.intel_syntax noprefix
mov byte ptr [esp+4],'*'
.att_syntax
AsmEnd
Else
AsmStart
.intel_syntax noprefix
mov byte ptr [esp+4],' '
.att_syntax
AsmEnd
EndIf
charSign<="%c\0" ;If you write "'%c',0", as you write that in FlatAssembler, GAS complains.
AsmStart
.intel_syntax noprefix
lea ebx,dword ptr [charSign]
mov dword ptr [esp],ebx
call printf
.att_syntax
AsmEnd
j:=j+1
EndWhile
j:=0
While j<n ;Copying "new_array" into "old_array".
old_array(j):=new_array(j)
j:=j+1
EndWhile
j:=0
While j<n
If j=0 | j=n-1 ;Edges
new_array(j):=0
ElseIf old_array(j-1)=old_array(j+1) ;In other words, each cell in the new line in the Sierpinski triangle is the "xor" of its neighbours in the line above it.
new_array(j):=0
Else
new_array(j):=1
EndIf
j:=j+1
EndWhile
i:=i+1
EndWhile
AsmStart ;Again, assembly code produced by CLANG 9.0 on Linux, I don't understand it either.
xorl %ecx, %ecx
movl %eax, -12(%ebp) # 4-byte Spill
movl %ecx, %eax
addl $24, %esp
popl %ebp
retl
.Lfunc_end0:
.size main, .Lfunc_end0-main
# -- End function
.type .L.str,@object # @.str
.section .rodata.str1.1,"aMS",@progbits,1
.L.str:
.asciz "Enter the number of rows and columns in the Sierpinski triangle.\n"
.size .L.str, 67
.type .L.str.1,@object # @.str.1
.L.str.1:
.asciz "%f"
.size .L.str.1, 3
.type n,@object # @n
.comm n,4,4
.type i,@object # @i
.comm i,4,4
.type j,@object # @j
.comm j,4,4
.type result,@object # @result
.comm result,4,4
.type old_array,@object # @old_array
.comm old_array,320,4
.type new_array,@object # @new_array
.comm new_array,320,4
.ident "clang version 9.0.0 (tags/RELEASE_900/final)"
.section ".note.GNU-stack","",@progbits
.addrsig
.addrsig_sym printf
.addrsig_sym __isoc99_scanf
.addrsig_sym n
AsmEnd
</code></pre>
<p>The executable file is available <a href="https://github.com/FlatAssembler/ArithmeticExpressionCompiler/raw/master/ArithmeticExpressionCompiler.zip" rel="nofollow noreferrer">here</a>, it's called <code>sierpinski.elf</code>.<br/>So, what do you think about it?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T13:19:34.677",
"Id": "243858",
"Score": "2",
"Tags": [
"fractals",
"compiler"
],
"Title": "Sierpinski Triangle in AEC"
}
|
243858
|
<p>I've decided to learn more about C++ with the time that I have right now through Udemy courses. To test out the stuff that I've learned up until now, I decided to try and code with some of the knowledge I've gained. I wanted try out object oriented features since I've been doing stuff through procedural programming instead. This is just a simple program utilising a few bits of OOP. I'm not sure if my use of it is appropriate (seeing as it is very minimal in use throughout the program). I would love some feedback and some tips to improve. Please keep feedback simple since I'm new to programming in general, and I don't know all of the technical jargon. Thanks.</p>
<pre><code>// SIMPLE ROCK PAPER SCISSOR GAME w/ some OOP features
#include <cstdlib>
#include <vector>
#include <ctime>
#include <string>
#include <iostream>
using namespace std;
class Player { //stores player/enemy points
private:
int score;
public:
int getScore() {
return score;
}
void incrementScore() {
score++;
}
//constructor
Player(int points);
};
//constructor
Player::Player(int points)
: score {points} {
}
int convertToInt(string pChoice) { //converts player input into integers
if (pChoice == "Rock" || pChoice == "rock") {
return 0;
}
else if (pChoice == "Paper" || pChoice == "paper") {
return 1;
}
else if (pChoice == "Scissor" || pChoice == "scissor") {
return 2;
}
return 0;
}
bool inputValidation(const vector <string> choices, string pChoice) { //validates player input
bool boolean {};
for (const string choice : choices) { //checks vector that contains a list of all possible options
if (choice == pChoice) {
boolean = true;
break;
}
else {
boolean = false;
}
}
return boolean;
}
void printEnemyChoice(unsigned int &enemyRand, string &enemyChoice) { //prints enemy choice
//remember that 0, 1 and 2 correspond to rock, paper and scissor respectively
switch (enemyRand) {
case 0: {
enemyChoice = "Rock";
cout << "Enemy picked: " << enemyChoice << endl;
break;
}
case 1: {
enemyChoice = "Paper";
cout << "Enemy picked: " << enemyChoice << endl;
break;
}
case 2: {
enemyChoice = "Scissors";
cout << "Enemy picked: " << enemyChoice << endl;
break;
}
}
}
void checkResult(Player &playerScore, Player &enemyScore, unsigned int &playerIChoice, unsigned int &enemyRand) { //determines the winner
/* a 2D array is used to compared playerIChoice (the player's choice) and the enemy's choice (randomly generated)
* 0 represents draw
* 1 represents player's win
* 2 represents enemy's win
* remember that 0, 1, 2 is also Rock, Paper and Scissor respectively.. bit confusing. Hope theres a better way to name this properly.
* for eg. if playerIChoice = 2 (Scissors) and enemyRand = 1 (Paper), this points to "1" on the 2D array (3rd row, column 2)
* since it points to a "1", therefore the player wins (Scissors beats Paper).
* 1 is assigned to result, which is used in a switch statement to print out the winner on case 1 and increments the playerScore.score attribute.
*/
int resultArray[3][3] {
{0, 2, 1},
{1, 0, 2},
{2, 1, 0}
};
int result = resultArray[playerIChoice][enemyRand];
switch (result) {
case 0: {
cout << "Result is: Draw" << endl;
break;
}
case 1: {
cout << "Result is: You win!" << endl;
playerScore.incrementScore();
break;
}
case 2: {
cout << "Result is: You lose!" << endl;
enemyScore.incrementScore();
break;
}
}
}
int main() {
Player playerScore {0};
Player enemyScore {0};
bool gameLoop {true};
const vector <string> choices {"Rock", "rock", "Paper", "paper", "Scissor", "scissor", "Q", "q"};
string playerChoice {};
string enemyChoice {};
unsigned int playerIChoice {};
unsigned int enemyRand {};
cout << "======================================" << endl;
cout << "Rock, Paper, Scissor! - CLI w/ Objects" << endl;
cout << "======================================" << endl;
while (gameLoop) {
cout << "\nChoose rock, paper, or scissor: " << endl;
cout << "Press Q to quit the game." << endl;
cin >> playerChoice;
if (playerChoice == "Q" || playerChoice == "q") {
cout << "Thanks for playing." << endl;
gameLoop = false;
break;
}
if (inputValidation(choices, playerChoice) == false) { //passes vector with valid input and player's input to compare
cout << "Invalid input, try again!" << endl;
continue;
}
cout << "You picked: " << playerChoice << endl;
playerIChoice = convertToInt(playerChoice); //converts valid input into integers to compare with enemy's choice
srand (time(NULL));
enemyRand = rand() % 3; //generates random number from 0-2
printEnemyChoice(enemyRand, enemyChoice);
checkResult(playerScore, enemyScore, playerIChoice, enemyRand);
cout << "\nYour score is: " << playerScore.getScore() << endl;
cout << "Enemy score is: " << enemyScore.getScore() << endl;
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>General Observations</strong><br />\nThe game could have more than 2 players, you might want to use a container class to store the players. If this is a single player against the computer, it might be better if <code>enemy</code> was renamed to computer.</p>\n<p><strong>Avoid <code>using namespace std;</code></strong><br />\nIf you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code><<</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n<p><strong>Magic Numbers - Make the Code as Self Documenting as Possible</strong><br />\nThere are Magic Numbers in the <code>convertToInt()</code> function (0, 1, 2), it might be better to use an <a href=\"https://en.cppreference.com/w/cpp/language/enum\" rel=\"noreferrer\">ENUM</a> or create symbolic constants for them to make the code more readble and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier. In this case an ENUM is probably better.</p>\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n<p>It is better to have self documenting code using enums or symbolic constants, because it makes the code easier to read and maintain. Using comments is good where necessary, but they need to be maintained as well as the code, so it is better to write self documenting code.</p>\n<p>If you use an <a href=\"https://en.cppreference.com/w/cpp/container/map\" rel=\"noreferrer\">std::map<></a> the function <code>convertToInt()</code> isn't necessary, table look up is generally faster than logic, and easier to maintain or expand:</p>\n<pre><code>#include <map>\nusing objectType = enum {ROCK, PAPER, SCISSORS};\nusing objectTypeMap = std::map<std::string, objectType >;\n\n\nobjectTypeMap initChoices()\n{\n std::map<std::string, objectType > choices;\n choices.insert({"Rock", ROCK});\n choices.insert({"rock", ROCK});\n choices.insert({"Paper", PAPER});\n choices.insert({"Paper", PAPER});\n choices.insert({"Scissors", SCISSORS});\n choices.insert({"scissors", SCISSORS});\n\n return choices;\n}\n</code></pre>\n<p>In main():</p>\n<pre><code> ...\n string playerChoice {};\n string enemyChoice {};\n objectType playerIChoice {};\n objectTypeMap stringConverter = initChoices();\n\n ...\n playerIChoice = stringConverter[playerChoice]; //converts valid input into integers to compare with enemy's choice\n ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T14:57:30.230",
"Id": "243864",
"ParentId": "243859",
"Score": "7"
}
},
{
"body": "<p>I will focus mostly on the object oriented part.</p>\n<p>So, to make the code more <em>object oriented</em>, you need more objects. Free methods (i.e. methods that are not part of any class) with a lot of mutable arguments (references to types) are usually a sign that there is an object missing, since we are changing <em>states</em> of other objects.</p>\n<p>Let's start by removing the entire logic in the main method. For this, we will create an object "RockScissorPaper", which has a constructor and a play-method, and a sub-set of the variables defined in your main.</p>\n<pre><code>class RockPaperScissors\n{\npublic:\n RockPaperScissors();\n void play();\n\nprivate:\n Player playerScore_ {0}; // suffixing with "_" to mark that these are member variables\n Player enemyScore_ {0};\n const vector <string> choices_ {"Rock", "rock", "Paper", "paper", "Scissor", "scissor", "Q", "q"};\n};\n</code></pre>\n<p>The constructor of RockPaperScissors can be</p>\n<pre><code>RockPaperScissors::RockPaperScissors() : \n{\n cout << "======================================" << endl;\n cout << "Rock, Paper, Scissor! - CLI w/ Objects" << endl;\n cout << "======================================" << endl;\n};\n</code></pre>\n<p>.</p>\n<p>Now we can put the logic into the play-method. I will move each variable to right before it is used (good practice):</p>\n<pre><code>RockPaperScissors::play()\n{\n bool gameLoop{true};\n while (gameLoop) {\n cout << "\\nChoose rock, paper, or scissor: " << endl;\n cout << "Press Q to quit the game." << endl;\n string playerChoice {};\n cin >> playerChoice;\n \n if (playerChoice == "Q" || playerChoice == "q") {\n cout << "Thanks for playing." << endl;\n gameLoop = false;\n break;\n }\n \n if (inputValidation(choices_, playerChoice) == false) { //passes vector with valid input and player's input to compare\n cout << "Invalid input, try again!" << endl;\n continue;\n }\n \n cout << "You picked: " << playerChoice << endl;\n unsigned int playerIChoice = convertToInt(playerChoice); //converts valid input into integers to compare with enemy's choice\n \n srand (time(NULL));\n unsigned int enemyRand = rand() % 3; //generates random number from 0-2\n \n string enemyChoice {};\n printEnemyChoice(enemyRand, enemyChoice);\n checkResult(playerScore_, enemyScore_, playerIChoice, enemyRand);\n \n cout << "\\nYour score is: " << playerScore_.getScore() << endl;\n cout << "Enemy score is: " << enemyScore_.getScore() << endl;\n }\n}\n</code></pre>\n<p>Now we can move <code>inputValidation</code>, and <code>checkResult</code> as <em>private</em> methods of RockPaperScissors. <code>printEnemyChoice</code> and <code>convertToInt</code> do not rely on any private members of RockPaperScissors, but are relying on internal logic of the class. I will thus put them there as well, but as <em>static methods</em> of the class.</p>\n<pre><code>class RockPaperScissors\n {\n public:\n RockPaperScissors();\n void play();\n \n private:\n void checkResult(unsigned int &playerIChoice, unsigned int &enemyRand);\n bool inputValidation(string pChoice);\n\n static void printEnemyChoice(unsigned int &enemyRand, string &enemyChoice); \n static int convertToInt(string pChoice);\n\n Player playerScore_ {0}; // suffixing with "_" to mark that these are member variables\n Player enemyScore_ {0};\n const vector <string> choices_ {"Rock", "rock", "Paper", "paper", "Scissor", "scissor", "Q", "q"};\n };\n</code></pre>\n<p>Note that the member methods have less arguments. I also added the last function <em>convertToInt</em> as a <em>static method</em> of RockPaperScissors, since it relies on internal logic of the class. A static method cannot access the state variables, which is fine, since "convertToInt" does not do that.</p>\n<p>The play method is now instead</p>\n<pre><code>RockPaperScissors::play()\n{\n bool gameLoop{true};\n while (gameLoop) {\n cout << "\\nChoose rock, paper, or scissor: " << endl;\n cout << "Press Q to quit the game." << endl;\n string playerChoice {};\n cin >> playerChoice;\n \n if (playerChoice == "Q" || playerChoice == "q") {\n cout << "Thanks for playing." << endl;\n gameLoop = false;\n break;\n }\n \n if (inputValidation(playerChoice) == false) { //passes vector with valid input and player's input to compare\n cout << "Invalid input, try again!" << endl;\n continue;\n }\n \n cout << "You picked: " << playerChoice << endl;\n unsigned int playerIChoice = convertToInt(playerChoice); //converts valid input into integers to compare with enemy's choice\n \n srand (time(NULL));\n unsigned int enemyRand = rand() % 3; //generates random number from 0-2\n \n string enemyChoice {};\n printEnemyChoice(enemyRand, enemyChoice);\n checkResult(playerIChoice, enemyRand);\n \n cout << "\\nYour score is: " << playerScore_.getScore() << endl;\n cout << "Enemy score is: " << enemyScore_.getScore() << endl;\n }\n}\n</code></pre>\n<p>The main method now looks like:</p>\n<pre><code>int main() {\n RockPaperScissors rps{};\n rps.play();\n return 0;\n}\n</code></pre>\n<p>Now you have one <em>main</em> game class, and a person class. A next step could be to refactor "Rock","Paper","Scissors"-logic to a separate class - so that the main class does not need to have the responsibility of this. It's good practice to create as small classes as possible, each of them having a specific goal.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T18:41:21.417",
"Id": "478853",
"Score": "0",
"body": "Thanks, this is exactly the feedback I needed. By \"Rock, Paper, Scissors logic\" are you referring to the checkResults() method?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T19:26:07.173",
"Id": "478860",
"Score": "1",
"body": "@novachrono, I actually meant `convertToInt`, since it has logic for how to convert user input to an int. But I think `checkResults` can also be made an object with the resposibility check the scores. If you are just playing around with OOP, you can make everything an object. Just try to assign it a specific responsibility and figure out its dependencies to other objects."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T15:57:35.700",
"Id": "243868",
"ParentId": "243859",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "243868",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T13:31:02.740",
"Id": "243859",
"Score": "11",
"Tags": [
"c++",
"beginner"
],
"Title": "A pretty simple Rock, Paper, Scissor game on C++"
}
|
243859
|
<p>guys I'm new to python and I decided to learn it via doing some project myself so I started working on Hangman game is there somebody willing to chceck my code for some common mistakes and what could be better done than it is, btw the works fine.</p>
<pre><code>import random
def rand_word(version):
if version.lower() == "slovak":
words = open("Slova", "r")
all_lines = words.readlines()
line_num = random.randint(0, len(all_lines))
words.close()
return all_lines[line_num]
elif version.lower() == "english":
words = open("Words", "r")
all_lines = words.readlines()
line_num = random.randint(0, len(all_lines))
words.close()
return all_lines[line_num]
else:
print("Wrong input! [FATAL ERROR]")
input("Press enter to EXIT!")
exit()
def draw(what_to_do):
HANGMANPICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
if what_to_do == 1:
print(HANGMANPICS[what_to_do])
elif what_to_do == 2:
print(HANGMANPICS[what_to_do])
elif what_to_do == 3:
print(HANGMANPICS[what_to_do])
elif what_to_do == 4:
print(HANGMANPICS[what_to_do])
elif what_to_do == 5:
print(HANGMANPICS[what_to_do])
elif what_to_do == 6:
print(HANGMANPICS[what_to_do])
elif what_to_do == 7:
print(HANGMANPICS[what_to_do])
else:
print(HANGMANPICS[0])
def list_fill(size):
i = 0
size -= 1
while i < size:
positions.append("_")
i += 1
print("HANGMAN")
print("You have 6 tries to guess the correct word!")
dictionary = input("Chose dictionary Slovak or English: ")
positions = []
tries = 0
win_con = 1
addition = False
temp_word = rand_word(dictionary)
#print(temp_word)
list_fill(len(temp_word))
while tries < 6:
counter = 0
draw(tries)
print(*positions)
user_letter = input("Enter a letter: ")
for letter in temp_word:
if letter == user_letter:
positions[counter] = letter
win_con += 1
tries -= 1
else:
addition = True
counter += 1
if addition:
tries += 1
if win_con == len(temp_word):
print("You have won!")
print(*positions)
input("Press enter to EXIT!")
exit()
print("You have run out of tries! ")
print(f"The word was {temp_word.upper()}")
input("Press enter to EXIT!")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T15:46:13.147",
"Id": "478698",
"Score": "0",
"body": "`version = version.lower()` and you don't have to repeate `lower()` in all `if/else`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T16:46:35.690",
"Id": "478708",
"Score": "0",
"body": "BTW: `HANGMANPICS` has elements with indexes from 0 to 6 but you use index 7"
}
] |
[
{
"body": "<p>Below my version with changes - I didn't run it to test.</p>\n<p>I describe it after code.</p>\n<pre><code>import random\n\n# --- constants ---\n\nHANGMANPICS = ['''\n +---+\n | |\n |\n |\n |\n |\n =========''', '''\n +---+\n | |\n O |\n |\n |\n |\n =========''', '''\n +---+\n | |\n O |\n | |\n |\n |\n =========''', '''\n +---+\n | |\n O |\n /| |\n |\n |\n =========''', '''\n +---+\n | |\n O |\n /|\\ |\n |\n |\n =========''', '''\n +---+\n | |\n O |\n /|\\ |\n / |\n |\n =========''', '''\n +---+\n | |\n O |\n /|\\ |\n / \\ |\n |\n ========='''\n]\n\n# --- functions ---\n\ndef rand_word(version):\n \n version = version.lower()\n \n if version == "slovak":\n filename = "Slova"\n elif version == "english":\n filename = "Words"\n else:\n print("Wrong input! [FATAL ERROR]")\n input("Press enter to EXIT!")\n exit()\n\n words = open(filename) \n #all_lines = words.readlines() # it keeps `\\n` in lines\n #all_lines = words.read().split('\\n') # it removes `\\n` in lines\n all_lines = words.read().splitlines() # it removes `\\n` in lines\n words.close()\n \n print(all_lines)\n\n #line_num = random.randint(0, len(all_lines))\n #return all_lines[line_num]\n\n word = random.choice(all_lines)\n return word \n\ndef draw(what_to_do):\n\n if 1 <= what_to_do <= 7:\n print(HANGMANPICS[what_to_do])\n else:\n print(HANGMANPICS[0])\n \n # or\n\n #if what_to_do < 1 or what_to_do > 7:\n # what_to_do = 0\n #print(HANGMANPICS[what_to_do])\n\ndef list_fill(size):\n return ["_"] * size\n #return ["_"] * size-1 # if you didn't remove `\\n` from lines\n\n# --- main ---\nprint("HANGMAN")\nprint("You have 6 tries to guess the correct word!")\n\ndictionary = input("Chose dictionary Slovak or English: ")\n\ntries = 0\nwin_con = 0\n\ntemp_word = rand_word(dictionary)\npositions = list_fill(len(temp_word))\n\nwhile tries < 6:\n\n counter = 0\n \n draw(tries)\n #print(*positions)\n print(' '.join(positions)) # the same result\n \n user_letter = input("Enter a letter: ")\n\n addition = False\n \n for letter in temp_word:\n\n if letter == user_letter:\n positions[counter] = letter\n win_con += 1\n tries -= 1\n else:\n addition = True\n\n counter += 1\n\n if addition:\n tries += 1\n\n if win_con == len(temp_word):\n print("You have won!")\n print(*positions)\n input("Press enter to EXIT!")\n exit()\n\nprint("You have run out of tries! ")\nprint(f"The word was {temp_word.upper()}")\ninput("Press enter to EXIT!")\n</code></pre>\n<hr />\n<p><strong>rand_word()</strong></p>\n<p>You could convert to lower only once</p>\n<pre><code>version = version.lower()\n</code></pre>\n<p>Inside <code>if/else</code> you use the same code so you could use it after <code>if/else</code></p>\n<pre><code>if version == "slovak":\n filename = "Slova"\nelif version == "english":\n filename = "Words"\nelse:\n print("Wrong input! [FATAL ERROR]")\n input("Press enter to EXIT!")\n exit()\n\nwords = open(filename) \nall_lines = words.readlines() # it keeps `\\n` in lines\nwords.close()\n\nline_num = random.randint(0, len(all_lines))\nreturn all_lines[line_num]\n</code></pre>\n<p>But <code>readlines()</code> gives lines with <code>\\n</code> (and probabably later you have to use <code>size-1</code> and <code>win_con = 1</code>) but you can read it in different way to remove the <code>\\n</code></p>\n<pre><code>all_lines = words.read().split('\\n') # it removes `\\n` in lines\n</code></pre>\n<p>or</p>\n<pre><code>all_lines = words.read().splitlines() # it removes `\\n` in lines\n</code></pre>\n<p>Eventually use list compression to remove <code>\\n</code> from elements on list</p>\n<pre><code>all_lines = [line.strip() for line in all_lines]\n</code></pre>\n<p>Using<code>strip()</code> or <code>rstrip()</code> it removes also spaces/tabs if they are in file.</p>\n<p><code>random</code> has many useful functions and you can get random word without using index</p>\n<pre><code>word = random.choice(all_lines)\n\nreturn word \n</code></pre>\n<p>BTW: There can be one problem - if would run hangmap for many words then <code>choice()</code> (or <code>randint()</code>) may select the same word again. You would have to remeber which word was already used and repeat selection - or you should shuffle list <code>random.shuffle(all_lines)</code> and later you can run code with <code>for word in all_lines</code> and it will use different words in random order.</p>\n<hr />\n<p><strong>draw()</strong></p>\n<p><code>HANGMANPICS</code> never changes so it is good that you use <code>UPPER_CASE_NAME</code>. But you could put it outside function. Inside function it will create it again and again when you run <code>draw()</code> (but it has always the same values so there is no need to create again and again)</p>\n<p><strong>EDIT:</strong> <code>HANGMANPICS</code> has elements with indexes from <code>0</code> to <code>6</code> but you use <code>7</code></p>\n<p>You can use <code><=</code> instead of <code>==</code> to make it simpler</p>\n<pre><code>if 1 <= what_to_do <= 6: # EDIT: it has to be 6 instead of 7\n print(HANGMANPICS[what_to_do])\nelse:\n print(HANGMANPICS[0])\n</code></pre>\n<p>or use "reversed" comparitions</p>\n<pre><code>if what_to_do < 1 or what_to_do > 6: # EDIT: it has to be 6 instead of 7\n what_to_do = 0\n\nprint(HANGMANPICS[what_to_do])\n</code></pre>\n<hr />\n<p><strong>list_fill()</strong></p>\n<p>You can use <code>*</code> to repeat strings on list.</p>\n<pre><code>def list_fill(size):\n return ["_"] * size-1\n</code></pre>\n<p>And use <code>return</code> to assign to <code>position</code></p>\n<pre><code>positions = list_fill(len(temp_word))\n</code></pre>\n<p>This way you can run it in a loop which repeats the game with next word</p>\n<hr />\n<p><strong>other code</strong></p>\n<p>I'm not sure but <code>addition = False</code> probably should be inside <code>while</code>-loop before every <code>for</code>-loop which change <code>addition = True</code></p>\n<hr />\n<p><strong>BTW:</strong> <code>open()</code> as default use <code>"r"</code> so you don't have to use it.</p>\n<hr />\n<p><strong>EDIT:</strong> I don't know if I understand <code>addition</code>. You add only 1 to <code>tries</code> when you don't guess letter but you also subract from <code>tries</code> many times - ie. if you guess <code>a</code> in word <code>ABBA</code> then it substracts 2 because <code>a</code> is two times in this word. The same for char <code>b</code> - it substracts 2. This way you can get tries smaller then <code>0</code></p>\n<p>I would use to add 1 only when not found letter - and keep current value when found letter (and it doesn't matter how many times it exists in word).</p>\n<pre><code> found = False\n \n for index, letter in enumerate(word):\n if letter == user_letter:\n positions[index] = letter\n win_con += 1\n found = True\n\n if not found:\n tries += 1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T03:16:40.380",
"Id": "478752",
"Score": "0",
"body": "I never like the \"wrong input => abandon ship\" approach. Just give the user a chance to correct himself without needing to restart the program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T13:30:04.743",
"Id": "478817",
"Score": "0",
"body": "@infinitezero you can describe it with code as answer and it will be useful for OP and other users."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T16:14:58.630",
"Id": "243869",
"ParentId": "243866",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "243869",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T15:28:46.000",
"Id": "243866",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"hangman"
],
"Title": "Python hangman code"
}
|
243866
|
<p>I'm posting my Java code for the <a href="https://leetcode.com/problems/minimum-window-substring/" rel="nofollow noreferrer">Minimum Window Substring</a>. If you have time and would like to review, please do so, I appreciate that.</p>
<h3>Problem</h3>
<blockquote>
<p>Given a string <code>string</code> and a string <code>target</code>, find the minimum window
in <code>string</code> which will contain all the characters in <code>target</code> in
complexity O(n).</p>
<p>Example:</p>
<p>Input: <code>string</code> = "ADOBECODEBANC", <code>target</code> = "ABC" Output: "BANC"
Note:</p>
<p>If there is no such window in <code>string</code> that covers all characters in
<code>target</code>, return the empty string "". If there is such window, you are
guaranteed that there will always be only one unique minimum window in
<code>string</code>.</p>
</blockquote>
<h3>Java</h3>
<pre><code>import java.util.*;
import javafx.util.*;
class Solution {
public String minWindow(String string, String target) {
if (string == null || target == null || string.length() == 0 || target.length() == 0 || string.length() < target.length()) {
return "";
}
int minLeft = 0, minRight = 0, min = string.length();
boolean flag = false;
int targetLength = target.length();
Map<Character, Integer> map = new HashMap<>(targetLength);
for (char character : target.toCharArray()) {
map.put(character, -~map.getOrDefault(character, 0));
}
int left = 0, right = 0;
while (right < string.length()) {
char character = string.charAt(right);
map.put(character, map.getOrDefault(character, 0) - 1);
if (map.get(character) > -1) {
targetLength--;
}
while (targetLength == 0 && left <= right) {
flag = true;
int curLength = -~right - left;
if (curLength <= min) {
minLeft = left;
minRight = right;
min = curLength;
}
char leftChar = string.charAt(left);
map.put(leftChar, -~map.getOrDefault(leftChar, 0));
if (map.get(leftChar) > 0) {
targetLength++;
}
left++;
}
right++;
}
return flag == true ? string.substring(minLeft, -~minRight) : "";
}
}
</code></pre>
<h3>Reference</h3>
<ul>
<li><p><a href="https://leetcode.com/problems/minimum-window-substring/solution/" rel="nofollow noreferrer">Question</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/minimum-window-substring/solution/" rel="nofollow noreferrer">Solution</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/minimum-window-substring/discuss/?currentPage=1&orderBy=most_votes&query=" rel="nofollow noreferrer">Discussion</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<p>I have some suggestions.</p>\n<h2>Extract some of the logic to methods.</h2>\n<p>In your code, I see at least three sections of code that could be in methods. In my opinion, those extraction will help with the reading and make the code a bit shorter.</p>\n<ol>\n<li>The validation of the parameters.</li>\n</ol>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if (string == null || target == null || string.length() == 0 || target.length() == 0 || string.length() < target.length()) {\n return "";\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public String minWindow(String string, String target) {\n //[...]\n if (haveInvalidParameters(string, target)) {\n return "";\n }\n //[...]\n}\n\nprivate boolean haveInvalidParameters(String string, String target) {\n return string == null || target == null || string.length() == 0 || target.length() == 0 || string.length() < target.length();\n}\n</code></pre>\n<ol start=\"2\">\n<li>The map initialization.</li>\n</ol>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nMap<Character, Integer> map = new HashMap<>(targetLength);\nfor (char character : target.toCharArray()) {\n map.put(character, -~map.getOrDefault(character, 0));\n}\n//[...]\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public String minWindow(String string, String target) {\n //[...]\n Map<Character, Integer> map = initializeMap(target, targetLength);\n //[...]\n}\n\nprivate Map<Character, Integer> initializeMap(String target, int targetLength) {\n Map<Character, Integer> map = new HashMap<>(targetLength);\n for (char character : target.toCharArray()) {\n map.put(character, -~map.getOrDefault(character, 0));\n }\n return map;\n}\n</code></pre>\n<ol start=\"3\">\n<li>The substring section.</li>\n</ol>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public String minWindow(String string, String target) {\n //[...]\n return flag == true ? string.substring(minLeft, -~minRight) : "";\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public String minWindow(String string, String target) {\n //[...]\n return applySubstring(string, minLeft, minRight, flag);\n}\n\nprivate String applySubstring(String string, int minLeft, int minRight, boolean flag) {\n return flag == true ? string.substring(minLeft, -~minRight) : "";\n}\n</code></pre>\n<h2>Try to keep the variable declarations at the top of the blocks.</h2>\n<p>Generally in Java, we try to put the variable declarations at the top of the blocks.</p>\n<ul>\n<li><a href=\"https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141270.html#16817\" rel=\"nofollow noreferrer\">Code Conventions for the Java (Revised April 20, 1999)</a></li>\n</ul>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>int left = 0, right = 0;\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>int minLeft = 0, minRight = 0, min = string.length();\nint left = 0, right = 0;\n</code></pre>\n<h2>You can simplify the boolean expression</h2>\n<pre class=\"lang-java prettyprint-override\"><code>return flag == true ? string.substring(minLeft, -~minRight) : "";\n</code></pre>\n<p><strong>is equals to</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>return flag ? string.substring(minLeft, -~minRight) : "";\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T22:33:30.790",
"Id": "243954",
"ParentId": "243872",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243954",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T17:43:27.033",
"Id": "243872",
"Score": "0",
"Tags": [
"java",
"performance",
"beginner",
"algorithm",
"programming-challenge"
],
"Title": "LeetCode 76: Minimum Window Substring - Java"
}
|
243872
|
<p>I'm fairly new to Python but had to start using it and for reasons I have to use 2.7, which is why I am using that syntax. I have this function which gets data from a file, if it exists, and then gets passed onto other functions to perform SQL queries etc. The script is only intended to work for the directory it is running in, hence the os.getcwd()</p>
<p>This static data is the only data that gets looked up then returned and referenced by other functions. It works as it is but would you say for professionalism and understanding python better that a class would be better here or a restructure in someway? I am of course only posting a snippet.</p>
<pre><code> currentdirectory = os.getcwd()
versionf = "version.ini"
verfile = os.path.join(currentdirectory, versionf)
def main():
get_local_details()
push_app(application, version)
do_something(app_name_version)
def get_local_details():
if os.path.isfile(verfile):
def get_app_name():
try:
global application
application = subprocess.check_output(['grep', 'application', verfile]).strip('\n')
application = application.rsplit('=')[1]
return application
except:
print "Application missing from version.ini"
def version_number():
try:
global version
version = subprocess.check_output(['grep', 'version', verfile]).strip('\n')
version = version.rsplit('=')[1]
return version
except:
print "version missing from version.ini"
get_app_name()
version_number()
def app_name_version(application, version)
try:
global applicationver
applicationver = application + "." + version
return applicationver
except:
print "error here"
app_name_version(application, version)
else:
print "File does not exist."
main()
</code></pre>
<p>contents of ini file are</p>
<pre><code>application=testapp
version=1.0
</code></pre>
<p>do_something is a function that contains a SQL query that uses the app_name_version as the WHERE statement.</p>
<p>Is it even possible to use a function within a class to define the attributes?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T19:41:41.150",
"Id": "478723",
"Score": "2",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T19:43:18.660",
"Id": "478724",
"Score": "1",
"body": "First of all, Python 2.7 is end of life. Continuing development on that environment means accruing technical debt. Is it possible that the code you posted is truncated and incomplete ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T19:45:28.940",
"Id": "478725",
"Score": "2",
"body": "`do_something` always looks fishy in a piece of code. What details are we missing? What does the INI look like?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T21:12:06.800",
"Id": "478740",
"Score": "0",
"body": "I've updated the question. The above works exactly as I need it to but I don't know if executing the 2 nested functions within that function are efficient or whether there is a better way to do this? I did have them as 3 separate functions before but though it would be nicer to put them all together."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T06:44:05.283",
"Id": "478761",
"Score": "2",
"body": "`new job and all their libs` Are you aware that [you put code under Creative Commons just by presenting it here](https://codereview.stackexchange.com/help/licensing)? Are you in a position to do so?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T08:14:46.680",
"Id": "478780",
"Score": "2",
"body": "@greybeard I haven't posted anything that includes private libs or details."
}
] |
[
{
"body": "<p>Wow, this is kind of a mess.\nI'll just review items in sequence as I read them.\nMy short answer, tl;dr: Yes!</p>\n<p>Try executing python 2.7 code with a python 3 interpreter,\neven if only during development on your laptop, or in unit tests.\nIt will give you the confidence to <code>import six</code> or otherwise drag\nancient code kicking and screaming into the modern era.\nSmall changes like <code>print x</code> → <code>print(x)</code> are easy and helpful.</p>\n<p>The first three lines are nice.\nWe define <code>currentdirectory</code>, <code>versionf</code>, & <code>verfile</code> as top-level module constants.\n<a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> prefers the name <code>current_directory</code>, but I quibble, it's fine as-is.</p>\n<p>You conditionally <code>def</code> or <code>print</code>.\nI recommend an early abort:</p>\n<pre><code> if not os.path.isfile(verfile):\n raise FileNotFoundError(verfile)\n</code></pre>\n<p>You have unfortunate <a href=\"https://en.wikipedia.org/wiki/Coupling_(computer_programming)\" rel=\"nofollow noreferrer\">coupling</a> in this code.\nPython, like all O-O languages, offers you structuring tools to improve cohesion.\nPlease avoid the <code>global</code> keyword, it is a bad code smell.\nAnd please avoid nested <code>def</code>, as its effect on namespaces is similar to using global variables.\nFor private helpers, choose <code>_private</code> names like <code>def _get_app_name</code>,\n<code>def _version_number</code>, and <code>def _app_name_version</code>.</p>\n<p>You wrote:</p>\n<blockquote>\n<pre><code>application = subprocess.check_output(['grep', 'application', verfile]) ...\n</code></pre>\n</blockquote>\n<p>In several places you reference <code>verfile</code>.\nJust listen to your code.\nClearly it is telling you it wants an <code>__init__</code> constructor\nwhich assigns to <code>self.verfile</code>, so that it may be used here.\nAlso, fork'ing <code>grep</code> is <strong>a</strong> tool one might use,\nbut it's not the most appropriate one for the task at hand.\nLet me introduce you to <a href=\"https://docs.python.org/3/library/configparser.html\" rel=\"nofollow noreferrer\"><code>import configparser</code></a>.</p>\n<blockquote>\n<pre><code> global application\n ...\n return application\n</code></pre>\n</blockquote>\n<p>Ok, you used to have 3 module-level variables,\nand now you've added a 4th one.\nSadly, you have scattered them all around the module,\nand you will continue to define additional ones.\nThis is poorly structured.\nThere's no central place for a maintenance engineer\nto discover "what are the important pieces of state I need to worry about?"</p>\n<p>Also, not sure why, after side effecting the variable,\nyou bothered to <code>return</code> it, since caller ignores the return value.\nRather than no-arg invocations of get_app_name and version_number,\nyou might consider passing in the values they need as arguments.\nBut if you turn this into a class, then <code>self</code> can supply those values.</p>\n<blockquote>\n<pre><code> except:\n print ...\n</code></pre>\n</blockquote>\n<p>Better for your catch to be <code>except Exception</code>,\nlest you accidentally catch CTRL-C exceptions, as well.\nConsider using a <a href=\"https://docs.python.org/3/howto/logging.html#a-simple-example\" rel=\"nofollow noreferrer\">logger</a>.</p>\n<p>Then we continue to see a pattern of "more of the same",\nI won't belabor it with repetition.\nYou are consistently abusing namespaces,\nrelying on implicit args,\nand side effecting globals at module-level.</p>\n<p>It's not quite clear from the generic code you posted,\nbut I'm going to go out on a limb and say that this module\nseems to be about "app verification".</p>\n<hr />\n<p>Please do this:</p>\n<pre><code>class AppVerifier:\n</code></pre>\n<p>and then define half a dozen object attributes as I suggested above.\nDoing just that <em>one</em> thing will have a huge effect on making your\ncode more maintainable for the next engineer that has to interact with it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T00:34:01.470",
"Id": "478743",
"Score": "0",
"body": "Hmm, you've said \"`print x` → `print(x)`\" without explaining why it works. Additionally the better choice to just import that functionality from `__future__`. This makes me think this is a poor answer from the get go."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T05:15:55.957",
"Id": "478756",
"Score": "0",
"body": "Why didn't you mention `2to3`?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T23:54:56.730",
"Id": "243884",
"ParentId": "243873",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243884",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T18:39:25.400",
"Id": "243873",
"Score": "2",
"Tags": [
"python",
"python-2.x"
],
"Title": "Python - Do I need a class or are these functions okay?"
}
|
243873
|
<p>I'm posting an sliding window problem of LeetCode (<a href="https://leetcode.com/problems/minimum-window-substring/" rel="nofollow noreferrer">Minimum Window Substring</a>) with C++. If you have time and would like to review the code, please do so, I appreciate that.</p>
<p>On LeetCode, we are only allowed to change the variable names and brute force algorithms are discouraged, usually fail with TLE (Time Limit Error) or MLE (Memory Limit Error).</p>
<h3>Problem</h3>
<blockquote>
<p>Given a string <code>base_string</code> and a string <code>target</code>, find the minimum window
in <code>base_string</code> which will contain all the characters in <code>target</code> in
complexity O(n).</p>
<p>Example:</p>
<p>Input: <code>base_string</code> = "ADOBECODEBANC", <code>target</code> = "ABC" Output: "BANC"
Note:</p>
<p>If there is no such window in <code>base_string</code> that covers all characters in
<code>target</code>, return the empty string "". If there is such window, you are
guaranteed that there will always be only one unique minimum window in
<code>base_string</code>.</p>
</blockquote>
<h3>C++</h3>
<pre><code>class Solution {
public:
string minWindow(string base_string, string target) {
vector<int> count_map(128, 0);
for (auto character : target)
count_map[character]++;
int left = 0, right = 0;
int min_left = 0, min_right = INT_MAX;
int target_length = target.size();
while (right < base_string.size()) {
if (count_map[base_string[right++]]-- > 0)
target_length--;
while (target_length == 0) {
if (right - left < min_right)
min_right = right - (min_left = left);
if (count_map[base_string[left++]]++ == 0)
target_length++;
}
}
return min_right == INT_MAX ? "" : base_string.substr(min_left, min_right);
}
};
</code></pre>
<h3>Reference</h3>
<ul>
<li><p><a href="https://leetcode.com/problems/minimum-window-substring/" rel="nofollow noreferrer">Question</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/minimum-window-substring/solution/" rel="nofollow noreferrer">Solution</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/minimum-window-substring/discuss/?currentPage=1&orderBy=most_votes&query=" rel="nofollow noreferrer">Discussion</a></p>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T03:51:41.413",
"Id": "478933",
"Score": "1",
"body": "(Down-voters please comment.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T07:31:58.540",
"Id": "479176",
"Score": "1",
"body": "I can’t see anything wrong with the question, maybe the links but it took me three reads to think I understood it. You might want to consider ++var for non-pod types."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T14:24:04.940",
"Id": "479216",
"Score": "1",
"body": "What happens when you submit this code to LeetCode? Did you pass the TL? Why do you think it can be further improved? Comparison with competitor results? (I didn't donwvote)"
}
] |
[
{
"body": "<p>In the following code, I tried two modifications.</p>\n<ol>\n<li><p>I slightly modified the way tests are performed, in order to minimize them a little bit</p>\n</li>\n<li><p>I used iterators, like this :<code>auto p_str = base_string.begin() + right;</code></p>\n</li>\n</ol>\n<p>with the idea to avoid a redirection here:</p>\n<pre><code>count_map[*p_str++]--;\n</code></pre>\n<p>instead of</p>\n<pre><code>count_map[base_string[right++]]--;\n</code></pre>\n<p>At the end, we cannot be sure how much the speed has been improved. A benchmark is needed (by LeetCode?). We can only be sure that the code is more difficult to read!</p>\n<pre><code>#include <iostream>\n#include <string>\n#include <vector>\n#include <cassert>\n\n\nstd::string minWindow(std::string base_string, std::string target) {\n std::vector<int> count_map(128, 0);\n int n = base_string.length();\n\n for (auto character : target)\n count_map[character]++;\n\n int left = 0, right = 0;\n int min_left = 0, min_right = n+1;\n int target_length = target.size();\n\n while (right < n) {\n auto p_str = base_string.begin() + right;\n while (target_length > 0 && p_str != base_string.end()) {\n if (count_map[*p_str++]-- > 0)\n target_length--;\n }\n right = p_str - base_string.begin();\n \n if (target_length == 0 && right - left < min_right)\n min_right = right - left;\n\n p_str = base_string.begin() + left;\n while (target_length == 0) {\n if (count_map[*p_str++]++ == 0) {\n left = p_str - base_string.begin() - 1;\n if (right - left < min_right)\n min_right = right - (min_left = left);\n target_length++;\n }\n }\n left = p_str - base_string.begin();\n }\n if (target_length == 0 && (right - left < min_right))\n min_right = right - (min_left = left);\n \n return min_right == n ? "" : base_string.substr(min_left, min_right);\n}\n\n\nint main() {\n std::string s = "XXXABYYCTTTABYC";\n std::string target = "CBA";\n std::cout << minWindow (s, target) << "\\n";\n \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T16:29:53.033",
"Id": "244122",
"ParentId": "243874",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244122",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T18:41:48.533",
"Id": "243874",
"Score": "1",
"Tags": [
"c++",
"performance",
"beginner",
"algorithm",
"programming-challenge"
],
"Title": "LeetCode 76: Minimum Window Substring"
}
|
243874
|
<p>I'm posting a two-pointer, sliding-window problem of LeetCode (<a href="https://leetcode.com/problems/minimum-window-substring/" rel="nofollow noreferrer">Minimum Window Substring</a>) solved with Python. If you have time and would like to review the code, please do so, I appreciate that.</p>
<p>On LeetCode, we are only allowed to change the variable names and brute force algorithms are discouraged, usually fail with TLE (Time Limit Error) or MLE (Memory Limit Error).</p>
<h3>Problem</h3>
<blockquote>
<p>Given a string <code>base_string</code> and a string <code>target</code>, find the minimum window
in <code>base_string</code> which will contain all the characters in <code>target</code> in
complexity O(n).</p>
<p>Example:</p>
<p>Input: <code>base_string</code> = "ADOBECODEBANC", <code>target</code> = "ABC" Output: "BANC"
Note:</p>
<p>If there is no such window in <code>base_string</code> that covers all characters in
<code>target</code>, return the empty string "". If there is such window, you are
guaranteed that there will always be only one unique minimum window in
<code>base_string</code>.</p>
</blockquote>
<h3>Solution 1</h3>
<pre><code>import collections
class Solution:
def minWindow(self, base_string: str, target: str) -> str:
count_map = collections.Counter(target)
left = 0
min_left, min_right = 0, 0
target_length = len(target)
for right, char in enumerate(base_string, 1):
target_length -= count_map[char] > 0
count_map[char] -= 1
if not target_length:
while left < right and count_map[base_string[left]] < 0:
count_map[base_string[left]], left = -~count_map[base_string[left]], -~left
if not min_right or right - left <= min_right - min_left:
min_left, min_right = left, right
return base_string[min_left:min_right]
</code></pre>
<h3>Solution 2</h3>
<pre><code>import collections
class Solution:
def minWindow(self, base_string: str, target: str) -> str:
count_map = collections.Counter(target)
left, right = 0, 0
min_left, min_right, min_window = 0, float('inf'), ''
target_length = len(target)
while right < len(base_string):
if count_map[base_string[right]] > 0:
target_length -= 1
count_map[base_string[right]] -= 1
while target_length == 0:
sliding_window = -~right - left
if not min_window or sliding_window < len(min_window):
min_window = base_string[left:-~right]
count_map[base_string[left]] += 1
if count_map[base_string[left]] > 0:
target_length += 1
left += 1
right += 1
return min_window
</code></pre>
<h3>Reference</h3>
<ul>
<li><p><a href="https://leetcode.com/problems/minimum-window-substring/" rel="nofollow noreferrer">Question</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/minimum-window-substring/solution/" rel="nofollow noreferrer">Solution</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/minimum-window-substring/discuss/?currentPage=1&orderBy=most_votes&query=" rel="nofollow noreferrer">Discussion</a></p>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T03:52:12.440",
"Id": "478934",
"Score": "2",
"body": "(Down-voters please comment.)"
}
] |
[
{
"body": "<p>I'm not sure if online courses even go into this, but this is the exact opposite of what good code should look like. Unless there is a dire performance requirement (which is rarer than you think) the aim is always to make your code as readable (clear/stupid/simple) as possible, so that:</p>\n<ol>\n<li>Errors have fewer places to hide</li>\n<li>It is easier to reason about <em>what</em> the code is doing without going into <em>how</em>, which in turn helps you uncover errors, and makes it easier to change.</li>\n</ol>\n<p>The most important factor in readability is intent. If you can't tell what the programmer is trying to accomplish, or how they are going about it, it will be very difficult to detect bugs.</p>\n<p>So the real focus should be on making it clear from your code what your intention is, preferably baked into the code itself (structure, variable names etc...) and failing that, add comments.</p>\n<p>This means you first need to decide on your overall strategy, so in this case: how are you going to find this window? There are many options, here are some:</p>\n<ul>\n<li>Are you going to first get all possible windows and try each of them?</li>\n<li>Are you going to try all windows at position 0, then move to position 1 etc...?</li>\n<li>Are you going to try all windows of smallest size, then next size etc...?</li>\n</ul>\n<p>In your code, I am really not sure what you're going for. Both are also big functions with a lot of variables. So I didn't even try to figure out what it does (and it would be the same in a professional code review: if I don't understand at a glance what the code is even trying to do, it gets rejected).</p>\n<p>I'll go with that last option to give you an idea of how I would write code which makes the intention clear. You'll note that by forcing the code to clearly show its intention you also end up having to break things into smaller parts, and use clear variable names, and all of these things help.</p>\n<p>Ps: you don't need to define a class in python ;-)</p>\n<pre><code>def find_window(base_string, target):\n """\n Try all windows in ascending size order, left to right.\n """\n base_string_length = len(base_string)\n\n def all_chars_in_window(window):\n for c in target:\n if c not in window:\n return False\n return True\n\n def find_match_at_size(try_length):\n end = try_length\n start = 0\n while end <= base_string_length:\n window = base_string[start:end]\n if all_chars_in_window(window):\n return window\n start += 1\n end += 1\n\n try_length = len(target)\n while (try_length <= base_string_length):\n window_found = find_match_at_size(try_length)\n if window_found:\n return window_found\n try_length += 1\n return ''\n\nbase_string = "ADOBECODEBANC"\ntarget = "ABC"\nexpected = "BANC"\n\nprint(find_window(base_string, target))\n</code></pre>\n<p>This took 7 minutes to write, because I only had to write simple code: each bit only has a couple of variables and does something very simple. If I had forced myself to do it the way you did with all those variables and calculations, I would have been at it much longer.</p>\n<p>Hope this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T02:25:06.230",
"Id": "478746",
"Score": "2",
"body": "-1 Whilst this seems like ok advice, though I find some choices to be questionable. Complete disregard for the limitations imposed by LeetCode is a level of unhelpfulness that I can't personally condone."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T02:31:00.807",
"Id": "478747",
"Score": "2",
"body": "@Peilonrayz you're right, I hadn't read those fully. I thought this was a place for telling people how they can improve their code. Having looked at it more closely, I personally cannot condone LeetCode showing people code like that :-/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T02:37:11.020",
"Id": "478748",
"Score": "2",
"body": "@Emma yes, I see I missed part of the LeetCode instructions (and misunderstood the overall point of the question). I'm still struggling to understand why LeetCode would even show code like that. That's just plain wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T17:33:21.260",
"Id": "478845",
"Score": "0",
"body": "+1 for @andyhasit ; this is _Code Review_ not _Assignment help_... and he did a good job at pointing out the problems with this code, as well as giving a good alternative example. Computer time is way cheaper than programmer time, so making code clearer is almost always less expensive than making it faster."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T01:54:17.980",
"Id": "243888",
"ParentId": "243878",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243888",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T19:59:27.357",
"Id": "243878",
"Score": "0",
"Tags": [
"python",
"performance",
"beginner",
"algorithm",
"programming-challenge"
],
"Title": "LeetCode 76: Minimum Window Substring - Python"
}
|
243878
|
<p>I implemented getting the <span class="math-container">\$k\$</span>-nearest neighbours of an origin point to a set of points in C++17. I tried to use some more modern C++ lambda techniques and was looking for feedback on use of lambdas, auto return types, and using a custom comparison function with priority queue.</p>
<ol>
<li>Should other lambdas be captured by referenced or by value?</li>
<li>For <code>auto</code> return types, when should you use the arrow notation to signify a return type?</li>
<li>Is there a cleaner way to declare the type of <code>queue</code> in the code below?</li>
</ol>
<p>Other feedback is welcome too.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <algorithm>
#include <iostream>
#include <queue>
using Point = std::pair<int, int>;
auto knn(const std::vector<Point>& points,
const Point& origin,
const int k) -> std::vector<Point> {
auto squared_distance = [&origin](const Point& p) {
const int dx = std::get<0>(p) - std::get<0>(origin);
const int dy = std::get<1>(p) - std::get<1>(origin);
return dx*dx + dy*dy;
};
auto closer = [&squared_distance](const Point& p1, const Point& p2) {
return squared_distance(p1) > squared_distance(p2);
};
std::priority_queue<Point, std::vector<Point>, decltype(closer)> queue(closer);
for (const auto& point : points) {
queue.push(point);
}
std::vector<Point> nearest_neighbours;
for (int i = 0; i < k; ++i) {
nearest_neighbours.emplace_back(std::move(queue.top()));
queue.pop();
}
return nearest_neighbours;
}
</code></pre>
|
[] |
[
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>Should other lambdas be captured by referenced or by value?</p>\n</blockquote>\n<p>Functionally, for non-mutable lambdas, it doesn't matter. However, if a lambda is marked mutable then capturing by value will make a copy of the lambda's state, whereas if it's a reference no copy is made. Here is an example you can try out yourself:</p>\n<pre><code>#include <iostream>\n#include <vector>\n#include <algorithm>\n\nint main() {\n std::vector<int> vs[2];\n auto iota = [i=0]() mutable {return i++;};\n auto generator = [&iota]() mutable {return iota();}; // try removing the &\n\n for(auto &v: vs) {\n std::generate_n(std::back_inserter(v), 5, generator); // try using iota directly\n for(auto i: v)\n std::cout << i << ' ';\n std::cout << '\\n';\n }\n}\n</code></pre>\n<p>It's probably best to capture them by reference, unless mutable lambdas are used and you want a copy of the state to be made.</p>\n<blockquote>\n<p>For auto return types, when should you use the arrow notation to signify a return type?</p>\n</blockquote>\n<p>You should use it when it is important to constrain the return type, so that you don't accidentily return the wrong type. For example, if I want to write a function that calculates the square root of something, and always return the same type as the input, you should write:</p>\n<pre><code>auto square_root(auto value) -> decltype(value) {\n return std::sqrt(value);\n}\n</code></pre>\n<p>If you omit the trailing return type, then calling the above function with an <code>int</code> will return a <code>double</code> instead. And that might then be a problem if you would do something like:</p>\n<pre><code>printf("Square root of 4 is %d\\n", square_root(4)); // runtime error\n</code></pre>\n<blockquote>\n<p>Is there a cleaner way to declare the type of queue in the code below?</p>\n</blockquote>\n<p>Yes, if you can make the compiler deduce that it should use <code>closer()</code> to compare two <code>Points</code>. One option is to make <code>Point</code> a <code>class</code> and implement <code>operator<()</code>, another one (as pointed out by Mikael H) is to just define a global overload for <code>operator<</code> that takes two <code>Points</code>:</p>\n<pre><code>bool operator<(const Point& p1, const Point& p2) {\n return closer(p1, p2);\n}\n</code></pre>\n<p>Then you can just write:</p>\n<pre><code>std::priority_queue<Point> queue;\n</code></pre>\n<h1>Use <a href=\"https://en.cppreference.com/w/cpp/algorithm/partial_sort_copy\" rel=\"nofollow noreferrer\"><code>std::partial_sort_copy</code></a></h1>\n<p>Using a priority queue is one way to solve it, but it is a bit cumbersome here, since there is no fast way to get the first <code>k</code> elements out. Also, by adding all input elements to the queue, you have sorted all elements, which means you have done more work than necessary. What you want is just to do a partial sort, where you sort the input array until you get the first <code>k</code> smallest elements, and you don't care about the order of the rest. <code>std::partial_sort_copy()</code> allows you to do that, while still allowing a const reference to the input vector:</p>\n<pre><code>std::vector<Point> nearest_neighbours(k);\nstd::partial_sort_copy(points.begin(), points.end(), nearest_neighbours.begin(), neareset_neighbours.end(), closer);\nreturn nearest_neighbours;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T10:20:29.067",
"Id": "478789",
"Score": "0",
"body": "I don't agree lambdas are like passing a *function pointer* (in C). A lambda is basically a class, containing members corresponding to its closure. The same rules as for classes should hold for lambdas - if the lambda/class is small, a copy is suitable, otherwise a reference might be better (ignoring lifetime)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T10:22:52.730",
"Id": "478791",
"Score": "1",
"body": "Also note that Point does not need to be a *class* to define the operator>. It is sufficient to create a free function `bool operator>(const Point& p1, const Point& p2)` for `std::priority_queue` to find the comparison operator without having to have it passed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T12:18:45.127",
"Id": "478807",
"Score": "0",
"body": "@MikaelH You're correct that a lambda expression is basically an object, which has storage if there are captures. But I don't think it matters if it is captured by reference or not, since if anything is captured, it can only be passed to template functions, which will always be inlined, so the compiler is always able to optimize it regardless of whether it's a reference or not? It's different for *mutable* lambdas though, there copy vs. reference would make a semantic difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T12:45:11.637",
"Id": "478810",
"Score": "1",
"body": "I think that it's still an object, regardless of what you do with it. A lambda is a class like any other, with the type being unnamed. Putting the code to cppinsights gives https://cppinsights.io/s/7fe0d32a. Using reference or value will create an object reference or object - impacting size. Just as you would use value or reference when adding a member to a class, you should probably do the same for lambdas."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T12:56:23.960",
"Id": "478812",
"Score": "1",
"body": "@MikaelH Interestingly, passing the lambda by value results in slightly shorter assembly output by both GCC and Clang, see this diff for example: https://godbolt.org/z/cL3W8X"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T13:06:35.103",
"Id": "478813",
"Score": "0",
"body": "If I understand the numbers correctly (412330B vs 413245B), the assembly is shorter, but more heavy? Maybe there something wrong there, I don't see why there should be a 1KB increase (and run time seems off)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T13:09:09.280",
"Id": "478814",
"Score": "0",
"body": "Having a reference creates another indirection. I would assume that assembly should be smaller when having the object as a value directly. The size of the object is on the stack at runtime, I am not sure if we can read that from here. Anyway, for a small lambda, I would use value to capture it. For a big one, a reference (just as for classes)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T21:24:33.420",
"Id": "243882",
"ParentId": "243880",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243882",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T20:27:38.320",
"Id": "243880",
"Score": "4",
"Tags": [
"c++",
"performance",
"c++17",
"computational-geometry",
"machine-learning"
],
"Title": "C++: k-Nearest Neighbours with Lambdas and Priority Queues"
}
|
243880
|
<p>So I've written a URL router which also allows for wildcards (path parameters).</p>
<p>A URL like <code>/users/{uuid}</code> can be added and then, when a user sends a request to the server with the following target <code>/users/955b2a88-ae80-11ea-b3de-0242ac130004</code>, the uuid will then equal <code>955b2a88-ae80-11ea-b3de-0242ac130004</code>.</p>
<p>Example:</p>
<pre><code>PathMatcher<int> matcher(-1);
matcher.add_path("/users/{uuid}", 1);
Parameters parameters;
assert(matcher.match("/users/9c4ceec8-f929-434e-8ff1-837dd54b7b56", parameters) == 1);
assert(parameters.find("uuid", "") == "9c4ceec8-f929-434e-8ff1-837dd54b7b56");
</code></pre>
<p>I have learned C++ through Stack Overflow, therefore I don't really have an idea how production ready code should look like.</p>
<p>I'd like to know what should be written differently and would could be improved.</p>
<p>If you'd like to run the code, it is hosted on <a href="https://github.com/nilsegger/url-router" rel="nofollow noreferrer">GitHub</a> with an example <code>main.cpp</code>.</p>
<pre><code>typedef std::string string_t;
class Parameters {
std::vector<std::pair<string_t, string_t>> parameters_;
public:
void add(string_t& name, string_t& value) {
parameters_.emplace_back(name, value);
}
string_t find(string_t name, string_t default_="") {
for(auto & parameter : parameters_) {
if(parameter.first == name) return parameter.second;
}
return default_;
}
void clear() {
parameters_.clear();
}
};
template<typename Result>
class PathMatcher {
struct Path {
char character;
std::vector<Path *> children;
std::optional<Result> result;
Path(char character, std::optional<Result> result) : character(character), result(result) {}
~Path() {
for(size_t i = 0; i < children.size(); i++) {
delete children[i];
}
}
};
Path *
find_child(char character, std::vector<Path *> &parent, bool findWildcard = false, Path **wildcard = nullptr) {
Path *child = nullptr;
for (size_t i = 0; i < parent.size(); i++) {
if (parent[i]->character == character) {
child = parent[i];
// If wildcards are not wanted, there is no need to continue
if (!findWildcard) break;
} else if (findWildcard && parent[i]->character == wildcard_open_) {
(*wildcard) = parent[i];
// If child has already been found, there is no need to continue
if (child != nullptr) break;
}
}
return child;
}
Path *create_path(std::vector<Path *> &parent, char character, std::optional<Result> value) {
Path *route = new Path(character, value);
parent.push_back(route);
return route;
}
void insert_path(string_t &path, Result &result, Path *step = nullptr, int path_pos = 0) {
/*
* Recursively creates path. A path contains a vector with child paths.
* These linked paths create a chain which can be walked down.
* If we input /users/a and /users/b the following chain would be created.
* / -> u -> s -> e -> r -> s -> / -> a
* -> b
*
* Now if you want to match against an input, this chain can be walked down until a path no longer contains the matching character.
* If the input would equal /users/c, the chain would be walked until the last '/' and then failing because it only contains the children a & b, not c.
*
* The last two paths (a & b) will contains a value. This value states that the path has reached its end.
*/
assert(path.size() > 1);
if (path_pos == path.size() - 1) {
// last insertion accompanied by ending value
Path *child = find_child(path[path_pos], step->children);
if (child != nullptr) {
assert(!child->result); // Cant already have a value
child->result = result;
} else {
create_path(step->children, path[path_pos], result);
}
} else {
Path *child;
if (path_pos == 0) {
child = find_child(path[path_pos], paths_);
} else {
child = find_child(path[path_pos], step->children);
}
if (child == nullptr && path_pos == 0) {
child = create_path(paths_, path[path_pos], std::nullopt);
} else if (child == nullptr) {
child = create_path(step->children, path[path_pos], std::nullopt);
}
return insert_path(path, result, child, path_pos + 1);
}
}
void get_wildcard_name(Path **wildcard, string_t &wildcard_name) {
/*
* /users/{uuid} and users/{uuid}/friends is allowed
* /users/{uuid} and users/{id}/friends is not allowed, because wildcards at the same positions must match
*
* This method walks down the chain until the wildcard_close_ character has been found. Everything between start and end is appended to the value.
*/
assert((*wildcard)->children.size() == 1);
if ((*wildcard)->children[0]->character != wildcard_close_) {
wildcard_name.append(1, (*wildcard)->children[0]->character);
*wildcard = (*wildcard)->children[0];
get_wildcard_name(wildcard, wildcard_name);
} else {
*wildcard = (*wildcard)->children[0];
}
}
string_t get_wildcard_value(string_t &path, size_t &pos) {
// Walks down the input until the trailing_wildcard_ is found or the end is reached, everything between equals the wildcard value
int begin = pos;
for (; pos < path.size() - 1; pos++) {
if (path[pos + 1] == trailing_wildcard_) {
return path.substr(begin, pos - begin + 1);
}
}
return path.substr(begin);
}
std::vector<Path *> paths_;
Result default_;
char wildcard_open_;
char wildcard_close_;
char trailing_wildcard_;
public:
PathMatcher(Result default_, char wildcard_open='{', char wildcard_close='}', char trailing_wildcard='/')
: default_(default_), wildcard_open_(wildcard_open), wildcard_close_(wildcard_close), trailing_wildcard_(
trailing_wildcard) {}
virtual ~PathMatcher() {
for(size_t i = 0; i < paths_.size(); i++) {
delete paths_[i];
}
}
void add_path(string_t path, Result value) {
insert_path(path, value);
}
Result match(string_t path, Parameters &variables) {
/*
* Starts at paths_ and continues trying to find children matching the next characters in input path.
* If there is no child which matches the next character, but there was a wildcard_open_ as a child,
* the code jumps back to it and sets a Parameters value for the wildcard with its value and then continues normally.
*/
Path *step = find_child(path[0], paths_);
if (step == nullptr) return default_;
Path *lastWildcard = nullptr;
size_t lastWildcardPos;
size_t i = 1;
for (; i < path.size() - 1 && step != nullptr; i++) {
Path *nextWildcard = nullptr;
step = find_child(path[i], step->children, true, &nextWildcard);
if (nextWildcard != nullptr && nextWildcard != lastWildcard) {
lastWildcardPos = i;
lastWildcard = nextWildcard;
}
if (path[i] == trailing_wildcard_) {
lastWildcard = nullptr;
}
if (step == nullptr && lastWildcard != nullptr) {
i = lastWildcardPos;
string_t wildcard_name;
get_wildcard_name(&lastWildcard, wildcard_name);
string_t wildcard_value = get_wildcard_value(path, i);
variables.add(wildcard_name, wildcard_value);
if (i == path.size() - 1) {
// Wildcard value reaches end
if (!lastWildcard->result) return default_;
return lastWildcard->result.value();
} else {
step = lastWildcard;
}
}
}
if (step == nullptr) return default_;
Path *wildcard = nullptr;
Path *result = find_child(path[path.size() - 1], step->children, true, &wildcard);
if(result != nullptr && result->result) return result->result.value();
else if(wildcard != nullptr) {
// find wildcard ending and check if it contains a value
string_t wildcardName;
get_wildcard_name(&wildcard, wildcardName);
if(!wildcard->result) return default_;
string_t value = path.substr(path.size() - 1);
variables.add(wildcardName, value);
return wildcard->result.value();
}
return default_;
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T09:40:52.093",
"Id": "478787",
"Score": "0",
"body": "Is there a reason for not using `std::basic_regex`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T12:22:29.717",
"Id": "478808",
"Score": "0",
"body": "I'm not really familiar with regex and I thought it would end up being faster like this. @Edward"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T18:23:23.013",
"Id": "478850",
"Score": "1",
"body": "Regular expressions are usually very fast. Another benefit is that you can make your patterns much more precise: in your example, the UUID pattern matches anything that comes after `/user/`, even if what follows doesn't look like a UUID at all. With regular expressions, you can write [a pattern that only accepts valid UUIDs](https://stackoverflow.com/questions/136505/searching-for-uuids-in-text-with-regex)."
}
] |
[
{
"body": "<p>I see some things that may help you improve your program.</p>\n<h2>Separate interface from implementation</h2>\n<p>It makes the code somewhat longer for a code review, but it's often very useful to separate the interface from the implementation. In C++, this is usually done by putting the interface into separate <code>.h</code> files and the corresponding implementation into <code>.cpp</code> files. It helps users (or reviewers) of the code see and understand the interface and hides implementation details. The other important reason is that you might have multiple source files including the <code>.h</code> file but only one instance of the corresponding <code>.cpp</code> file. In other words, split your existing <code>.h</code> file into a <code>.h</code> file and a <code>.cpp</code> file. The templated class, by contrast, can stay in a <code>.h</code> file.</p>\n<h2>Make sure you have all required <code>#include</code>s</h2>\n<p>The code uses <code>std::pair</code> but doesn't <code>#include <utility></code>. Also, carefully consider which <code>#include</code>s are part of the interface (and belong in the <code>.h</code> file) and which are part of the implementation per the above advice.</p>\n<h2>Reconsider the interface</h2>\n<p>It doesn't seem very useful to me to have the <code>PathMatcher</code> return an <code>int</code>. What would be more useful, I think, would be for it to return a <code>Parameters</code> object. That would also probably eliminate the need for <code>Parameters::clear()</code>.</p>\n<h2>Use standard libraries more effectively</h2>\n<p>The <code>Parameters</code> object currently iterates through its parameters to find a match. I would suggest that instead of this existing line:</p>\n<pre><code>std::vector<std::pair<string_t, string_t>> parameters_;\n</code></pre>\n<p>a more appropriate data structure would be this:</p>\n<pre><code>std::unordered_map<std::string, std::string> parameters_;\n</code></pre>\n<p>That would make <code>find</code> very simple:</p>\n<pre><code>std::string Parameters::find(std::string key, std::string notfound) const {\n auto result = parameters_.find(key);\n return result == parameters_.end() ? notfound : result->second;\n}\n</code></pre>\n<p>Here again, the interface is strange. I don't see much use in passing back a passed string if the key is not found. I'd expect to have an exception thrown instead. That renders the function even simpler:</p>\n<pre><code>std::string Parameters::find(std::string key) const {\n return parameters_.at(key);\n}\n</code></pre>\n<h2>Use <code><regex></code> to greatly simplify the code</h2>\n<p>This code could be much simpler, even without altering the interface, by using <code>std::regex</code>. Here's what the include file would look like:</p>\n<h3>parameter.h</h3>\n<pre><code>#ifndef PARAMETER_H\n#define PARAMETER_H\n#include <regex>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n\nclass Parameters {\npublic:\n std::string find(std::string name, std::string notfound = "") const;\n void clear();\n template <class T>\n friend class PathMatcher;\nprivate:\n std::unordered_map<std::string, std::string> m;\n};\n\nstruct Pattern {\n Pattern(std::string path);\n std::regex re;\n std::vector<std::string> names;\n};\n\ntemplate <class T>\nclass PathMatcher {\npublic:\n PathMatcher(T init) : nomatch{init} {}\n void add_path(std::string pattern, T value) {\n patterns.emplace_back(pattern, value);\n }\n T match(std::string input, Parameters& p) {\n T answer{nomatch};\n for (const auto& patpair : patterns) {\n std::smatch m;\n if (std::regex_match(input, m, patpair.first.re)) {\n answer = patpair.second;\n for (unsigned i{1}; i < m.size(); ++i) {\n p.m[patpair.first.names[i-1]] = m[i].str();\n }\n }\n }\n return answer;\n }\nprivate:\n T nomatch;\n std::vector<std::pair<Pattern, T>> patterns;\n};\n\n#endif // PARAMETER_H\n</code></pre>\n<p>This is the implementation file:</p>\n<h3>parameter.cpp</h3>\n<pre><code>#include "parameter.h"\n\nstd::string Parameters::find(std::string name, std::string notfound) const {\n auto result = m.find(name);\n return result == m.end() ? notfound : result->second;\n}\n\nvoid Parameters::clear() {\n m.clear();\n}\n\nPattern::Pattern(std::string path) {\n static const std::regex vble{R"(\\{[^\\}]*\\})"};\n auto start = std::sregex_iterator{path.begin(), path.end(), vble}; \n auto finish = std::sregex_iterator{};\n for (auto it{start}; it != finish; ++it) {\n auto str = it->str();\n str.erase(0, 1); // remove {\n str.pop_back(); // remove }\n names.push_back(str);\n }\n re = std::regex_replace(path, vble, "(.*)");\n}\n</code></pre>\n<p>When I tested it, it's exactly as fast as the original version (both ran in 5ms on my machine).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T21:24:17.310",
"Id": "478879",
"Score": "0",
"body": "_I don't see much use in passing back a passed string if the key is not found_ I assume that parameters are optional (possibly passed on the command line), so when you ask for the value of one of these having the default value returned (instead of having to handle a not found exception to set that) can simplify the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T21:26:47.607",
"Id": "478880",
"Score": "0",
"body": "It might also be worth mentioning that the original implementation of `Parameters` does not handle duplicate parameters properly. It will return the original (first) value added if an \"updated\" value is added. Using some form of map will replace the existing value with the new value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T21:36:29.757",
"Id": "478881",
"Score": "1",
"body": "Passing `std::string` without the `&` looks unusual to me. Did I miss the latest developments?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T22:05:22.650",
"Id": "478885",
"Score": "0",
"body": "@RolandIllig: It depends where you mean. For `find` it would make sense to pass `const std::string &` but for the `Pattern` constructor, since we need to make a copy anyway, it makes sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T22:08:02.797",
"Id": "478886",
"Score": "0",
"body": "@1201ProgramAlarm: if I say \"tell me how many oranges you have or say 'bleep' if you have no oranges\" I don't see how that simplifies things over \"tell me how many oranges you have or throw an exception if you don't know what I'm asking about.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T08:05:29.680",
"Id": "478945",
"Score": "0",
"body": "Thanks a lot for your answer, helps me a lot. There is just one point I dont understand. What do you mean with \"Also, carefully consider which #includes are part of the interface (and belong in the .h file) and which are part of the implementation per the above advice.\" Even after splitting the code, dont all includes belong into the .h file? @Edward"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T08:59:57.553",
"Id": "478951",
"Score": "1",
"body": "Only `#include`s that are required to understand the interface go in the`.h` file. So if, for example I had used something from `<cmath>` in `parameter.cpp` that `#include` would go only in the `.cpp` file since it’s an internal detail not relevant to the interface."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T15:55:02.073",
"Id": "243927",
"ParentId": "243881",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "243927",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T21:01:32.270",
"Id": "243881",
"Score": "4",
"Tags": [
"c++",
"url-routing"
],
"Title": "URL router for production"
}
|
243881
|
<p>I wanted to make a calculator in python so I first wrote a tokenizer. I have written one before but this time I tried to refine it a bit. Any thoughts on improvements, things I could of done better.</p>
<pre class="lang-py prettyprint-override"><code>import re
class KeyWord:
def __init__(self, name, regex):
self.name = name
self.regex = regex
class NewToken:
def __init__(self, name, value, start, end):
self.name = name
self.value = value
self.start = start
self.end = end
class Lexer:
def __init__(self):
self.text = ""
self.keyWords = []
self.delimiters = ["+", "-", "/", "*", "%", "(", ")", "\n", " "]
self.ignore = [" "]
self.newTokens = []
self.setTokens()
def setTokens(self):
self.keyWords.append(KeyWord("NUMBER", re.compile("([0-9]*\.[0-9]+)|([0-9]+\.[0-9]*)|([0-9])")))
self.keyWords.append(KeyWord("PLUS", re.compile("\+")))
self.keyWords.append(KeyWord("MINUS", re.compile("-")))
self.keyWords.append(KeyWord("TIMES", re.compile("\*")))
self.keyWords.append(KeyWord("DIVIDE", re.compile("\/")))
self.keyWords.append(KeyWord("MODULO", re.compile("%")))
self.keyWords.append(KeyWord("OPENBRACKET", re.compile("\(")))
self.keyWords.append(KeyWord("CLOSEBRACKET", re.compile("\)")))
def setText(self, text):
self.text = text.strip() + "\n"
def getTokens(self):
self.newTokens = []
word = ""
#Loop through input
for i in range(0, len(self.text)):
ignoreFound = False
for ig in self.ignore:
if self.text[i] == ig:
ignoreFound = True
tokenFound = False
#Look for a delimiter
for d in self.delimiters:
if tokenFound:
break
#If a delimiter is found
if self.text[i] == d:
#Look for keyword
for t in self.keyWords:
match = t.regex.match(word)
if match:
self.newTokens.append(NewToken(t.name, word, (i - len(word)), i))
word = ""
tokenFound = True
break
#Check if delimiter has a token
if not ignoreFound:
for t in self.keyWords:
match = t.regex.match(d)
if match:
self.newTokens.append(NewToken(t.name, d, i, i))
tokenFound = True
break
if not tokenFound and not ignoreFound:
word += self.text[i]
self.newTokens.append(NewToken("EOF", "", i, i))
return self.newTokens
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<p>I have written one before</p>\n</blockquote>\n<p>Yeah, I can tell. Nice. This looks well organized.</p>\n<blockquote>\n<pre><code>def setTokens(self):\n</code></pre>\n</blockquote>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> asks that you spell it <code>set_tokens</code>.\nSimilarly for some other setters and getters,\nand for assignments to e.g. <code>self.key_words</code> & <code>self.new_tokens</code>.</p>\n<blockquote>\n<pre><code> self.keyWords.append(KeyWord("NUMBER", re.compile("([0-9]*\\.[0-9]+)|([0-9]+\\.[0-9]*)|([0-9])")))\n</code></pre>\n</blockquote>\n<p>Hmmm, several remarks.</p>\n<p><a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a>, you have an opportunity here to loop\nover a list of pairs (list of tuples),\nso there's just a single <code>.append</code> that we repeatedly call.</p>\n<p>Perhaps you have your reasons, but I personally disagree with your definition of NUMBER.\nChoose a different name if it is a specialized restricted number from some problem domain.\nWith alternation you mention <code>frac|real|digit</code>.\nThe <code>digit</code> seems superfluous, it is subsumed by at least one of the other two.\nI'd prefer to see the order <code>real|frac</code> so we can mandate\n"starts with at least one digit".\nAfter that, you passed up the opportunity to say <code>\\.?</code> for optional decimal.\nThe <code>frac</code> case would then be "starts with decimal point".\nAlso your current expression rejects <code>12</code> while accepting <code>1</code> and <code>123.</code>.</p>\n<p>Rather than e.g. <code>"[0-9]"</code>, consider saying <code>r"\\d"</code>.</p>\n<blockquote>\n<pre><code> self.keyWords.append(KeyWord("PLUS", re.compile("\\+"))) ...\n self.keyWords.append(KeyWord("DIVIDE", re.compile("\\/")))\n</code></pre>\n</blockquote>\n<p>Please run <a href=\"https://pypi.org/project/flake8/\" rel=\"nofollow noreferrer\">flake8</a> against your code, and heed its warnings.\nHere, I have a strong preference for phrasing it <code>re.compile(r"\\+")</code>,\nwith a raw string, to avoid confusion with e.g. <code>"\\t\\n"</code> escapes.\nAlso, the regex <code>/</code> works fine, similar to the regex <code>Z</code>,\nit is just a single character, no need for a <code>\\</code> backwhack.</p>\n<blockquote>\n<pre><code> for i in range(0, len(self.text)):\n</code></pre>\n</blockquote>\n<p>Typical idiom would be <code>for i, ch in enumerate(self.text)</code>.</p>\n<p>The whole <code>ig</code> loop is much too verbose.\nJust test <code>if ch in self.ignore</code> (<code>if self.text[i] in self.ignore</code>)\nand be done with it.</p>\n<hr />\n<p>Two algorithmic remarks:</p>\n<p>It's not yet obvious to me why we need flag + loop to ignore optional\nwhitespace. Wouldn't a simple <code>continue</code> at top of loop suffice?\nMaybe that <code>range</code> is not convenient,\nand you'd be happier with a <code>while</code> loop where you increment <code>i</code> yourself.</p>\n<p>DRY, I'm not keen on <code>self.delimiters</code>,\nit is redundant with those beautiful regexes you went to the trouble of defining.\nI'd like to see one or the other of them go,\nso you don't have to remember to maintain two things in parallel\nwhen you (or someone else!) is maintaining this a few months from now.</p>\n<p>Overall, looks pretty good.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T12:05:02.803",
"Id": "478803",
"Score": "0",
"body": "Thanks for the feedback, i'll have a go at implementing your suggestions"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T01:50:33.477",
"Id": "243887",
"ParentId": "243883",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243887",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T23:17:09.790",
"Id": "243883",
"Score": "4",
"Tags": [
"python",
"lexer"
],
"Title": "Tokenizer / lexer"
}
|
243883
|
<p>I implemented the following function using the matrix object from <a href="https://github.com/scalanlp/breeze" rel="nofollow noreferrer">breeze library</a>. Basically it is just a glorified <code>while</code> loop.</p>
<p>The convolution there is extremely slow so I rolled out my own, optimized on a kernel which is just a vector. This is already much faster but I figured there must be something else I can to to make this go faster.</p>
<p>The most expensive operation according to the profiler is the instantiation of the <code>ArrayDeque</code> (pointed by the arrow) which I don’t really need because all I wanted was a circular buffer, but could not find much in the library.</p>
<p>The second thing is calling <code>until</code> on the <code>Int</code>. I don't think that can be avoided.</p>
<p>Boxing the doubles is also taking quite some time, maybe there is a way to specialize?</p>
<p>Finally the majority of the time is taken by the function call itself (circled in red) which I don’t know what it means. Any insight?</p>
<pre><code>def conv(m: DenseMatrix[Int], k: DenseVector[Double]): DenseMatrix[Double] = {
val kData = k.data
val dataIter = m.data.iterator
val height = m.rows
val convoluted = Array.newBuilder[Double]
val prev = mutable.ArrayDeque.empty[Double]
for (_ <- 1 until k.length) {
prev.addOne(dataIter.next())
}
var count = k.length - 1
while (dataIter.hasNext) {
val cur = dataIter.next()
val slice = prev.append(cur)
if (count % height >= k.length - 1) {
var r = 0D
for (i <- 0 until k.length) {
r += kData(i) * slice(i)
}
convoluted.addOne(r)
}
prev.removeHead()
count += 1
}
DenseMatrix.create(m.rows - (k.length - 1), m.cols, convoluted.result())
}
</code></pre>
<p>Following is the annotated flamechart, <em>please note that <code>fut</code> is the above function <code>conv</code>.</em> Everything else is unchanged.</p>
<p><a href="https://i.stack.imgur.com/8HuZM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8HuZM.png" alt="flamechart" /></a></p>
|
[] |
[
{
"body": "<blockquote>\n<p>all I wanted was a circular buffer</p>\n</blockquote>\n<p>Consider using an array accessed with <code>mod</code>.</p>\n<p>That is, assign size <code>s = k.length - 1</code>,\nallocate a "previous" array <code>p</code>,\nand then access <code>p[i % s]</code>.</p>\n<p>If you're lucky, the compiler may notice that\na portion of the code is just copying,\nand it will issue <code>memcpy</code> instructions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T01:18:43.447",
"Id": "243886",
"ParentId": "243885",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T00:33:49.633",
"Id": "243885",
"Score": "4",
"Tags": [
"scala",
"mathematics"
],
"Title": "Convolution function"
}
|
243885
|
<p>I'm getting into learning python so to learn I made a die-rolling application.
What would you do differently? What would you suggest to improve performance/readability? What tips do you have? Suggest pretty much anything.</p>
<pre><code>import random
import time
import re
#installed via pip install inflect (https://pypi.org/project/inflect/)
import inflect
while True:
confirmation = input("Would you like to roll some dice?(y/n) > ")
if len(confirmation) != 1:
print("Error! You may only input one character")
elif not re.match(r"^[yn]$", confirmation, flags=re.IGNORECASE):
print("Error! Only y and n are valid")
else :
break
if confirmation.casefold() == "n" :
print("No dice have been rolled")
elif confirmation.casefold() == "y":
while True:
count = input("How many dice would you like to roll? > ")
if len(count) == 0 :
print("Error! Please input something!")
elif not re.search(r"^[0-9]*$", count) :
print("Error! You may only input numbers")
else :
p = inflect.engine()
for i in range(1, int(count)+1) :
result = random.randint(1,6)
print("The " + p.number_to_words(p.ordinal(i)) + " die rolled a: " + str(result))
break
</code></pre>
|
[] |
[
{
"body": "<p>If these die rolls are going to be used for anything at all important, it's better to use the <a href=\"https://docs.python.org/3/library/secrets.html\" rel=\"nofollow noreferrer\"><code>secrets</code></a> module rather than <a href=\"https://docs.python.org/3/library/random.html\" rel=\"nofollow noreferrer\"><code>random</code></a>.</p>\n<pre><code>import secrets\n\n...\n\nrng = secrets.SystemRandom()\n\n...\n\n result = rng.randint(1, 6)\n</code></pre>\n<p>The <code>random</code> module provides numbers which are statistically random, but not cryptographically secure; in principle (and if there's enough money involved, also in practice), someone could work out what the next number is likely to be.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T07:53:24.857",
"Id": "478774",
"Score": "1",
"body": "I will keep that in mind. This isn't being used for anthing important, but the secrets module will be someting worth keeping in mind."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T06:22:03.727",
"Id": "243899",
"ParentId": "243895",
"Score": "4"
}
},
{
"body": "<h2>Specific suggestions</h2>\n<ol>\n<li><p>The <code>while True</code> loop at the top is, well, pointless. Why have a section in the program asking whether the user wants to (effectively) run the program?</p>\n</li>\n<li><p><code>re.match(r"^[yn]$", confirmation, flags=re.IGNORECASE)</code> implies <code>len(confirmation) == 1</code>, so you could consider the length check redundant. The same goes for <code>count</code>.</p>\n</li>\n<li><p>You end up effectively converting the case of <code>confirmation</code> thrice:</p>\n<ul>\n<li><code>re.match(r"^[yn]$", confirmation, flags=re.IGNORECASE)</code></li>\n<li><code>confirmation.casefold() == "n"</code></li>\n<li><code>confirmation.casefold() == "y"</code></li>\n</ul>\n<p>By instead converting <code>confirmation</code> to lowercase before doing <em>any</em> of these you can do a case <em>sensitive</em> match, which is simpler code and faster.</p>\n</li>\n<li><p><code>r"^[0-9]*$"</code> includes matches for the empty string. What you probably want is <code>r"^[0-9]+$"</code>, which looks for <em>at least one</em> number.</p>\n</li>\n<li><p>The last <code>else</code> should just run <code>break</code>; then <code>p = inflect.engine()</code> etc can be moved outside the loop for clarity.</p>\n</li>\n<li><p>This code isn't really reusable. Almost 100% of Python scripts you will ever find in <em>production</em> systems will be reusable. This means they are:</p>\n<ul>\n<li><p><em>Non-interactive.</em> In this case, that means removing the <code>input</code>s, instead either using <code>argparse</code> or something to get a single parameter containing the number of dies you want to print, or very simply just printing one die number.</p>\n</li>\n<li><p><em>Importable.</em> Typically there are three parts to this: an entrypoint (in your case this could be a very simple function which prints a single random number in the specified range), a <code>main</code> method which takes care of reading command line parameters and running the entrypoint, and this magic:</p>\n<pre><code> if __name__ == "__main__":\n main()\n</code></pre>\n</li>\n</ul>\n<p>The last bit runs the <code>main</code> method when the script is called from the command line. The entrypoint can then be imported from any other script and reused trivially.</p>\n</li>\n</ol>\n<h2>Tool support suggestions</h2>\n<ol>\n<li><p><a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic. It'll do things like adjusting the vertical and horizontal spacing, while keeping the functionality of the code unchanged.</p>\n</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\"><code>flake8</code></a> can give you hints to write idiomatic Python. I would start with this configuration:</p>\n<pre><code> [flake8]\n max-complexity = 4\n ignore = W503,E203\n</code></pre>\n<p>This would for example detect that you have a redundant import (<code>time</code>).</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T22:16:31.053",
"Id": "478890",
"Score": "0",
"body": "A confirmation step is only relevant when the script does something potentially destructive. Printing to screen is not destructive, and consider that the confirmation prompt prints much more than the actual functionality of the script… About learning to use `input` I can only say that it's unlikely to be useful in practice. It's an unfortunate practice in education to always teach how to have an interactive two-way conversation when really you just want the code to do a thing with minimal fuss."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T22:17:10.207",
"Id": "478891",
"Score": "0",
"body": "1) This I find is a very common disagreement among a lot of programmers. Some preferring a confirmation step for safety. Others not feeling any need. But the while loop was there to learn how to keep asking for y/n if you were to input let's say \"a\" \n\n2) I do see how that's redundant, thank you \n\n3) I do see how it is more efficient to do casefold earlier on and only once\n\n4) I can see how \"+\" is more clear, but the \"*\" is still working as intended, only returning when there is at least one number"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T22:17:47.667",
"Id": "478892",
"Score": "0",
"body": "5)) It is not run every iteration of the loop. It is not in the for loop, and the loop only gets to that elif once in the program. But if I were to do something else it would make it run every time possibly.\n\n6) Can you go into this more? I don't understand fully.\n\nI will also look into these tools"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T22:20:17.003",
"Id": "478893",
"Score": "0",
"body": "\"This I find is a very common disagreement among a lot of programmers.\" In about 10 years of using Python I don't think I've ever used `input`. I've only ever seen it in toy code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T22:21:23.797",
"Id": "478894",
"Score": "0",
"body": "'the \"`*`\" is still working as intended, only returning when there is at least one number.' No, `*` means zero or more of the preceding expression. The only reason it works is that you *also* check the length separately, which is unnecessary if you use `+` instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T22:27:01.457",
"Id": "478895",
"Score": "0",
"body": "\"It is not run every iteration of the loop.\" You're right, fixed."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T10:28:34.653",
"Id": "243911",
"ParentId": "243895",
"Score": "6"
}
},
{
"body": "<p>A few things in your code seem redundant (Most of these have been remarked well by previous answers) - Although perhaps I am missing some specific reasons for your choices and its also good to remember there are tonnes of answers for programming questions - This is my take on your functionality aim:</p>\n<pre><code>import random\nimport inflect\n\np = inflect.engine()\n\nwhile True:\n confirmation = input("Would you like to roll some dice?(y/n) > ")\n if confirmation == "y":\n while True:\n count = input("How many dice would you like to roll? > ")\n if len(count) == 0:\n print("Error! Please input something!")\n elif not count.isnumeric():\n print("Error! You may only input numbers")\n else:\n [print("The " + p.number_to_words(p.ordinal(i)) + " die rolled a: " \n + str(random.randint(1, 6))) for i in range(1, int(count))]\n break\n elif confirmation == "n":\n print("No dice have been rolled")\n else:\n print("Error! Only y and n are valid") if len(confirmation) > 1 else print("Error! You may only input one character")\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T09:21:24.117",
"Id": "243968",
"ParentId": "243895",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T04:55:28.457",
"Id": "243895",
"Score": "6",
"Tags": [
"python",
"python-3.x"
],
"Title": "Die-rolling program"
}
|
243895
|
<p>Submitting for review by experts.</p>
<p>Inspired by <a href="https://stackoverflow.com/a/62367589/9808063">this question</a> to color value cell having duplicates with a different color. So "Apple" will have one color for all duplicates. Then "Banana" will have a different color for all its duplicates. What if number of such values exceeds 56 (max number of <a href="https://docs.microsoft.com/en-us/office/vba/api/excel.colorindex" rel="nofollow noreferrer">ColorIndex property</a> ?</p>
<p>With this function I am trying to create array of all possible combinations in a given range and step of RGB colors in VBA.</p>
<p>Starting from 1 and ending 255 there are <code>256*256*256 = 16,777,216</code> (1 is added for absence of color, 0) unique combinations of RGB colors. More than enough for all excel rows :) Refer <a href="https://stackoverflow.com/a/20487795/9808063">this stackoverflow link</a>. However Excel permits only 64000 format styles. Refer <a href="https://docs.microsoft.com/en-us/office/troubleshoot/excel/too-many-different-cell-formats-in-excel#:%7E:text=Cause,are%20applied%20to%20a%20cell." rel="nofollow noreferrer">docs.microsoft.com</a></p>
<pre><code>Function RGBColorArray(Optional StartCol As Byte = 150, Optional EndCol As Byte = 240, _
Optional Calc_ColStep As Boolean = True, Optional ColStep As Byte = 1, _
Optional Number_of_Cells As Long = 1, Optional Skip_Black As Boolean = False) As Variant
'This function gives array of combinations of colors
'Function will return error if StartCol or EndCol > 255
'StartCol is the color number from where to start. Say 150 default value
'EndCol is the color number where to end. Say 240 as default value
'Default 240 - 150 = 90 gives 90*90*90 = 729000 unique color combinations, enough for excel
'However Excel permits only 64000 format styles.
'Refer https://docs.microsoft.com/en-us/office/troubleshoot/excel/too-many-different-cell-formats-in-excel#:~:text=Cause,are%20applied%20to%20a%20cell.
'ColStep is the desired gap/interval between the two consecutive color combinations
'If every color combination is desired then ColStep = 1
'If every 5th color combination is desired then ColStep = 5
Start:
If Calc_ColStep = True Then
ColStep = (EndCol - StartCol) / WorksheetFunction.Max(((WorksheetFunction.RoundUp(Application.Power(Number_of_Cells, 1 / 3), 0)) - 2), 1)
If ColStep < 1 Then 'This could happen if color range (end-start) is not enough for Number of cells is
StartCol = 150
EndCol = 240
GoTo Start
End If
End If
Dim RndEndCol As Integer
RndEndCol = StartCol + WorksheetFunction.MRound(EndCol - StartCol, ColStep)
If RndEndCol > 255 Then
EndCol = EndCol - ColStep
'Though this could be EndCol = RndEndCol - ColStep but it returns the same result of final array.
End If
Dim r As Byte, g As Byte, b As Byte, x As Byte, i As Long, j As Byte, k As Byte, l As Long
Dim arr As Variant, arrVal As Variant
x = 2 + (EndCol - StartCol) / ColStep
ReDim arr(1 To x ^ 3, 1 To 3)
StartCol = StartCol - ColStep
'_________________________________________
r = 0: l = 0
For i = 1 To x
g = 0
For j = 1 To x
b = 0
For k = 1 To x
l = l + 1
arr(l, 1) = r
arr(l, 2) = g
arr(l, 3) = b
If b = 0 Then
b = StartCol + ColStep
Else
If b <> 0 And k < x Then b = b + ColStep
End If
Next
If b = 0 Then
b = StartCol + ColStep
Else
If b <> 0 And k < x Then b = b + ColStep
End If
If g = 0 Then
g = StartCol + ColStep
Else
If g <> 0 And j < x Then g = g + ColStep
End If
Next
If b = 0 Then
b = StartCol + ColStep
Else
If b <> 0 And k < x Then b = b + ColStep
End If
If g = 0 Then
g = StartCol + ColStep
Else
If g <> 0 And j < x Then g = g + ColStep
End If
If r = 0 Then
r = StartCol + ColStep
Else
If r <> 0 And i < x Then r = r + ColStep
End If
Next
If Skip_Black = True Then
For i = 2 To UBound(arr)
arr(i - 1, 1) = arr(i, 1): arr(i - 1, 2) = arr(i, 2): arr(i - 1, 3) = arr(i, 3)
Next i
End If
RGBColorArray = arr
End Function
</code></pre>
<p>So, following procedure will color range E1:E125 with different RGB color combinations returned by the above function. Function is <code>RGBColorArray(150, 240, False, 30, , False)</code>. 125 cells is result of 5 step colors (0,150,180,210,240). So, <code>5*5*5 = 125</code></p>
<pre><code>Sub ColorMyRange()
' This procedure colors each cell in a given range/ selection with unique color
Dim Number_of_Cells As Long, RGB_Start As Byte, RGB_End As Byte, rng As Range
Dim cell As Range, arr As Variant, i As Long, j As Long, x As Long
Set rng = Selection 'WWWWWWW Enter this Range
Number_of_Cells = rng.Cells.Count
RGB_Start = 10 'WWWWWWW Enter this value or default is 150
RGB_End = 240 'WWWWWWW Enter this value or default if 240
'If this color range is not enough for number of cells then formula uses default.
arr = RGBColorArray(RGB_Start, RGB_End, , , Number_of_Cells, True)
'True for skipping first combination row of RGBColorArray of black color RGB(0,0,0)
x = UBound(arr, 1)
Debug.Print UBound(arr, 1) & vbTab & UBound(arr, 2)
i = 1
For Each cell In Selection
cell = arr(i, 1) & " | " & arr(i, 2) & " | " & arr(i, 3)
cell.Interior.Color = RGB(arr(i, 1), arr(i, 2), arr(i, 3))
i = i + 1
Application.StatusBar = i
Next
End Sub
</code></pre>
<p>Column A, B and C contains array of <code>RGBColorArray</code> function</p>
<p><a href="https://i.stack.imgur.com/zYk2t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zYk2t.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/1Ez0L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1Ez0L.png" alt="enter image description here" /></a></p>
<p>With following function we can calculate <code>ColStep</code> for the <code>RGBColorArray</code> function.</p>
<pre><code>Function Calculate_ColStep(Number_of_Cells As Long, RGB_Start As Byte, RGB_End As Byte)
Calculate_ColStep = (RGB_End - RGB_Start) / ((WorksheetFunction.RoundUp(Application.Power(Number_of_Cells, 1 / 3), 0)) - 2)
End Function
</code></pre>
<p>Following function returns second half of the <code>RGBColorArray</code> upside down.</p>
<pre><code>Function TwoDArraySecondHalf(myArray)
Dim myArray2ndHalf() As Variant
Dim a As Long, xa As Long, xb As Long, x2 As Long, b As Long, y As Long
Dim i As Long, j As Long
a = LBound(myArray, 1): xa = UBound(myArray, 1)
b = LBound(myArray, 2): y = UBound(myArray, 2)
xb = Int(xa / 2)
ReDim myArray2ndHalf(1 To (xa - xb), 1 To 3)
x2 = UBound(myArray2ndHalf, 1)
j = 1
For i = xa To (xb + 1) Step -1
myArray2ndHalf(j, 1) = myArray(i, 1)
myArray2ndHalf(j, 2) = myArray(i, 2)
myArray2ndHalf(j, 3) = myArray(i, 3)
j = j + 1
Next
TwoDArraySecondHalf = myArray2ndHalf
End Function
</code></pre>
<p>Using above functions in following procedure, we can color selected cells with alternate (dark/bright) unique colors while skipping black color (first element of <code>RGBColorArray</code>, <code>RBG(0,0,0)</code>)</p>
<pre><code>Sub ColorMyRangeAltCol()
' This procedure colors each cell in a given range/ selection with unique color
Dim Number_of_Cells As Long, RGB_Start As Byte, RGB_End As Byte, rng As Range
Dim cell As Range, arr As Variant, arr2 As Variant, i As Long, j As Long, x As Long
Dim Cell_Address As New Collection
Set rng = Selection 'WWWWWWW Enter this Range
Number_of_Cells = rng.Cells.Count
If Application.Power(Number_of_Cells, (1 / 3)) Mod 1 = 0 Then
Number_of_Cells = Number_of_Cells + 1
End If
RGB_Start = 215 'WWWWWWW Enter this value or default is 150
RGB_End = 216 'WWWWWWW Enter this value or default if 240
'If this color range is not enough for number of cells then formula uses default.
arr = RGBColorArray(RGB_Start, RGB_End, , , Number_of_Cells, True)
'True for skipping first combination row of RGBColorArray of black color RGB(0,0,0)
x = UBound(arr, 1)
arr2 = TwoDArraySecondHalf(arr)
arr = Application.Transpose(arr)
ReDim Preserve arr(1 To UBound(arr, 1), 1 To (UBound(arr, 2) - UBound(arr2, 1)))
arr = Application.Transpose(arr)
For Each cell In Selection
Cell_Address.Add cell.Address
Next
i = 1
For j = 1 To Cell_Address.Count Step 2
Range(Cell_Address(j)) = arr(i, 1) & " | " & arr(i, 2) & " | " & arr(i, 3)
Range(Cell_Address(j)).Interior.Color = RGB(arr(i, 1), arr(i, 2), arr(i, 3))
If i > Cell_Address.Count / 2 Then Exit For
Range(Cell_Address(j + 1)) = arr2(i, 1) & " | " & arr2(i, 2) & " | " & arr2(i, 3)
Range(Cell_Address(j + 1)).Interior.Color = RGB(arr2(i, 1), arr2(i, 2), arr2(i, 3))
i = i + 1
Next
End Sub
</code></pre>
<p>Following image shows such example for 250 cells.
<a href="https://i.stack.imgur.com/A3Sg6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A3Sg6.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/egQTl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/egQTl.png" alt="enter image description here" /></a></p>
<p>With following procedure, we can randomly color each cell as shown in the image below.</p>
<pre><code>Sub RandomColorMyRange()
' This procedure colors each cell in a given range/ selection with unique random color
Dim Number_of_Cells As Long, RGB_Start As Byte, RGB_End As Byte, rng As Range
Dim cell As Range, arr As Variant, i As Long, j As Long, x As Long
Dim ColorsColl As New Collection
Set rng = Selection 'WWWWWWW Enter this Range
Number_of_Cells = rng.Cells.Count
RGB_Start = 100 'WWWWWWW Enter this value or default is 150
RGB_End = 240 'WWWWWWW Enter this value or default if 240
'If this color range is not enough for number of cells then formula uses default.
arr = RGBColorArray(RGB_Start, RGB_End, , , Number_of_Cells, True)
'True for skipping first combination row of RGBColorArray of black color RGB(0,0,0)
x = UBound(arr, 1)
For j = 1 To UBound(arr, 1)
ColorsColl.Add arr(j, 1) & " | " & arr(j, 2) & " | " & arr(j, 3)
Next
ColorsColl.Remove (ColorsColl.Count)
'for removing last duplicate color caused by Skip_Black = True in the RGBColorArray function
For Each cell In Selection
i = WorksheetFunction.RandBetween(1, ColorsColl.Count)
cell = ColorsColl.Item(i)
cell.Interior.Color = RGB(Split(ColorsColl.Item(i), "|")(0), _
Split(ColorsColl.Item(i), "|")(1), _
Split(ColorsColl.Item(i), "|")(2))
ColorsColl.Remove (i)
Application.StatusBar = ColorsColl.Count
Next
End Sub
</code></pre>
<p><a href="https://i.stack.imgur.com/yvTS9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yvTS9.png" alt="enter image description here" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T08:03:29.130",
"Id": "478777",
"Score": "0",
"body": "Is there a reason you went to 240 instead of 255?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T09:21:03.750",
"Id": "478785",
"Score": "0",
"body": "No , that is just for example to show how we can select the bottom and the top end. Like 120-220, 150-250, etc."
}
] |
[
{
"body": "<p>I am posting this as an answer after many edits to the question and trials of the array function. Best one can be seen in <a href=\"https://www.youtube.com/watch?v=IM4rwlzs5_8\" rel=\"nofollow noreferrer\">this YouTube video</a>. Fixed errors and following function is the result. Please suggest improvements. Thank you</p>\n<pre><code>Option Explicit\n'WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW\nFunction Color_Array(Optional RGB_Array As Boolean = False, Optional Number_of_Cells As Long = 1, _\n Optional First_Shade As Byte = 140, Optional Last_Shade As Byte = 240, _\n Optional Shade_Step As Byte = 25, Optional Skip_Black As Boolean = True)\n'--------------------------------------------------------------------------------------------\n'This function gives array of combinations of RGB colors\n'There are two array options\n' -- > (1) RGB Array (values for red, green and blue) For this ensure "RGB_Array" boolean is true\n' -- > (2) Long Color Values. For this ensure "RGB_Array" boolean is false\n'First_Shade is the color number from where to start. Say 140 default value\n'Last_Shade is the color number where to end. Say 240 as default value\n'Default 240 - 150 = 90 gives 90*90*90 = 729000 unique color combinations, enough for excel\n'However, Excel permits only 64000 format styles.\n'Refer https://docs.microsoft.com/en-us/office/troubleshoot/excel/too-many-different-cell-formats-in-excel#:~:text=Cause,are%20applied%20to%20a%20cell.\n'Shade_Step is the desired gap/interval between the two consecutive shades\n'If every color combination is desired then Shade_Step = 1\n'Say, if every 5th color combination is desired then Shade_Step = 5\n'We can skip the first black color RGB(0,0,0), with Skip_Black = True\n'--------------------------------------------------------------------------------------------\n'Declaration of variables\nDim r As Byte, g As Byte, b As Byte ', Shade_Step As Byte\nDim i As Byte, j As Byte, k As Byte, l As Long, Number_Of_Shades As Long\nDim arr As Variant\n'--------------------------------------------------------------------------------------------\n'Caculations of variable values\nNumber_Of_Shades = WorksheetFunction.RoundUp((Number_of_Cells + 1) ^ (1 / 3), 0)\nShade_Step = WorksheetFunction.Min(Shade_Step, WorksheetFunction.RoundDown(((Last_Shade - First_Shade + 2) / (Number_Of_Shades - 1)), 0))\n'--------------------------------------------------------------------------------------------\n'Sizing array depending on whether RGB_Array and Skip_Black booleans are true or false\nIf RGB_Array = True Then\n If Skip_Black = True Then\n ReDim arr(1 To ((Number_Of_Shades ^ 3) - 1), 1 To 3)\n Else\n ReDim arr(1 To Number_Of_Shades ^ 3, 1 To 3)\n End If\nElse\n If Skip_Black = True Then\n ReDim arr(1 To ((Number_Of_Shades ^ 3) - 1), 1 To 1)\n Else\n ReDim arr(1 To Number_Of_Shades ^ 3, 1 To 1)\n End If\nEnd If\n'--------------------------------------------------------------------------------------------\n'Loop populating array\nr = 0\nl = 0\nFor i = 1 To Number_Of_Shades\n g = 0\n For j = 1 To Number_Of_Shades\n b = 0\n For k = 1 To Number_Of_Shades\n l = l + 1\n'--------------------------------------\n'Populate array depending on whether RGB_Array and Skip_Black booleans are true or false\n If RGB_Array = True Then\n If Skip_Black = True And l > 1 Then\n arr(l - 1, 1) = r\n arr(l - 1, 2) = g\n arr(l - 1, 3) = b\n Else\n arr(l, 1) = r\n arr(l, 2) = g\n arr(l, 3) = b\n End If\n Else\n If Skip_Black = True And l > 1 Then\n arr(l - 1, 1) = RGB(r, g, b)\n Else\n arr(l, 1) = RGB(r, g, b)\n End If\n End If\n'--------------------------------------\n If b = 0 Then b = First_Shade Else b = b + Shade_Step\n Next\n If g = 0 Then g = First_Shade Else g = g + Shade_Step\n Next\n If r = 0 Then r = First_Shade Else r = r + Shade_Step\nNext\n'--------------------------------------------------------------------------------------------\nColor_Array = arr\nEnd Function\n'WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW\n</code></pre>\n<p>Here is VBA code for <a href=\"https://www.youtube.com/watch?v=IM4rwlzs5_8\" rel=\"nofollow noreferrer\">the YouTube video</a>.</p>\n<pre><code>Sub RandomColorMyRange()\n' This procedure colors each cell in a given range/ selection with unique random color\nDim Number_of_Cells As Long, RGB_Start As Byte, RGB_End As Byte, rng As Range\nDim cell As Range, arr As Variant, i As Long, j As Long, x As Long\nDim ColorsColl As New Collection, CellAddress As New Collection\n\nSet rng = Selection 'WWWWWWW Enter this Range\nNumber_of_Cells = rng.Cells.Count\n\nRGB_Start = 100 'WWWWWWW Enter this value or default is 150\nRGB_End = 240 'WWWWWWW Enter this value or default if 240\n'If this color range is not enough for number of cells then formula uses default.\n\narr = Color_Array(False, Number_of_Cells, RGB_Start, RGB_End, 50, True)\n'First boolena RGB_Array = false\n'Second boolean Skip_Blank = True for skipping first row black color RGB(0,0,0)\n'enter max shade_step (upto 255) for max rnage of colors\nx = UBound(arr, 1)\n\nFor j = 1 To UBound(arr, 1)\nColorsColl.Add arr(j, 1)\nNext\n\nFor Each cell In Selection\nCellAddress.Add cell.Address\nNext\n\nFor Each cell In Selection\n i = WorksheetFunction.RandBetween(1, ColorsColl.Count)\n j = WorksheetFunction.RandBetween(1, CellAddress.Count)\n \n If CellAddress.Count <> 1 Then\n Range(CellAddress.Item(j)) = ColorRGBValue(ColorsColl.Item(i), 2)\n Range(CellAddress.Item(j)).Interior.Color = ColorsColl.Item(i)\n ColorsColl.Remove (i)\n CellAddress.Remove (j)\n \n Else\n Range(CellAddress.Item(1)) = ColorRGBValue(ColorsColl.Item(i), 2)\n Range(CellAddress.Item(1)).Interior.Color = ColorsColl.Item(i)\n End If\n Application.StatusBar = CellAddress.Count\nNext\n\nEnd Sub\n</code></pre>\n<p>Following is additional procedure</p>\n<pre><code>Sub ColorMyRange() 'Not random\n' This procedure colors each cell in a given range (or selection) with unique color at given shade_step\nDim Number_of_Cells As Long, RGB_Start As Byte, RGB_End As Byte, rng As Range\nDim cell As Range, arr As Variant, i As Long, j As Long, x As Long\nDim Cell_Address As New Collection\n\nSet rng = Selection 'WWWWWWW Enter this Range\nNumber_of_Cells = rng.Cells.Count\n\nRGB_Start = 100 'WWWWWWW Enter this value or default is 150\nRGB_End = 240 'WWWWWWW Enter this value or default if 240\n'If this color range is not enough for number of cells then formula uses default.\n\narr = Color_Array(False, Number_of_Cells, RGB_Start, RGB_End, 200, True)\n'First boolena RGB_Array = false\n'Second boolean Skip_Blank = True for skipping first row black color RGB(0,0,0)\n'enter max shade_step (upto 255) for max rnage of colors\nx = UBound(arr, 1)\n'Debug.Print UBound(arr, 1) & vbTab & UBound(arr, 2)\ni = 1\nFor Each cell In Selection\n cell = ColorRGBValue(arr(i, 1), 2)\n cell.Interior.Color = arr(i, 1) 'RGB(arr(i, 1), arr(i, 2), arr(i, 3))\n i = i + 1\n Application.StatusBar = i\nNext\n\nEnd Sub\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/k0diR.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/k0diR.gif\" alt=\"enter image description here\" /></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T15:09:18.987",
"Id": "480602",
"Score": "0",
"body": "`ColorRGBValue` function used in both the procedures above is [this function](https://stackoverflow.com/a/24216193) named differently."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T08:46:12.150",
"Id": "244096",
"ParentId": "243897",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T05:28:33.933",
"Id": "243897",
"Score": "4",
"Tags": [
"vba",
"excel"
],
"Title": "VBA function for array of RGB color combinations and procedure to color large number of cells with unique colors"
}
|
243897
|
<p>If the user/visitor has access to the API route, then the status code will 200, else 401.
I know that I can user Vue navigation guards, but I will need to use Vuex.</p>
<p>This way is much simpler and faster, what do you think, is it a right way to protect Vue page from unauthenticated users?</p>
<pre><code> <template>
<v-container>
<div v-if="isAuthenticated === false">loading</div>
<div v-else>Protected Profile Page</div>
</v-container>
</template>
<script>
export default {
data () {
return {
isAuthenticated : false,
}
},
beforeCreate: async function() {
axios.get('api/user', {})
.then(res => {
this.isAuthenticated = true;
}).catch(err => {
this.isAuthenticated = false;
this.$router.push('/login');
})
},
created () {
console.log('isAuthenticated', this.isAuthenticated) // return false
}
}
</script>
</code></pre>
|
[] |
[
{
"body": "<p>In theory what you do here works, but there are a few caveats:</p>\n<ul>\n<li>You declared your <code>beforeCreate</code> lifecycle hook as <code>async</code>, but you do not <code>await</code> any statement. It serves no particular purpose.</li>\n<li>Be very careful with declaring lifecycle hooks as asynchronous, because when you await something that rejects the promise, you cannot catch the resulting error. You will end up with a component that cannot render, which makes for a bad user experience.</li>\n<li>Vue router has global navigation guards, but you can actually also just declare a route guard on the component that is being mounted. They are called <a href=\"https://router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards\" rel=\"nofollow noreferrer\">in-component guards</a> and one that would be useful to you is <code>beforeRouteEnter</code>. You can redirect someone to the login page before this component even renders.</li>\n</ul>\n<pre><code>beforeRouteEnter (to, from, next) {\n axios.get('api/user', {})\n .then(_ => {\n next();\n }).catch(_ => {\n next('/login');\n });\n}\n</code></pre>\n<ul>\n<li>While you could rely on the endpoint returning an error of some sort, there are more reasons why your endpoint might return an error. Some of those reasons might include rate limiting of the api, a bad connection or an overloaded server. Having someone redirect to the login page everytime that happens will get old fast. If you want to protect multiple components this way, you are spamming your server with unnecessary api calls. Also keep in mind that frontend security is essentially no security at all. You only "protect" stuff in the frontend to help the user experience, but your api should never return data or save data from a user that has no permissions/is not logged in. You are likely better off catching 403 errors and only redirecting them, while showing a generic error message on anything else.</li>\n</ul>\n<p>You have already mentioned it, but you could use Vuex for state management. Arguably, something like "isAuthenticated" is not something every singular component should manage. Setting up a vuex store is usually less than 5 minutes work and I would still recommend managing something like that there.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T19:47:16.390",
"Id": "249967",
"ParentId": "243905",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249967",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T09:13:25.530",
"Id": "243905",
"Score": "4",
"Tags": [
"laravel",
"vue.js"
],
"Title": "Protecting Vue page based on the API response"
}
|
243905
|
<p>Link to problem: <a href="https://www.codechef.com/JUNE20B/problems/EVENM" rel="nofollow noreferrer">https://www.codechef.com/JUNE20B/problems/EVENM</a></p>
<p>Iam trying to solve a simple problem challenge, but getting TLE.</p>
<p>I had a different approach earlier, so tried this, again with no success.</p>
<p>I know this can be optimized further but can't figure how.</p>
<p>The problem: Print the matrix in a format depending upon the input.</p>
<p>If input is divisible by 2 then in this format:</p>
<p><a href="https://i.stack.imgur.com/f5MqY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f5MqY.jpg" alt="enter image description here" /></a></p>
<p>else in this format:</p>
<p><a href="https://i.stack.imgur.com/zv6B3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zv6B3.jpg" alt="enter image description here" /></a></p>
<p>Time limit: 1 sec</p>
<p>nxn matrix, where 1<=n<=1000</p>
<p>My code:</p>
<pre><code>BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int cases = Integer.parseInt(br.readLine());
for(int i = 0; i < cases; i++) {
int n = Integer.parseInt(br.readLine());
if(n%2==1) {
int cur = 0;
for(int j = 1; j <= n; j++) {
for(int k = 1; k <= n; k++) {
System.out.print(++cur);
if(k!=n) System.out.print(" ");
}
System.out.println();
}
}
else {
int first = 0;
boolean b = true;
for(int j = 1; j <= n; j++) {
for(int k = 1; k <= n; k++) {
if(b) System.out.print(++first);
else System.out.print(first--);
if(k!=n) System.out.print(" ");
}
if(b)b = false;
else b = true;
first+=n;
System.out.println();
}
}
}
</code></pre>
<p>According to the judge, this is taking slightly more than 2 seconds, which is double the time expected, so this is totally un-optimized</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T09:36:15.453",
"Id": "478786",
"Score": "5",
"body": "Welcome to Code Review. The title is of your question is too general and can be applied to a lot of questions present on the site, please change it to describe the problem. If you have a link to the programming challenge please include it, at the moment without looking the code at least for me it is unclear the description of the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T10:41:17.773",
"Id": "478795",
"Score": "0",
"body": "(I don't see anything in the *algorithm* that could be improved to lower asymptotic time.)"
}
] |
[
{
"body": "<p>First off I think your code can be adjusted:</p>\n<p>Booleans to keep track of even or odd size of matrix and even or odd numbered rows allows you to use one set of loops and simply change which set of numbers are printed.</p>\n<p>To test for odd or even I like <code>(num & 1)</code> if the result is 0 it's even, 1 it's odd. I think using modulus for this is inefficient.</p>\n<p>Changing the code to using one loop could look something like this:</p>\n<pre><code>static void solution(InputStream sIn, PrintStream sOut) throws IOException {\n Scanner sc = new Scanner(sIn);\n int cases = sc.nextInt();\n for (int c = 0; c < cases; ++c) {\n int size = sc.nextInt();\n boolean evenM = (size & 1) == 0;\n for (int row = 0; row < size; ++row) {\n boolean oddR = (row & 1) == 1;\n for (int col = 0; col < size; ++col) {\n boolean last = col == size - 1;\n int num = (row * size) + col + 1;\n if (evenM && oddR) {\n num = (num - col) + (size - col) - 1;\n if (last) {\n sOut.print(num);\n } else {\n sOut.printf("%d ", num);\n }\n } else if (last) {\n sOut.print(num);\n } else {\n sOut.printf("%d ", num);\n }\n }\n sOut.println();\n }\n }\n}\n</code></pre>\n<p>All that being said, I think your main problem is Java itself, or the implementation that CodeChef is using. When I port this code to c++ it works just fine and can be submitted successfully.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T20:22:29.760",
"Id": "243945",
"ParentId": "243906",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T09:15:57.300",
"Id": "243906",
"Score": "-4",
"Tags": [
"java",
"performance",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Time limit exceeds in this simple program"
}
|
243906
|
<p>So this is a modern implementation of a HTTP client, trying to find a way to optimise/simplify this.
Specifically the DeserializeAsync method with the GetStream and the compiler statement for if/debug is a bit messy and I would love for a way to simplify it, but I don't want to remove the debug statement because I love to get the raw http response back in case the data models is changed by the back end team but it would be great if it was a bit simpler/clearer</p>
<pre><code>// You should not dispose of HTTP client, so disable in this file.
#pragma warning disable CA2000 // Dispose objects before losing scope
namespace x
{
/// <summary>
/// The request provider holds our Get/Put request to our APIs in generic format.
/// Implement this class in your services and use this to make requests to the API.
/// </summary>
public class RequestProvider : IRequestProvider
{
/// <summary> Json serialization rules </summary>
private static JsonSerializerOptions _serializerOptions;
/// <summary> Initializes a new instance of the <see cref="RequestProvider" /> class. </summary>
public RequestProvider()
{
_serializerOptions = new JsonSerializerOptions { WriteIndented = true, PropertyNameCaseInsensitive = true, };
}
/// <summary> Returns the static method </summary>
public Task DeleteAsync(Uri uri, CancellationToken cancellationToken, string token = "")
{
return DeleteRequest(uri, cancellationToken, token);
}
/// <summary> Returns the static method </summary>
public Task<TResult> GetAsync<TResult>(Uri uri, CancellationToken cancellationToken, string token = "")
{
return GetAsyncStream<TResult>(uri, cancellationToken, token);
}
/// <summary> The post async posts data to an API when logged in </summary>
/// <param name="uri"> The uri we are posting to. </param>
/// <param name="data"> The data we are posting. </param>
/// <param name="cancellationToken"> Used to cancel the job </param>
/// <param name="token"> The token identifying who we are. </param>
/// <param name="header"> The header type we are using to post with HTTP client. </param>
/// <typeparam name="TResult"> returns the generic results </typeparam>
/// <returns> The result of the task is returned. <see cref="Task" />. </returns>
public Task<TResult> PostAsync<TResult>(
Uri uri,
TResult data,
CancellationToken cancellationToken,
string token = "",
string header = "")
{
return PostAsyncStream(uri, data, token, header, cancellationToken);
}
/// <summary> Send POST request to API from unauthenticated user </summary>
/// <param name="uri"> The uri we are posting to. </param>
/// <param name="data"> The data we are posting. </param>
/// <param name="clientId"> The client id (who we are, i.e mobile). </param>
/// <param name="clientSecret"> The client secret is an encryption to secure our token </param>
/// <param name="cancellationToken"> Used to cancel the job </param>
/// <typeparam name="TResult"> The result if it is success or failure </typeparam>
/// <returns> The task is returned <see cref="Task" />. </returns>
public async Task<TResult> PostAsync<TResult>(
Uri uri,
string data,
string clientId,
string clientSecret,
CancellationToken cancellationToken)
{
var httpClient = CreateHttpClient(string.Empty);
if (!string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(clientSecret))
AddBasicAuthenticationHeader(httpClient, clientId, clientSecret);
var content = new StringContent(data);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response =
await httpClient.PostAsync(uri, content, cancellationToken).ConfigureAwait(false);
content.Dispose();
await HandleResponse(response).ConfigureAwait(false);
var serialized = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var result = await Task.Run(
() => JsonSerializer.Deserialize<TResult>(serialized, _serializerOptions),
cancellationToken).ConfigureAwait(false);
return result;
}
/// <summary> Send a DELETE request to the specified Uri as an asynchronous operation.</summary>
/// <param name="uri"> The uri we are sending our delete request. </param>
/// <param name="cancellationToken"> Used to cancel the job </param>
/// <param name="token"> The token used by the API to authorize and identify. </param>
/// <returns> The <see cref="Task" />. </returns>
public static Task DeleteRequest(Uri uri, CancellationToken cancellationToken, string token = "")
{
var httpClient = CreateHttpClient(token);
return httpClient.DeleteAsync(uri, cancellationToken);
}
/// <summary> Gets data from API in stream form authenticated users </summary>
/// <param name="uri"> The uri we are sending our get request to. </param>
/// <param name="cancellationToken"> Used to cancel the job </param>
/// <param name="token"> The token identifying who we are. </param>
/// <typeparam name="TResult"> Gets the generic results returned back </typeparam>
/// <returns> The result of the task is returned <see cref="Task" />.</returns>
public static async Task<TResult> GetAsyncStream<TResult>(
Uri uri,
CancellationToken cancellationToken,
string token = "")
{
var request = CreateRequest(uri);
var httpClient = CreateHttpClient(token);
var response = await httpClient.SendAsync(
request,
HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
await HandleResponse(response).ConfigureAwait(false);
return await DeserializeAsync<TResult>(response, cancellationToken).ConfigureAwait(false);
}
/// <summary> Enables us to connect to sites with localhost as certificate, enables GZIP decompression </summary>
/// <returns> The <see cref="HttpClientHandler" />. </returns>
public static HttpClientHandler GetHttpHandler()
{
var handler = new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip,
ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
{
if (cert.Issuer.Equals("CN=localhost", StringComparison.Ordinal)) return true;
return errors == SslPolicyErrors.None;
}
};
return handler;
}
/// <summary> Post a stream to the API </summary>
/// <param name="uri"> The uri we are sending our get request to. </param>
/// <param name="data"> The data we use to query the API (ex: userID) </param>
/// <param name="token"> The token identifying who we are. </param>
/// <param name="header"> The header type we are using to post with HTTP client. </param>
/// <param name="cancellationToken"> Used to cancel the job </param>
/// <typeparam name="TResult"> Generic param so we can return any object </typeparam>
/// <returns> The <see cref="Task" />. </returns>
public static async Task<TResult> PostAsyncStream<TResult>(
Uri uri,
TResult data,
string token,
string header,
CancellationToken cancellationToken)
{
var httpClient = CreateHttpClient(token);
if (!string.IsNullOrEmpty(header)) AddHeaderParameter(httpClient, header);
var content = new StringContent(JsonSerializer.Serialize(data, _serializerOptions));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response =
await httpClient.PostAsync(uri, content).ConfigureAwait(false);
await HandleResponse(response).ConfigureAwait(false);
return await DeserializeAsync<TResult>(response, cancellationToken).ConfigureAwait(false);
}
/// <summary> The add basic authentication header. </summary>
/// <param name="httpClient"> The http client in use </param>
/// <param name="clientId"> The client id (who we are, i.e mobile). </param>
/// <param name="clientSecret"> The client secret is an encryption to secure our token </param>
private static void AddBasicAuthenticationHeader(HttpClient httpClient, string clientId, string clientSecret)
{
if (httpClient == null) return;
if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(clientSecret)) return;
httpClient.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(clientId, clientSecret);
}
/// <summary> Adds the header to the http client </summary>
/// <param name="httpClient"> The http client in use </param>
/// <param name="parameter"> The parameter is what we put into the header </param>
private static void AddHeaderParameter(HttpClient httpClient, string parameter)
{
if (httpClient == null) return;
if (string.IsNullOrEmpty(parameter)) return;
httpClient.DefaultRequestHeaders.Add(parameter, Guid.NewGuid().ToString());
}
/// <summary> Creates an http client with token and automatically unzips Gzip files </summary>
/// <param name="token"> The token default value is empty. </param>
/// <returns> The <see cref="HttpClient" /> </returns>
private static HttpClient CreateHttpClient(string token = "")
{
var handler = GetHttpHandler();
var httpClient = new HttpClient(handler);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (string.IsNullOrEmpty(token)) return httpClient;
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
return httpClient;
}
/// <summary> The create request. </summary>
/// <param name="uri"> The uri. </param>
/// <returns> The <see cref="HttpRequestMessage" />. </returns>
private static HttpRequestMessage CreateRequest(Uri uri)
{
return new HttpRequestMessage(HttpMethod.Get, uri);
}
/// <summary> Deserialize Json streams </summary>
/// <param name="response"> The message we got to deserialize </param>
/// <param name="cancellationToken"> Cancellation settings depending on request </param>
/// <typeparam name="TResult"> Generic parameter </typeparam>
/// <returns> The <see cref="Task" />. we return the task </returns>
private static async Task<TResult> DeserializeAsync<TResult>(
HttpResponseMessage response,
CancellationToken cancellationToken)
{
await using var contentStream = await GetStream(response).ConfigureAwait(false);
#if DEBUG
contentStream.Position = 0;
var reader = new StreamReader(contentStream);
var text = await reader.ReadToEndAsync().ConfigureAwait(false);
contentStream.Position = 0;
Debug.WriteLine("RECEIVED: " + text);
#endif
return await JsonSerializer.DeserializeAsync<TResult>(
contentStream,
_serializerOptions,
cancellationToken).ConfigureAwait(false);
}
private static async Task<Stream> GetStream(HttpResponseMessage response)
{
var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
#if DEBUG
var target = new MemoryStream();
await stream.CopyToAsync(target).ConfigureAwait(false);
return target;
#endif
return stream;
}
/// <summary>
/// Handles the response via HTTP via checking if the Https call was valid.
/// If not throws exception.
/// </summary>
/// <param name="response"> The response. </param>
/// <returns> The <see cref="Task" />. </returns>
/// <exception cref="ServiceAuthenticationException"> Throws a service authentication error if not here. </exception>
/// <exception cref="HttpRequestException"> Throws a general HttpRequestException unless forbidden or unauthorized. </exception>
private static async Task HandleResponse(HttpResponseMessage response)
{
if (!response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new ServiceAuthenticationException(response.StatusCode, content);
}
}
}
}
#pragma warning restore CA2000 // Dispose objects before losing scope
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T14:46:27.510",
"Id": "478821",
"Score": "0",
"body": "Hi @JsonDork! What are you looking for? An elegant alternative to `#if DEBUG` ? Or a smarter way to buffer response, like via `LoadIntoBufferAsync` ? Or something else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T09:19:07.250",
"Id": "478956",
"Score": "0",
"body": "No idea! I just feel that it's a big mess that part, it's important for me to write the HTTP response to assist in future debugging endevours but other than that I just feel it's a bit messy in some places an dwant to see if it can be still improved, can't think of any way personally."
}
] |
[
{
"body": "<p>I was think a lot that should I write this answer or not. I don't want to be rude or offensive, but this piece of code is terribly. It has tremendous problems.</p>\n<p>Let me just highlight a couple of them:</p>\n<ol>\n<li><p>Initialization of the <code>JsonSerializationOptions</code>: You have a static variable, which you initialize in your instance level constructor always with the same values.</p>\n</li>\n<li><p>Exposing methods: Your <code>GetAsync</code>, <code>DeleteAsync</code>, <code>PostAsync</code> public functions are just calling the (also exposed) static counterparts (<code>GetAsyncStream</code>, <code>DeleteRequest</code>, <code>PostAsyncStream</code>). The naming inconsistency is just a bonus.</p>\n</li>\n<li><p>Create HttpClient: You should not create for each and every request a new HttpClient. There are hundreds of articles, which warns you. For instance <a href=\"https://thecodebuzz.com/using-httpclient-best-practices-and-anti-patterns/\" rel=\"nofollow noreferrer\">this</a></p>\n</li>\n<li><p>Calling the Dispose manually: You should not call the <code>Dispose</code> manually (like: <code>content.Dispose()</code>)</p>\n</li>\n<li><p>Using <code>Task.Run</code> to deserialize result: I don't understand why do you do that? You also have a function called <code>DeserializeAsync</code>, which is used sometimes and sometimes not.</p>\n</li>\n<li><p>Lack of error handling: Checking just the <code>IsSuccessStatusCode</code> is really poor and naive. And translating every status code that is different than 2xx to <code>ServiceAuthenticationException</code> is ... well, it is not good.</p>\n</li>\n<li><p>etc...</p>\n</li>\n</ol>\n<p>Generally speaking it really hard to follow your code. The comments are pointless, variable names are just echoing their type, functional decomposition is done in the wrong way, like this:</p>\n<pre><code>private static HttpRequestMessage CreateRequest(Uri uri) \n => new HttpRequestMessage(HttpMethod.Get, uri);\n</code></pre>\n<p>So, in summary I'm sorry but I have to say that not the <code>if DEBUG</code> is your biggest problem here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:12:20.803",
"Id": "244115",
"ParentId": "243909",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T10:09:45.077",
"Id": "243909",
"Score": "2",
"Tags": [
"c#",
"http",
"stream"
],
"Title": "Deserialise Json and Read Stream twice in C#"
}
|
243909
|
<p>I have a matrix <code>M</code> of size <code>[n_rows, n_cols]</code> and a list of <code>x</code> and <code>y</code> pixel coordinates. I use these coordinates to draw a binary image. Here is my code:</p>
<pre><code>std::vector<std::vector<double>> x;
std::vector<std::vector<double>> y;
// fill x and y
std::vector<std::vector<unsigned int>> M(n_rows, std::vector<unsigned int>(n_cols));
std::vector<std::vector<double>>::const_iterator iter_row_x = x.begin();
std::vector<std::vector<double>>::const_iterator iter_row_y = y.begin();
for (; iter_row_x != x.end(); ++iter_row_x, ++iter_row_y) {
std::vector<double>::const_iterator iter_col_x = iter_row_x[0].begin();
std::vector<double>::const_iterator iter_col_y = iter_row_y[0].begin();
for (; iter_col_x != iter_row_x[0].end(); ++iter_col_x, ++iter_col_y) {
unsigned int i = unsigned int(*iter_col_x);
unsigned int j = unsigned int(*iter_col_y);
M[i][j] = 1;
}
}
</code></pre>
<p>I would like to know if there is a more elegant way to achieve this? My code above looks a bit bulky and error-prone for such a simple task.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T10:39:17.203",
"Id": "478794",
"Score": "1",
"body": "Do you need 2D-matrices for x and y? Would something like `std::vector<Point> xy` suffice? (where `Point` is a `struct` with members `double x` and `double y`.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T10:44:03.717",
"Id": "478796",
"Score": "0",
"body": "@MikaelH I need 2D-matrices since I have several objects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T10:55:29.060",
"Id": "478797",
"Score": "0",
"body": "Okay, but I assume `std::vector<std::vector<Point>> xy` would be fine?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T10:59:32.733",
"Id": "478798",
"Score": "0",
"body": "@MikaelH For only one object, yes. But I have many objects."
}
] |
[
{
"body": "<p><strong>auto</strong></p>\n<p>Automatic type deduction is especially welcoming for iterators, as their types are bulky. We can rewrite to</p>\n<pre><code>std::vector<std::vector<double>> x;\nstd::vector<std::vector<double>> y;\n\n// fill x and y\n\nstd::vector<std::vector<unsigned int>> M(n_rows, std::vector<unsigned int>(n_cols));\n\nauto iter_row_x = x.cbegin(); //note cbegin to get const_iterator\nauto iter_row_y = y.cbegin();\n\nfor (; iter_row_x != x.end(); ++iter_row_x, ++iter_row_y) {\n auto iter_col_x = iter_row_x->cbegin(); // iter_row_x[0].cbegin() = iter_row_x->cbegin()\n auto iter_col_y = iter_row_y->cbegin();\n for (; iter_col_x != iter_row_x[0].end(); ++iter_col_x, ++iter_col_y) {\n auto i = static_cast<unsigned int>(*iter_col_x); // be explicit about which cast you are using. Now you do not need to specify the type twice.\n auto j = static_cast<unsigned int>(*iter_col_y);\n M[i][j] = 1;\n }\n}\n</code></pre>\n<p>But it's still wordy. Having separate vectors for x and y seems unnecessary, since it is expected that they should be of same length. Better create a structure for xy and create only one vector.</p>\n<pre><code>struct Point \n{\n double x;\n double y;\n}\n</code></pre>\n<p>Then we have</p>\n<pre><code>std::vector<std::vector<Point>> xy;\n\n// fill xy\n\nstd::vector<std::vector<unsigned int>> M(n_rows, std::vector<unsigned int>(n_cols));\n\nfor (auto iter_row_xy = xy.cbegin() ; iter_row_xy != xy.end(); ++iter_row_xy) {\n for (auto iter_col_xy = iter_row_xy->cbegin(); iter_col_x != iter_row_x[0].end(); ++iter_col_x, ++iter_col_y) {\n auto i = static_cast<unsigned int>(*iter_col_xy.x);\n auto j = static_cast<unsigned int>(*iter_col_xy.y);\n M[i][j] = 1;\n }\n}\n</code></pre>\n<p>But we can do even better by using for range:</p>\n<pre><code>std::vector<std::vector<Point>> xy;\n\n// fill xy\n\nstd::vector<std::vector<unsigned int>> M(n_rows, std::vector<unsigned int>(n_cols));\n\nfor (const auto& elements : xy){\n for (const auto& point : elements){\n auto i = static_cast<unsigned int>(point.x);\n auto j = static_cast<unsigned int>(point.y);\n M[i][j] = 1;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T18:31:12.227",
"Id": "478852",
"Score": "4",
"body": "And with C++17 you can use structured bindings to simplify the inner for-loop: `for (auto [x, y]: elements) {unsigned int i = x, j = y; M[i][j] = 1;}`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T11:09:30.463",
"Id": "243912",
"ParentId": "243910",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "243912",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T10:17:57.160",
"Id": "243910",
"Score": "2",
"Tags": [
"c++",
"c++14",
"iterator"
],
"Title": "Generate binary image using coordinate vectors"
}
|
243910
|
<p>This is my first web app written in JS. I would like to know how the code can be improved in terms of style and structure, especially in terms of following JS's conventions and general heuristics. I would also be thankful for any improvements that could be made to my HTML or CSS.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var size = 3;
var board = [];
var team = "X"
var running = true;
buildEmptyBoard();
addClickListenerToEachCell();
// Initialise empty board dynamically based on size
function buildEmptyBoard() {
for (let i = 0; i < size; i++) {
board.push([]);
for (let j = 0; j < size; j++)
board[i].push(" ");
}
}
function addClickListenerToEachCell() {
var matches = document.querySelectorAll("#board .row .elem .clickable");
for (let i = 0; i < matches.length; i++)
matches[i].addEventListener("click", dealWithUserMove);
}
function dealWithUserMove(clickable) {
var id = clickable.target.id;
if (isValidMove(id))
makeMove(id);
else
alert("Invalid move");
simpleAIMove();
}
// A very simple AI that just picks the first possible move that's valid
function simpleAIMove() {
if (running) {
for (let i = 0; i < size; i++) {
for (let j = 0; j < size; j++) {
if (board[i][j] == " ") {
makeMove(convertCoordinatesToID(i, j));
return;
}
}
}
}
}
// Given 2 co-ordinates, convert to a string ID that the html will understand
function convertCoordinatesToID(i, j) {
return "r" + i + "c" + j;
}
function isValidMove(id) {
return board[getRowFromID(id)][getColumnFromID(id)] == " ";
}
function makeMove(id) {
updateViewWithMove(id);
updateBoardWithMove(id);
detectGameOver(id);
switchTeam();
}
// If game has finished, clean up and alert the appropriate message
function detectGameOver(id) {
if (isWinner(id)) {
alert("Team " + team + " has won!");
running = false;
removeClickListenerFromEachCell();
}
else if (isStalemate()) {
alert("Game ended in statemate");
running = false;
removeClickListenerFromEachCell();
}
}
function removeClickListenerFromEachCell() {
var matches = document.querySelectorAll("#board .row .elem .clickable");
for (let i = 0; i < matches.length; i++)
matches[i].removeEventListener("click", dealWithUserMove);
}
function isStalemate() {
for (let i = 0; i < size; i++) {
for (let j = 0; j < size; j++) {
if (board[i][j] == " ")
return false;
}
}
return true;
}
// Return true if move resulted in a win
function isWinner(id) {
return isSidewaysWinner(id) || isDiagonalWinner(id);
}
// Return true if move resulted in a vertical or horizontal win
function isSidewaysWinner(id) {
var column = 0;
var row = 0;
for (let i = 0; i < size; i++) {
if (board[getRowFromID(id)][i] == team)
column++;
if (board[i][getColumnFromID(id)] == team)
row++;
}
return row == size || column == size;
}
function isDiagonalWinner(id) {
posGradient = true;
negGradient = true;
for (let i = 1; i < size; i++) {
if (board[i][i] != board[i - 1][i - 1] || board[i - 1][i - 1] == " ")
posGradient = false;
if (board[size - 1 - i][i] != board[size - i][i - 1] || board[size - i][i - 1] == " ")
negGradient = false;
}
return posGradient || negGradient;
}
function switchTeam() {
if (team == "X")
team = "O"
else
team = "X"
}
function updateBoardWithMove(id) {
board[getRowFromID(id)][getColumnFromID(id)] = team;
}
function updateViewWithMove(id) {
var cell = document.querySelector("#board .row .elem #" + id);
cell.innerHTML = team;
cell.style.color = "black";
}
function getRowFromID(id) {
return parseInt(id.charAt(1));
}
function getColumnFromID(id) {
return parseInt(id.charAt(3));
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#page {
width: 50%;
margin: auto;
font-family: Helvetica-Neue, sans-serif;
}
#board {
text-align: center;
border-collapse: collapse;
border-style: hidden;
pointer-events: none;
table-layout: fixed
}
#board .row {
pointer-events: none;
}
#board .row .elem {
border: 5px solid black;
font-size: 1000%;
pointer-events: none;
}
#board .row .elem .clickable {
pointer-events: all;
color: white;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<title>Tic Tac Toe</title>
<meta charset="utfc8">
</head>
<body>
<div id="page">
<table id="board" height="600" width="600">
<tr class="row">
<td class="elem"><span class="clickable" id="r0c0">X</span></td>
<td class="elem"><span class="clickable" id="r0c1">X</span></td>
<td class="elem"><span class="clickable" id="r0c2">X</span></td>
</tr>
<tr class="row">
<td class="elem"><span class="clickable" id="r1c0">X</span></td>
<td class="elem"><span class="clickable" id="r1c1">X</span></td>
<td class="elem"><span class="clickable" id="r1c2">X</span></td>
</tr>
<tr class="row">
<td class="elem"><span class="clickable" id="r2c0">X</span></td>
<td class="elem"><span class="clickable" id="r2c1">X</span></td>
<td class="elem"><span class="clickable" id="r2c2">X</span></td>
</tr>
</table>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T22:15:36.390",
"Id": "478889",
"Score": "1",
"body": "@greybeard That's the way the snippet editor orders them. The actual markdown parser doesn't appear to care, so you could reorder them if you want to, but I'm not going to submit a functionally cosmetic suggested edit and waste reviewers' time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T03:43:55.540",
"Id": "478932",
"Score": "0",
"body": "(@pppery: as you can see, I left the decision to somebody wiser (or more judgemental). I remember trying to go easy on reviewers' time and appreciate the consideration.)"
}
] |
[
{
"body": "<p>Program looks well structured, so this is gonna be nitpicky</p>\n<pre><code>function isDiagonalWinner(id) {\n posGradient = true;\n</code></pre>\n<p>Since <code>posGradient</code> hasn't been declared anywhere, this will be treated as a global on <code>window['posGradient']</code>. <code>let</code> would suit you nicely here.</p>\n<pre><code>var matches = document.querySelectorAll("#board .row .elem .clickable");\n</code></pre>\n<p>The value of <code>matches</code> never changes. Using <code>const</code> here would indicate this.</p>\n<pre><code>var column = 0;\n</code></pre>\n<p><code>let</code> is a more modern keyword for declaring variables that lives in block scope rather than function scope. For local vaiables in functions, it will likely more often be in line with what you want. Note that it doesn't make a difference here, but can when callbacks are involved.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-13T04:26:50.697",
"Id": "245392",
"ParentId": "243913",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "245392",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T11:37:02.383",
"Id": "243913",
"Score": "8",
"Tags": [
"javascript",
"html",
"css",
"tic-tac-toe"
],
"Title": "A simple tic tac toe game in Javascript/HTML/CSS"
}
|
243913
|
<p>I'm writing some code to take high precision timings of a function call</p>
<blockquote>
<pre><code>for (int i = 0; i < iterations; i++) {
beginTime = high_resolution_clock::now();
CallFunc(functionPtr, otherParamaters ...); // inline function call to do the timed function
endTime = high_resolution_clock::now();
elapsedTime = duration_cast<duration<double>>(endTime - beginTime);
timings.push_back(elapsedTime.count());
}
</code></pre>
</blockquote>
<p>However some of the functions I'm timing run so fast the clock can't pick them up, it ends up just writing a load of <code>0</code>s</p>
<p>I Had the idea to do several repetitions of the function call per timing, to try to get a numerical time I could then divide down past the resolution of the clock, but I don't want to penalize the accuracy of the timing for functions that don't need these repetitions</p>
<p>My solution was to use preprocessor <code>#if</code>s</p>
<blockquote>
<pre><code>for (int i = 0; i < iterations; i++) {
beginTime = high_resolution_clock::now();
#if repetitions > 1
for (int i = 0; i < repetitions; i++) {
#endif
CallFunc(functionPtr, otherParamaters ...); // inline function call to do the timed function
#if repetitions > 1
}
#endif
endTime = high_resolution_clock::now();
elapsedTime = duration_cast<duration<double>>(endTime - beginTime);
timings.push_back(elapsedTime.count());
}
</code></pre>
</blockquote>
<p>My question is, is this kind of optimization silly? Is the compiler likely to do this for me anyway?</p>
<p>EDIT: repetitions is a <code>const int</code></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T12:50:56.633",
"Id": "478811",
"Score": "3",
"body": "Is repititions a compile time constant? If yes, it's probably not necessary. The compiler can unroll the loop itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T15:48:56.903",
"Id": "478831",
"Score": "0",
"body": "Welcome to code review where we review working code from one of your projects and provide suggestions on how to improve your code. As pointed out in the comment by @MikaelH there is some code here that is missing that is necessary, and that prevents us from doing a good review. This makes the question off-topic for code review. I would suggest first searching stackoverflow.com for an answer to your question, if an answer doesn't doesn't exist then ask the question on stackoverflow, but make sure to follow their [guidelines](https://stackoverflow.com/help/asking)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T15:54:01.520",
"Id": "478832",
"Score": "0",
"body": "Suggestion, this is not a compile time decision, I would have an if statement based on a first test of elapsed time, if elapsed time is zero, do it in a loop, if elapsed time is not zero you have enough resolution to do it the other way. When I had a job where CPU processor time mattered we measured performance using loops of basic instructions in operations over a million times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T17:07:34.887",
"Id": "478843",
"Score": "2",
"body": "@Jake: Use https://github.com/google/benchmark . Don't try to write microbenchmarking code on your own; your results won't mean anything."
}
] |
[
{
"body": "<p>Notational suggestion: <em>if</em> insisting on a bracketed controlled statement, favour</p>\n<pre><code>#if 0 < repetitions\n# if 1 < repetitions\n for (int i = 0; i < repetitions; i++)\n# endif\n {\n CallFunc(functionPtr, otherParamaters …); // inline call to timed function\n }\n#endif\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T21:21:39.863",
"Id": "478878",
"Score": "0",
"body": "Why not simply `#if repetitions != 1`? That would make the other `#if` redundant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T03:39:19.990",
"Id": "478931",
"Score": "2",
"body": "@RolandIllig it is about *explicit* (my preference) vs. *implicit*, covered by your suggestion. Using just `repetitions > 1` to control the visibility gets the statement executed once for `repetitions` 0 - makes me icky. That is handled by the original `for` construct pre-processor controlled as per your suggestion - I'd feel pressed to leave a code comment. And think it better to code the blatantly obvious way instead of explaining."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T20:44:45.550",
"Id": "243948",
"ParentId": "243916",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T11:55:57.830",
"Id": "243916",
"Score": "1",
"Tags": [
"c++",
"c-preprocessor"
],
"Title": "c++ is it worth preprocessor optimization for for loops while i < 1"
}
|
243916
|
<p>In my <code>BlogList.vue</code> component I made a search input field:</p>
<pre><code><input type="text" placeholder="Enter key word ..." v-model="search">
</code></pre>
<p>And a computed property:</p>
<pre><code>computed: {
getfilteredData() {
return this.blogs.filter(blog =>
blog.name.toLowerCase().includes(
this.search.toLowerCase()
) ||
blog.category.toLowerCase().includes(
this.search.toLowerCase()
)
)
}
},
</code></pre>
<p>The user can search on multiple values, i.e. <code>blog.name</code> and <code>blog.category</code>, which updates the list accordingly.</p>
<p>Can I write the above JavaScript (computed property) in a cleaner way?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T17:04:21.933",
"Id": "478842",
"Score": "0",
"body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/posts/243920/revisions) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T13:03:00.723",
"Id": "479099",
"Score": "0",
"body": "How many blog posts do you search? Hundreds at most wouldn't be a problem but it shouldn't iterate over thousands and thousands of posts. In this case, you'd need another data type (e.g. database, Trie, ...)"
}
] |
[
{
"body": "<p>It is really hard to say, but at least for me, your code is fine. It seems readable and has no issues. Perhaps if you want to change the style and make it more "canonical", you could write instead:</p>\n<pre class=\"lang-js prettyprint-override\"><code>computed: {\n getfilteredData() {\n return this.blogs.filter(blog =>\n blog.name.toLowerCase().includes(this.search.toLowerCase()) ||\n blog.category.toLowerCase().includes(this.search.toLowerCase())\n )\n }\n },\n</code></pre>\n<p>But for me (and I believe, most readers of this post) your code is just fine.</p>\n<p>Note: for "canonical" I mean fewer lines of code and more compactness. Clearly, it should be done rationally, and you should not write a 200 characters line. The point is write less and allow readability.</p>\n<h3>Edit</h3>\n<p>As <a href=\"https://codereview.stackexchange.com/users/120114/s%E1%B4%80%E1%B4%8D-on%E1%B4%87%E1%B4%8C%E1%B4%80\">Sᴀᴍ Onᴇᴌᴀ</a> answered, it could be substantially optimized if you do:</p>\n<pre class=\"lang-js prettyprint-override\"><code> getfilteredData() {\n const lowerCaseSearch = this.search.toLowerCase();\n return this.blogs.filter(blog =>\n blog.name.toLowerCase().includes(lowerCaseSearch) ||\n blog.category.toLowerCase().includes(lowerCaseSearch)\n )\n }\n</code></pre>\n<p>because you are creating the lowercase string of your search field only once and using it twice instead of creating it twice and use it twice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T16:52:46.887",
"Id": "478841",
"Score": "1",
"body": "thanks totally clear!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T17:51:22.463",
"Id": "479015",
"Score": "2",
"body": "If you write the || in front of the following line it gets even clearer, because you are less likely to overlook it. Also, if you have multiple (read many) lines, you can immediately see, if you screwed up an operator. Much easier at least, than if it was at the end of the line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-22T21:23:52.160",
"Id": "506091",
"Score": "0",
"body": "i would use JavaScripts `some` array method and avoid joining the \"or\" `||` operator"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T15:11:26.137",
"Id": "243923",
"ParentId": "243920",
"Score": "9"
}
},
{
"body": "<p>One improvement would be factoring out the repeated call to <code>this.search.toLowerCase()</code> and storing the result in <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\">a block-scoped constant</a> so it:</p>\n<ol>\n<li>doesn't need to be calculated on every call to <code>.includes()</code> for each iteration of <code>filter()</code></li>\n<li>can decrease the length of each line where that value is used</li>\n</ol>\n<p>That may be a small optimization but it is in line with <a href=\"https://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\">the D.R.Y. principle</a></p>\n<pre><code>getfilteredData() {\n const lowerTerm = this.search.toLowerCase()\n return this.blogs.filter(blog =>\n blog.name.toLowerCase().includes(lowerTerm) ||\n blog.category.toLowerCase().includes(lowerTerm)\n ) \n},\n</code></pre>\n<p>Additionally, it could further be simplified by using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#object_destructuring\" rel=\"nofollow noreferrer\">Object destructuring</a> to eliminate the need for the identifier <code>blog</code> with the callback to the <code>filter</code> method:</p>\n<pre><code>getfilteredData() {\n const lowerTerm = this.search.toLowerCase()\n return this.blogs.filter({name, category} =>\n name.toLowerCase().includes(lowerTerm) ||\n category.toLowerCase().includes(lowerTerm)\n ) \n},\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T17:01:03.607",
"Id": "243931",
"ParentId": "243920",
"Score": "13"
}
},
{
"body": "<p>Another way is to create an array from <code>name</code> and <code>category</code> and combine <code>some</code> method with <code>include</code>:</p>\n<pre><code>const result = blogs.filter(blog =>\n [blog.name, blog.category].some(s => s.toLowerCase().includes(searchRow.toLowerCase()))\n);\n</code></pre>\n<p>It would be very convenient to scale your method by adding into array just necessary property. Let me show an example:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let blogs = [\n { name: \"name 1\", category: \"category 1\"},\n { name: \"name 2\", category: \"category 2\"},\n { name: \"name 3\", category: \"category 3\"},\n];\n\nlet searchRow = \"name 1\";\nlet result = blogs.filter(blog =>\n [blog.name, blog.category].some(s => s.toLowerCase().includes(searchRow.toLowerCase()))\n);\nconsole.log(result);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T17:18:23.093",
"Id": "243932",
"ParentId": "243920",
"Score": "8"
}
},
{
"body": "<p>As already mentioned, the code is ok, but if you want to make it cleaner by removing code duplication, you can introduce local variables and helper functions:</p>\n<pre><code>getfilteredData() {\n const term = this.search.toLowerCase();\n const isMatched = str => str.toLowerCase().includes(term);\n return this.blogs.filter(blog => isMatched(blog.name) || isMatched(blog.category));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T09:21:52.227",
"Id": "243969",
"ParentId": "243920",
"Score": "4"
}
},
{
"body": "<p>It doesn't look like this has been suggested yet but you can use object destructuring so you don't have to repeat <code>blog</code> a couple of times.</p>\n<pre><code>computed: {\n getfilteredData() {\n const term = this.search.toLowerCase()\n \n return this.blogs.filter(({ name, category }) => {\n return name.toLowerCase().includes(term) || category.toLowerCase().includes(term)\n })\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T18:24:15.330",
"Id": "479017",
"Score": "1",
"body": "You're missing two `.toLowerCase()` calls though"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T15:47:28.010",
"Id": "243990",
"ParentId": "243920",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "243923",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T13:42:12.520",
"Id": "243920",
"Score": "12",
"Tags": [
"javascript",
"array",
"functional-programming",
"ecmascript-6",
"vue.js"
],
"Title": "Vue.js search functionality"
}
|
243920
|
<p>I have these 3 methods for ATM mock program.</p>
<pre><code> public decimal CheckBalance(BankAccount account)
{
return account.AccountBalance;
}
public void Deposit(BankAccount account, BankTransaction bankTransaction)
{
account.AccountBalance += bankTransaction.TransactionAmount;
}
public void Withdraw(BankAccount account, BankTransaction bankTransaction)
{
if(bankTransaction.TransactionAmount > account.AccountBalance)
{
throw new Exception("Withdraw failed. Transaction amount is more than account balance.");
}
account.AccountBalance -= bankTransaction.TransactionAmount;
}
</code></pre>
<p>And here are my xUnit unit test methods. The test data is in-memory for this version.</p>
<pre><code> [Theory, MemberData(nameof(CheckBalanceShouldReturnValidBalanceAmount_Data))]
public void CheckBalanceShouldReturnValidBalanceAmount(BankAccount account, decimal accountBalance)
{
// Act
var balance = _atm.CheckBalance(account);
// Assert
Assert.Equal(accountBalance, balance);
}
[Theory, MemberData(nameof(DepositShouldPass_Data))]
public void DepositShouldPass(BankAccount account, BankTransaction bankTransaction, BankAccount accountExpected)
{
// Act
_atm.Deposit(account, bankTransaction);
var balance = _atm.CheckBalance(account);
// Assert
Assert.Equal(accountExpected.AccountBalance, balance);
}
[Theory, MemberData(nameof(WithdrawShouldPass_Data))]
public void WithdrawShouldPass(BankAccount account, BankTransaction bankTransaction, BankAccount accountExpected)
{
// Act
_atm.Withdraw(account, bankTransaction);
var balance = _atm.CheckBalance(account);
// Assert
Assert.Equal(accountExpected.AccountBalance, balance);
}
[Theory, MemberData(nameof(WithdrawAmountMoreThanBalanceShouldFail_Data))]
public void WithdrawAmountMoreThanBalanceShouldFail(BankAccount account, BankTransaction bankTransaction)
{
// Assert and Act
var exception = Assert.Throws<Exception>(() => _atm.Withdraw(account, bankTransaction));
Assert.Equal("Withdraw failed. Transaction amount is more than account balance.",
exception.Message);
}
</code></pre>
<p>All tests passed successfully. Any comments on coding style of unit test?</p>
<p><strong>Edited After Answer with extra class:</strong></p>
<pre><code>namespace XUnitSample.ClassLib.Models
{
public class BankAccount
{
public int Id { get; set; }
public int BankAccountNo { get; set; }
public decimal AccountBalance { get; set; }
}
}
namespace XUnitSample.ClassLib.Models
{
public class BankTransaction
{
public int Id { get; set; }
public decimal TransactionAmount { get; set; }
public TransactionTypeEnum TransactionType { get; set; }
}
public enum TransactionTypeEnum
{
Deposit, Withdraw, ThirdPartyTransfer
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Is your mock ATM class literally named <code>_atm</code>?! Or is it a non-static class that you have assigned to an instance named <code>_atm</code>? Either way, I don't like it and find the <code>_atm</code> class to be useless in your limited example.</p>\n<p>The <code>BankAccount</code> class, which you do not share, should have a <code>Deposit</code> and <code>Withdraw</code> method, both accepting a <code>BankTransaction</code> as a input argument. You should include validation of a particular transaction within each method, i.e. do not accept a deposit of negative amount. You also do not share <code>BankTransaction</code> with us.</p>\n<p><code>CheckBalance</code> is not needed, as you would just as easily show the <code>BankAccount.AccountBalance</code> property. Also the property name could be shortened to <code>Balance</code> since it is the balance of the bank account.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T23:08:22.457",
"Id": "478899",
"Score": "0",
"body": "My ATM class is named as `AtmApp`. Yeah, it is a non-static class and I instantiate it in my constructor at this `AtmAppTest` class and name the instance as `_atm`. I have added `BankAccount` and `BankTransaction` class at my original post. But these class is anemic. Oh this means `Deposit` and `Withraw` method should moved to `BankAccount`. Okay, thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T16:38:52.090",
"Id": "243930",
"ParentId": "243921",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243930",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T14:40:29.837",
"Id": "243921",
"Score": "2",
"Tags": [
"c#",
"xunit"
],
"Title": "Atm program xUnit unit test"
}
|
243921
|
<p>I have a simple macro moving data from Teradata to Excel. The process normally takes me 10 minutes to perform manually, however the macro can run for hours sometimes. This is making the macro seems counterproductive. But I still want to give it a chance.</p>
<p>Manually, I would just simply paste the sql to teradata, and copy/paste the results to Excel. This takes about 10 mins including the teradata run time.</p>
<p>Can someone suggest any ways to improve the performance? I'm still quite new to macros, so using simple language would be very much appreciated.</p>
<pre><code>Option Explicit
Global glbUN As String
Global glbPWD As String
Global cnEDW As ADODB.Connection
Sub RefreshData()
Call Open_EDWDatabase
DoEvents
Call BuildCode
DoEvents
End Sub
Public Sub Open_EDWDatabase()
Set cnEDW = New ADODB.Connection
If glbUN = "" Or glbPWD = "" Then
'Open login screen and center the form for people with 2 monitors
UserForm1.StartUpPosition = 0
UserForm1.Left = Application.Left + (0.5 * Application.Width) - (0.5 * UserForm1.Width)
UserForm1.Top = Application.Top + (0.5 * Application.Height) - (0.5 * UserForm1.Height)
UserForm1.Show 1
End If
cnEDW.ConnectionString = "Driver={Teradata};Persist Security Info=False;User ID=" & glbUN & ";Pwd=" & glbPWD & ";Data Source=teradata_PRD"
cnEDW.Open
End Sub
Public Sub Close_EDWDatabase()
cnEDW.Close
Set cnEDW = Nothing
End Sub
Sub BuildCode()
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim LastLineofSQL As Long
Dim LastLineofSQL2 As Long
Dim strQry As String
Dim strQry2 As String
Dim x, y As Long
Dim OutputAddress As String
Dim iCol As Long
LastLineofSQL = 44
strQry = ""
Set cmd = New ADODB.Command
cmd.ActiveConnection = cnEDW
cmd.CommandTimeout = 20000000
For x = 1 To LastLineofSQL
strQry = strQry + Sheets("Codes").Cells(x, 1).Value
If InStr(strQry, ";") <> 0 Then
cmd.CommandText = strQry
Set rs = cmd.Execute
If x = LastLineofSQL Then
Sheets("Data").Range("B2").CopyFromRecordset rs
End If
strQry = ""
DoEvents
Else
If Right$(strQry, 2) <> vbCrLf Then
strQry = strQry + vbCrLf
End If
End If
Next x
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T15:35:45.523",
"Id": "478826",
"Score": "1",
"body": "Does this answer your question? [Looking for more efficient VBA to Move data from Teradata to Excel](https://codereview.stackexchange.com/questions/243493/looking-for-more-efficient-vba-to-move-data-from-teradata-to-excel)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T15:40:42.010",
"Id": "478827",
"Score": "1",
"body": "Feel free to edit the original post to bump it back onto the front page, but please do not post duplicates."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T15:11:04.683",
"Id": "243922",
"Score": "1",
"Tags": [
"performance",
"vba"
],
"Title": "Run Teradata using Excel VBA"
}
|
243922
|
<p>I would like to arrange a system messages dictionary for an application in JavaScript.</p>
<p>As an initial intention, I thought something about the following structure:</p>
<pre class="lang-js prettyprint-override"><code>export const SYS_MESSAGES = Object.freeze({
fileSizeExceeded: {
code: "FILE_SIZE_EXCEEDED",
text: "The file size exceeds allowed limit"
}
});
</code></pre>
<p>But then I realized, the structure could be even more simple:</p>
<pre class="lang-js prettyprint-override"><code>export const SYS_MESSAGES = Object.freeze({
FILE_SIZE_EXCEEDED: "The file size exceeds allowed limit"
});
</code></pre>
<p>Which option of two structures is a preferred-one from maintenance/style perspective?</p>
|
[] |
[
{
"body": "<p>I consider that the second option is better for the following:</p>\n<ul>\n<li>The first option is more verbose than the second, and it is in a way that there is no additional information which allow other developers or even you to obtain meaningful information.</li>\n<li>The second option has a constant style name which represents what you are trying to tell us, "hey, this is a constant and its value is ..." and so, it clearly reflects a shorter and descriptive code style.</li>\n<li>Having less properties (in your objects) implies less space, and less space computed implies less execution time. (even if it is very small).</li>\n<li>Less content helps you to debug faster.</li>\n</ul>\n<p>Well, I hope it helped you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T19:16:15.870",
"Id": "478857",
"Score": "0",
"body": "Thanks for the opinion, I also considered the second option, but then I realized that with a such structure it will be more difficult to get a code of a message. E.g. `SYS_MESSAGES.FILE_SIZE_EXCEEDED` returns always a text message (\"The file size exceeds allowed limit\"), but if I want to get the message code itself (`FILE_SIZE_EXCEEDED`), then I'll have to play with `Object.keys()` and rely on a permanent order of messages in the dictionary, which can be changed at any time day and will require adjusting the entire code base. That's why the option #1 is better, although it's more verbose."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T18:18:50.080",
"Id": "243936",
"ParentId": "243928",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T16:24:20.947",
"Id": "243928",
"Score": "1",
"Tags": [
"hash-map"
],
"Title": "A structure for a text messages dictionary with system notifications/errors"
}
|
243928
|
<p>I have started to use C# 7's type based <a href="https://docs.microsoft.com/en-us/dotnet/csharp/pattern-matching" rel="nofollow noreferrer">pattern matching</a>. A method that only manages a single pattern-based result looks very clean and is easy to reason about.</p>
<p>However, once a second pattern-based result that depends on the first pattern-based result creates an arrow anti-pattern, and will only get worse with n-results that depend on each other.</p>
<p>Here is an simplified example that demonstrates the arrow pattern:</p>
<pre><code>public Result<bool> ValidateSomething(string strId)
{
var id = Guid.Parse(strId);
Result<Something> fetchSomethingResult = new SomethingDao.FetchSomething(id);
switch (fetchSomethingResult)
{
case ValueResult<Something> successfulSomethingResult:
Result<Related> fetchRelatedFieldsResult = new RelatedDao.FetchRelatedFields(successfulSomethingResult.Value.RelatedId);
switch (fetchRelatedFieldsResult)
{
case ValueResult<Related> successfulFieldValueResult:
var isValid = successfulSomethingResult.Value.ComparableVal <= successfulFieldValueResult.Value.RelatedComparableVal;
return new ValueResult<bool>(isValid);
case ValueNotFoundResult<Related> _:
return new ValueNotFoundResult<bool>();
case ErrorResult<Related> errorResult:
return new ErrorResult<bool>(errorResult.ResultException);
default:
throw new NotImplementedException("Unexpected Result Type Received.");
}
case ValueNotFoundResult<Something> notFoundResult:
return new ValueNotFoundResult<bool>();
case ErrorResult<Something> errorResult:
return new ErrorResult<bool>(errorResult.ResultException);
default:
throw new NotImplementedException("Unexpected Result Type Received.");
}
}
</code></pre>
<p>For reference, these are the definitions for the <code>Result</code> classes:</p>
<pre><code>public abstract class Result<T>
{
}
public class ValueResult<T> : Result<T>
{
public ValueResult()
{
}
public ValueResult(T inValue)
{
Value = inValue;
}
public T Value { get; set; }
}
public class ValueNotFoundResult<T> : Result<T>
{
public ValueNotFoundResult()
{
}
}
public class ErrorResult<T> : Result<T>
{
public Exception ResultException { get; set; }
public ErrorResult()
{
}
public ErrorResult(Exception resultException)
{
ResultException = resultException;
}
}
</code></pre>
<p>What options are there to handle this type of code better? What suggestions do you have for the previous examples? How do I avoid the arrow anti-pattern with pattern-based results?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T18:24:16.480",
"Id": "478851",
"Score": "2",
"body": "Welcome to Code Review! Unfortunately this question does not match what this site is about. Please re-read the Help center page [_What topics can I ask about here?_](https://codereview.stackexchange.com/help/on-topic) - specifically the third question. Reviewers need more than hypothetical/stub code. For more information, see [this meta post](https://codereview.meta.stackexchange.com/a/3652/120114)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T17:55:31.353",
"Id": "243934",
"Score": "1",
"Tags": [
"c#",
"object-oriented",
".net-core"
],
"Title": "Avoiding Arrow Pattern with C# Pattern Matching"
}
|
243934
|
<p>I have an array of the form (3x3 case as an example)</p>
<p><span class="math-container">$$A = [a_{11}, a_{12}, a_{22}, a_{13}, a_{23}, a_{33}] $$</span></p>
<p>corresponding to the symmetric matrix</p>
<p><span class="math-container">$$\begin{pmatrix} a_{11} & a_{12} & a_{13}\\ a_{12} & a_{22} & a_{23} \\ a_{13} & a_{23} & a_{33} \end{pmatrix}$$</span></p>
<p>I want to print out this very matrix (in general of size NxN) given the array A (in general of length N*(N+1)/2) in a nice way.
My approach was</p>
<pre><code>void print__symm_matrix_packed(double* arr, int N){
int idx2 = 0;
for(int i=0; i<N; i++){
printf("(");
int idx1 = i;
for(int j=0; j<N; j++){
if(j < i){
printf("%f ", arr[idx2 + j]);
} else {
printf("%f ", arr[idx1]);
}
idx1 += j+1;
}
idx2 += i+1;
printf(")\n");
}
}
</code></pre>
<p>Is there room for some elegant improvement?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T18:54:58.287",
"Id": "478854",
"Score": "0",
"body": "I think you mean $$ A = [a_{11}, a_{12}, a_{13}, a_{21}, a_{22}, a_{23}, a_{31}, a_{32}, a_{33}] $$, Am I correct ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T19:33:16.307",
"Id": "478863",
"Score": "0",
"body": "@MiguelAvila No, it is stored column wise back to back"
}
] |
[
{
"body": "<p>I think it the following is a good approach:</p>\n<pre><code>//use lowercase on non constant values\nvoid print_symmetric_packed_matrix(double* compact_matrix, int n)\n{\n const int entries = N*N;\n for (int i = 0; i < entries;)\n {\n //i++ here avoids i != 0 each iteration\n printf("%f ", compact_matrix[i++]);\n if (i % N == 0) printf("\\n");\n }\n}\n</code></pre>\n<p>I hope it helped you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T19:45:39.407",
"Id": "478866",
"Score": "0",
"body": "Thank you, but this does not display the matrix that I mentioned in my question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T19:06:55.520",
"Id": "243938",
"ParentId": "243937",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T18:26:57.303",
"Id": "243937",
"Score": "3",
"Tags": [
"c",
"matrix"
],
"Title": "Print out symmetric matrix from compactly stored array"
}
|
243937
|
<p>I 'm new here. I wrote the following django code. I 'm opening, closing files here and saving them temporarily and deleting them. I tried to use Python's tempfile and was getting Permission Error and I did asked about it on IRC #django but maybe Windows is not a pleasant to use OS for programmers so I couldn't get a good answer. I needed something like render_to_string of django which takes in a html string and replace all templating with the context dict but it seems django is made to treat every .html file as a template.</p>
<p>Purpose of the project
:
It is to take a visitor's id and return him with a pdf which will be formed by picking up a row from the database by looking at his id. There are 3 kinds of ids here.</p>
<p>How is the pdf being made?</p>
<p>I was given a pdf empty form which I converted to .docx file with the use of online sites. Now I tried to use python-docx to convert docx to pdf but that required libre office/ms word which might not be available on the server (The form can be formed by the client on his local pc and be given to the technical guy to put on the server).</p>
<p>I was suggested to use a html form and the client said that he might change the form.</p>
<p>@ChrisWarrick on #python IRCnode suggested me to use HTML to PDF conversion which could be done by weasyPrint which was cross platform and easier to install. Although he said me to use jinja but since I was using django why install some other library. Now I said to the client to open a .docx file and create whatever form he has to make and put {{NAME}} and other variables wherever he wants some information from the database to be put and save it as .html file and further put it in the /media folder of the django project. Then he has to open the config (.cfg) file and put</p>
<p>NAME=NAME
here 'NAME' on left is what is in the .html file(docx form) and on the right is column name of the database table(I got a single table).</p>
<p>Please help me make this code make more maintainable and remove that unnecessary saving file and deleting it. Also there's a problem that on windows when I save the docx file as .html I get the encoding as cp1252 whereas the server has linux as told to me. I have been told on IRCnode #powershell that windows can have a bunch of too many encodings. To do this I will say to the client to convert .html to utf8 using <code>Get-Content word.htm | out-file -encoding utf8 word-1.htm </code></p>
<p>App name base</p>
<p>base/view.py</p>
<pre><code>from django.shortcuts import render
from .forms import InputData
from . import backend
from django.http import FileResponse, HttpResponse
import configparser
config = configparser.RawConfigParser()
config.read('vars.cfg')
# Create your views here.
def index(request):
if request.method == "POST":
form = InputData(request.POST)
if form.is_valid():
check, data = backend.main(**form.cleaned_data)
if check:
return FileResponse(
data,
as_attachment=True,
filename=config['DOWNLOAD']['DOWNLOAD_FILE_AS'])
else:
return HttpResponse(data)
form = InputData()
return render(request, "base/index.html", {
'forms': form
})
</code></pre>
<p>base/backend.py</p>
<pre><code>import os
import pandas as pd
import codecs
from weasyprint import HTML
import configparser
import tempfile
from django import template
from django.template.loader import render_to_string
from pathlib import Path
if os.path.exists('temp.pdf'):
os.remove('temp.pdf')
def getConfigObject():
config = configparser.RawConfigParser()
config.optionxform = str
config.read('vars.cfg')
return config
config = getConfigObject()
def load_custom_tags():
html = codecs.open(
config["FILES"]["HTML_FILE_NAME"],
encoding='utf-8').read()
html = "{% load numbersinwords %}" if not html.startswith(
"{% load"
) else "" + html
Html_file = open(config["FILES"]["HTML_FILE_NAME"], "w", encoding="utf-8")
Html_file.write(html)
Html_file.close()
def html2pdf(row):
row = row.to_dict()
load_custom_tags()
html = render_to_string(Path(config["FILES"]["HTML_FILE_NAME"]).name,
{key: row[value]
for key, value in config._sections["TAGS"].items()})
return html
def get_data():
return pd.read_csv(config["FILES"]["EXCEL_FILE_NAME"],
dtype=str, keep_default_na=False)
def search_row(opt, value):
user_data = get_data()
return user_data[user_data[opt] == value]
def main(opt, value):
row = search_row(opt, value)
if len(row) == 1:
row = row.squeeze()
else:
return (False, f"<h1>Invalid credential :"
" Multiple candidates exists"
"with given credential</h1>")
if not(row.empty):
html = html2pdf(row)
HTML(string=html).write_pdf("temp.pdf")
# Code from
# https://stackoverflow.com/questions/47833221/emailing-a-django-pdf-file-without-saving-in-a-filefield
# temp = tempfile.NamedTemporaryFile()
# temp.write(pdf_file)
# temp.seek(0)
########
f = open("temp.pdf", "rb")
return (True, f)
return (False, f"<h1>Invalid credential {opt}: {value}</h1>")
</code></pre>
<p>base/templatetags/numbersinwords.py</p>
<pre><code>from django import template
from num2words import num2words
register = template.Library()
@register.filter()
def to_words(value):
return num2words(int(value), lang="en_IN").upper()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T16:50:40.420",
"Id": "479677",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Do not add extra questions once it has been answered. Besides, your edit contained code that wasn't working yet, which is out-of-scope for Code Review. Thank you."
}
] |
[
{
"body": "<h2>Else-after-return</h2>\n<p>Some people consider this a stylistic choice, but this:</p>\n<pre><code> if check:\n return FileResponse(\n data, \n as_attachment=True,\n filename=config['DOWNLOAD']['DOWNLOAD_FILE_AS'])\n else:\n return HttpResponse(data)\n</code></pre>\n<p>can be</p>\n<pre><code> if check:\n return FileResponse(\n data, \n as_attachment=True,\n filename=config['DOWNLOAD']['DOWNLOAD_FILE_AS'])\n return HttpResponse(data)\n</code></pre>\n<h2>Import-time file manipulation</h2>\n<p>This:</p>\n<pre><code>if os.path.exists('temp.pdf'):\n os.remove('temp.pdf')\n</code></pre>\n<p>is done at global scope on file interpretation, which is risky for a few reasons - including that it will make isolated unit testing much more difficult. This kind of thing should be pulled into a function that runs on program initialization, not at global scope.</p>\n<p>Beyond that, having one temporary file with a fixed name invites a collection of security vulnerabilities and failures of re-entrance. This file should be randomly named; the <code>tempfile</code> module can do this for you.</p>\n<h2>snake_case</h2>\n<p><code>getConfigObject</code> should be <code>get_config_object</code>, like your other functions already are.</p>\n<p><code>Html_file</code> should not be capitalized since it's a local variable. Also, it should be used in a <code>with</code> statement without an explicit call to <code>close</code>.</p>\n<h2>Ternary abuse</h2>\n<pre><code>html = "{% load numbersinwords %}" if not html.startswith(\n "{% load"\n) else "" + html\n</code></pre>\n<p>should simply be</p>\n<pre><code>if not html.startswith("{% load"):\n html = "{% load numbersinwords %}" + html\n</code></pre>\n<h2>Implicit return tuples</h2>\n<pre><code> return (True, f)\n</code></pre>\n<p>does not need parens.</p>\n<h2>Avoiding temp files</h2>\n<p>Read the documentation:</p>\n<p><a href=\"https://weasyprint.readthedocs.io/en/stable/api.html#weasyprint.HTML.write_pdf\" rel=\"nofollow noreferrer\">https://weasyprint.readthedocs.io/en/stable/api.html#weasyprint.HTML.write_pdf</a></p>\n<blockquote>\n<p>target (<code>str</code>, <code>pathlib.Path</code> or file object) – A filename where the PDF file is generated, a file object, or <code>None</code>.</p>\n</blockquote>\n<p>In this case it's easy to avoid a temp file by passing a file object. That file object can be a Django HTTP response stream; for more reading see</p>\n<p><a href=\"https://docs.djangoproject.com/en/3.0/ref/request-response/#passing-strings\" rel=\"nofollow noreferrer\">https://docs.djangoproject.com/en/3.0/ref/request-response/#passing-strings</a></p>\n<p>Currently you do</p>\n<pre><code> HTML(string=html).write_pdf("temp.pdf")\n f = open("temp.pdf", "rb")\n return (True, f)\n # ...\n\n check, data = backend.main(**form.cleaned_data)\n if check:\n return FileResponse(\n data, \n as_attachment=True,\n filename=config['DOWNLOAD']['DOWNLOAD_FILE_AS'])\n else:\n return HttpResponse(data)\n</code></pre>\n<p>This needs to be refactored so that</p>\n<ul>\n<li>the Response object is passed to <code>write_pdf</code> instead of a filename</li>\n<li>you no longer return an open file handle</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T09:48:36.113",
"Id": "479628",
"Score": "0",
"body": "Thanks for the answer @Reinderien. Can you provide some more tips on when to use ternary operators since that you called as ternary abuse. Also isn't camelcase also a way to write in python just like the snake case or \"_\" separated names?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T10:04:38.930",
"Id": "479630",
"Score": "0",
"body": "Another thing is you have advised to use a `with` statement(under `snake_case` section) but not at the end when I 'm returning from main function where I have neither closed the file or used any with. I was using the with context manager in my code initially but the file was getting closed before sending the `f' or the pdf object and I was getting a binary string printed on the DOM. That's why I was hesitant to use with statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T10:08:45.133",
"Id": "479631",
"Score": "0",
"body": "I have upvoted your answer but 'm interested in some answer which can directly help me send the pdf object without saving it to any tempfile or creating/deleting any temporary file since I couldn't find it myself by my efforts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T14:04:01.510",
"Id": "479649",
"Score": "0",
"body": "_Can you provide some more tips on when to use ternary operators_ - sparingly, and only when the expression is relatively simple. Also, the fact that one of the ternary outputs is effectively a no-op means it's better captured by an `if` anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T14:05:35.800",
"Id": "479651",
"Score": "0",
"body": "_isn't camelcase also a way to write in python just like the snake case or underscore-separated names_ - Not according to the PEP8 standard - https://www.python.org/dev/peps/pep-0008/#function-and-variable-names"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T14:07:30.030",
"Id": "479652",
"Score": "0",
"body": "_the file was getting closed before sending the `f`_ - Your current usage of `Html_file` opens and closes the file within three lines. That's a clear case for a `with`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T14:15:18.677",
"Id": "479653",
"Score": "0",
"body": "_help me send the pdf object without saving it to any tempfile_ - sure; edited the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T15:35:00.587",
"Id": "479667",
"Score": "0",
"body": "Thanks a lot, thanks for providing me with the good coding guidelines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T16:40:02.407",
"Id": "479674",
"Score": "0",
"body": "Hi, I 'm still not sure on how to connect the \"target\" in write_pdf and django's StreamingResponse. I don't understand how exactly it works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T16:41:26.593",
"Id": "479675",
"Score": "0",
"body": "Can you help me with the edit please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T16:56:24.747",
"Id": "479679",
"Score": "0",
"body": "Edited. If you still cannot make the streamed approach work, then a specific question about the problem you are having would be appropriate for Stack Overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T17:00:19.787",
"Id": "479681",
"Score": "0",
"body": "thanks for the advice. I didn't know how the flow goes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T17:19:41.397",
"Id": "479684",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/109697/discussion-between-vishesh-mangla-and-reinderien)."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T00:00:02.717",
"Id": "244294",
"ParentId": "243939",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244294",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T19:33:24.923",
"Id": "243939",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"pandas",
"django"
],
"Title": "Use django engine to fill in a .html file on storage (no template) and use weasyPrint to convert it to PDF"
}
|
243939
|
<p>I am (relatively) new to game programming and have been exploring creating an entity component system for my simple 2D game engine.</p>
<p>Here is what I have so far:</p>
<p><strong>Entity.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
using Entity = int;
</code></pre>
<p><strong>ComponentArray.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include "Entity.h"
#include <unordered_map>
class ComponentArrayAbstract {};
template<typename T>
class ComponentArray : public ComponentArrayAbstract {
public:
void AddComponent(Entity entity, T component);
void RemoveComponent(Entity enitity);
T& GetComponent(Entity entity);
private:
std::unordered_map<Entity, T> mComponents;
};
template<typename T>
void ComponentArray<T>::AddComponent(Entity entity, T component) {
mComponents.emplace(entity, component);
}
template<typename T>
void ComponentArray<T>::RemoveComponent(Entity entity) {
mComponents.erase(entity);
}
template<typename T>
T& ComponentArray<T>::GetComponent(Entity enitity) {
return mComponents[enitity];
}
</code></pre>
<p><strong>ECSManager.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include "Entity.h"
#include "ComponentArray.h"
#include <bitset>
#include <array>
#include <vector>
#include <functional>
const int MAX_COMPONENT_TYPES = 32;
using ComponentType = int;
using ComponentSignature = std::bitset<MAX_COMPONENT_TYPES>;
class ECSManager;
using System = std::function<void(ECSManager*, double)>;
class ECSManager {
public:
ECSManager() = default;
~ECSManager();
ECSManager(const ECSManager& other) = delete;
ECSManager(ECSManager&& other) = delete;
ECSManager& operator=(const ECSManager& other) = delete;
ECSManager& operator=(ECSManager&& other) = delete;
// Entity Functions
Entity CreateEntity(int id); // TODO: use hashed string ids instead.
void DestroyEntity(Entity entity);
template<typename... Args>
std::vector<Entity> GetEntitiesWith();
template<typename T>
T& GetComponent(Entity entity) const;
// Component Functions
template<typename T>
void RegisterComponentType();
template<typename T>
void AddComponent(Entity entity, T component);
template<typename T>
void RemoveComponent(Entity entity);
// System Functions
void AddSystem(System system);
void UpdateSystems(double deltaTime);
private:
ComponentSignature GetComponentSignature(Entity entity) const;
void SetComponentSignature(Entity entity, ComponentSignature signature);
template<typename T>
ComponentArray<T>* GetComponentArray() const;
template<typename T>
ComponentType GetComponentType() const;
int* GetComponentCount() const;
template<typename T>
ComponentSignature CreateComponentSignature() const;
template<typename T, typename Second, typename... Args>
ComponentSignature CreateComponentSignature() const;
std::unordered_map<Entity, ComponentSignature> mComponentSignatures;
std::array<ComponentArrayAbstract*, MAX_COMPONENT_TYPES> mComponentArrays;
std::vector<System> mSystems;
};
template<typename... Args>
std::vector<Entity> ECSManager::GetEntitiesWith() {
ComponentSignature systemSignature = CreateComponentSignature<Args...>();
std::vector<Entity> entities;
for (auto i : mComponentSignatures) {
if ((i.second & systemSignature) == i.second) entities.push_back(i.first);
}
return entities;
}
template<typename T>
T& ECSManager::GetComponent(Entity entity) const {
return GetComponentArray<T>()->GetComponent(entity);
}
template<typename T>
void ECSManager::RegisterComponentType() {
mComponentArrays[GetComponentType<T>()] = new ComponentArray<T>();
}
template<typename T>
void ECSManager::AddComponent(Entity entity, T component) {
GetComponentArray<T>()->AddComponent(entity, component);
SetComponentSignature(entity, GetComponentSignature(entity).set(GetComponentType<T>(), true));
}
template<typename T>
void ECSManager::RemoveComponent(Entity entity) {
GetComponentArray<T>()->RemoveComponent(entity);
SetComponentSignature(entity, GetComponentSignature(entity).set(GetComponentType<T>(), false));
}
template<typename T>
ComponentArray<T>* ECSManager::GetComponentArray() const {
return ((ComponentArray<T>*) (mComponentArrays[GetComponentType<T>()]));
}
template<typename T>
ComponentType ECSManager::GetComponentType() const {
static int index = (*GetComponentCount())++; return index;
}
template<typename T>
ComponentSignature ECSManager::CreateComponentSignature() const {
ComponentSignature signature;
signature.set(GetComponentType<T>(), true);
return signature;
}
template<typename T, typename Second, typename... Args>
ComponentSignature ECSManager::CreateComponentSignature() const {
ComponentSignature signature;
signature.set(GetComponentType<T>(), true);
signature |= CreateComponentSignature<Second, Args...>();
return signature;
}
</code></pre>
<p><strong>ECSManager.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include "ECSManager.h"
#include "ComponentArray.h"
#include <unordered_map>
#include <array>
#include <vector>
#include <functional>
ECSManager::~ECSManager() {
for (ComponentArrayAbstract* componentArray : mComponentArrays) {
if (componentArray != nullptr) {
delete componentArray;
}
}
}
Entity ECSManager::CreateEntity(int id) {
mComponentSignatures.emplace(id, ComponentSignature());
return id;
}
void ECSManager::DestroyEntity(Entity entity) {
mComponentSignatures.erase(entity);
}
ComponentSignature ECSManager::GetComponentSignature(Entity entity) const {
return mComponentSignatures.at(entity);
}
void ECSManager::SetComponentSignature(Entity entity, ComponentSignature signature) {
mComponentSignatures[entity] = signature;
}
void ECSManager::AddSystem(System system) {
mSystems.push_back(system);
}
void ECSManager::UpdateSystems(double deltaTime) {
for (System system : mSystems) {
system(this, deltaTime);
}
}
int* ECSManager::GetComponentCount() const {
static int componentCount = 0;
return &componentCount;
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include "ECSManager.h"
#include <stdio.h>
struct Component1 {
int num1;
};
struct Component2 {
int num2;
};
void TestSystem(ECSManager* world, double deltaTime) {
for (Entity entity : world->GetEntitiesWith< Component1, Component2>()) {
Component1 component1 = world->GetComponent<Component1>(entity);
Component2 component2 = world->GetComponent<Component2>(entity);
printf("%i\n", component1.num1 + component2.num2);
}
}
int main() {
ECSManager world;
world.RegisterComponentType<Component1>();
world.RegisterComponentType<Component2>();
Entity entity1 = world.CreateEntity(1);
world.AddComponent<Component1>(entity1, {1}); // I will use hashed string ids in the future.
world.AddComponent<Component2>(entity1, {2});
Entity entity2 = world.CreateEntity(2);
world.AddComponent<Component1>(entity2, {3});
world.AddComponent<Component2>(entity2, {4});
world.AddSystem(TestSystem);
world.UpdateSystems(0.16);
return 0;
}
</code></pre>
<p>I have a few questions:</p>
<ul>
<li><p>Implementation:</p>
<p>Is the implementation flawed in any way, eg. are my uses of std containers appropriate? Is it relatively cache friendly? (I'm looking at the unordered map of entities). I initially wanted to make <code>ECSManager</code> a namespace with functions, like my other subsystems (<code>Renderer</code>, <code>Input</code>, etc. I don't know if this is a good idea either!). Is this feasible, or a good way to do it? I decided not to, since there are lots of template functions, so accessing data would be a pain.</p>
</li>
<li><p>Style:</p>
<p>Are there any issues with the way I have written my code? Should I implement the <code>ECSManager</code> functions in a cpp file, since most are template functions anyway?</p>
</li>
<li><p>API:</p>
<p>Is the API realistic and scalable? Is it holding me back in any way?</p>
</li>
<li><p>Have I made any silly mistakes?</p>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T21:59:28.710",
"Id": "478882",
"Score": "1",
"body": "`ComponentArray` is basically useless as it is just a worse `std::unordered_map`. Also introducing type-erared classes for templates without reason makes no sense either (Im talking about `ComponentArrayAbstract."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T22:00:35.617",
"Id": "478883",
"Score": "1",
"body": "if you want to have a \"default\" container for your code base, e.g to be able to quickly switch implementations consider using `using` instead. Also any container class should be able to accept arbitrary allocators (have a look at how std containers are designed)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T22:05:06.163",
"Id": "478884",
"Score": "1",
"body": "Oh and you might want to check out boost hana for heterogenous containers (containers which can store objects of more than one type). Especially `hana::map` which can be used to map types to arbitrary objects"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T09:05:12.407",
"Id": "478952",
"Score": "3",
"body": "Your ECSManager manager needs to implement the rule of five. As it is now horrible things will happen if you copy an instance of it and move semantics are disabled."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T19:36:28.397",
"Id": "243940",
"Score": "6",
"Tags": [
"c++",
"c++17",
"entity-component-system"
],
"Title": "C++17 ECS Implementation"
}
|
243940
|
<p>I had an assignment last semester to program a payroll app utilizing methods. I went back to it and re-wrote it to include an extra class as well. I would like some feedback regarding whether my code is following the Single Responsibility SOLID principle - should the class be split further into more classes?</p>
<p>I would also like some tips on how I could format the output nicer using printf as depending on how long the names or pay are, the columns get misaligned.</p>
<p>Here is the code:</p>
<pre><code>//Java payroll program utilizing methods and classes
import java.util.Scanner;
public class Payroll
{
public static void main(String[]args)
{
//declaration block
Payroll app = new Payroll();
int SIZE;
double overtimeEarnings = 0.0;
double averageGross = 0.0;
double totalGross = 0.0;
//taxes and fees constants
final double fTax = 0.12;
final double sTax = 0.06;
final double uFees = 0.01;
double sentinel = 0.0;
Scanner kb = new Scanner(System.in);
System.out.println("Welcome to the Payroll Calculator\n");
do {
System.out.println("How many employees?: ");
SIZE = kb.nextInt();
Employees dataHousing = new Employees(SIZE);
dataHousing.input();
dataHousing.calculateGross();
dataHousing.calculateNet(sTax, fTax, uFees);
totalGross = app.calculateTotalGross(dataHousing.grossPay, SIZE);
averageGross = app.calculateAverageGross(totalGross, SIZE);
app.output(dataHousing, totalGross, averageGross, SIZE);
//clear after output in case user wants to repeat program
totalGross = 0.0;
averageGross = 0.0;
System.out.println("\nPlease enter 1 to repeat the program, any other number to quit");
sentinel = app.input();
}
while(sentinel == 1);
System.out.println("Goodbye!");
}
double input()
{
Scanner kb = new Scanner(System.in);
double value;
value = Double.parseDouble(kb.nextLine());
return value;
}
double calculateTotalGross( double gIncome[], final int SIZE)
{
double totalGross = 0.0;
for(int i = 0; i < SIZE; i++)
{
totalGross += gIncome[i];
}
return totalGross;
}
double calculateAverageGross(double tGross, final int SIZE)
{
return tGross/SIZE;
}
void output(Employees x,double tGross, double aGross, final int SIZE)
{
System.out.printf("%70s%n", "Data Housing Corp. Payroll");
System.out.printf("%110s%n","__________________________________________________________________________________________________________________");
System.out.printf("%10s %10s %10s %10s %10s %10s %10s %10s %10s %10s%n", "First Name |" , "M Initial |" , "Surname |" , "Rate/h |" , "OT Hours |" ,
"Gross $ |" , "State Tax |" , "Fed Tax |" , "Union fees |" , "Net $ |");
for (int i = 0; i < SIZE; i++)
{
System.out.printf("%5s %8s %15s %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f%n%n",x.firstName[i] , x.MI[i] , x.lastName[i] ,
x.payRate[i] , x.overtimeHours[i] , x.grossPay[i], x.stateTax[i] , + x.fedTax[i] , x.unionFees[i] , x.netPay[i]);
}
System.out.printf("Total Gross is: %.2f%n" , tGross);
System.out.printf("Average Gross is: %.2f%n" , aGross);
}
}
class Employees
{
String[] firstName;
String[] lastName;
char[] MI;
double[] hours;
double[] overtimeHours;
double[] payRate;
double[] grossPay;
double[] netPay;
double[] stateTax;
double[] fedTax;
double[] unionFees;
final int SIZE;
Employees(int SIZE)
{
this.SIZE = SIZE;
this.firstName = new String[SIZE];
this.lastName = new String[SIZE];
this.MI = new char[SIZE];
this.hours = new double[SIZE];
this.payRate = new double[SIZE];
this.grossPay = new double[SIZE];
this.overtimeHours = new double[SIZE];
this.netPay = new double[SIZE];
this.stateTax = new double[SIZE];
this.fedTax = new double[SIZE];
this.unionFees = new double[SIZE];
}
void input()
{
for(int i = 0; i < SIZE; i++)
{
System.out.println("Please enter the First Name: ");
firstName[i] = keyboard();
System.out.println("Please enter the Middle Initial: ");
MI[i] = keyboard().charAt(0);
System.out.println("Please enter the Last Name: ");
lastName[i] = keyboard();
System.out.println("Please enter the hours worked: ");
hours[i] = Double.parseDouble(keyboard());
System.out.println("Please enter the hourly pay rate: ");
payRate[i] = Double.parseDouble(keyboard());
}
}
String keyboard()
{
Scanner kb = new Scanner(System.in);
String value;
value = kb.nextLine();
return value;
}
/**
* gross method calculates the gross income of each employee and stores the value in grossPay member
*
*
*/
void calculateGross()
{
double overtimeEarnings;
for(int i = 0; i < SIZE; i++)
{
if(hours[i] > 40)
{
overtimeHours[i] = hours[i] - 40;
overtimeEarnings = overtimeHours[i] * (payRate[i] * 1.5);
grossPay[i] = ((hours[i] - overtimeHours[i]) * payRate[i]) + overtimeEarnings;
}else {
overtimeHours[i] = 0.0;
grossPay[i] = hours[i] * payRate[i];
}
}
}
/**
* Calculate Net method calculates the net pay of each employee after taxes and stores it in netPay member
*
* @param sT = stateTax
* @param fT = fedTax
* @param uF = unionFees
*/
void calculateNet(final double sT,final double fT, final double uF)
{
for(int i = 0; i < SIZE; i++)
{
stateTax[i] = grossPay[i] * sT;
fedTax[i] = grossPay[i] * fT;
unionFees[i] = grossPay[i] * uF;
netPay[i] = grossPay[i] - (stateTax[i] + fedTax[i] + unionFees[i]);
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T10:49:30.827",
"Id": "478966",
"Score": "0",
"body": "bump :((((((((("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T11:48:29.257",
"Id": "478971",
"Score": "1",
"body": "Give us time to answer. Reviewing a code and writing a polite, well described and useful answer take time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T12:50:22.703",
"Id": "478977",
"Score": "0",
"body": "@gervais.b didn't mean to rush! I'm new to the forum and wasn't sure if anyone would answer after so many hours."
}
] |
[
{
"body": "<p>So, you would like to know if your code is <em>"following the Single Responsibility\nSOLID principle"</em>. <em>S.O.L.I.D.</em> stand for <em>Single responsibility</em>,\n<em>Open-closed principle</em>, <em>Liskov substitution principle</em>, <em>Interface segregation</em>\nand <em>Dependency Inversion</em>.</p>\n<h2>Single responsibility</h2>\n<p><em>One class have a single responsibility</em>. But both <code>Payroll</code> and <code>Employees</code> are\nmixing business logic, IOs and datas.</p>\n<h2>Open-closed principle</h2>\n<p><em>Classes should be open for extension but closed for modification</em>. This is not\neasily applicable in your case.</p>\n<p>Try to implement different way to compute the payroll.</p>\n<h2>Liskov substitution</h2>\n<p><em>Classes should be replaceable with subtypes</em>. This one is not applicable because\nthere are no inheritance in your code.</p>\n<h2>Interface segregation</h2>\n<p><em>Client should not depend on interfaces they don't use</em>. Like for the previous,\nthis one is not easily applicable in a small system.</p>\n<h2>Dependency Inversion</h2>\n<p><em>Depend on abstraction</em>. Once again, this is not easily applicable in a small\nsystem. But one way will be to pass your <code>Employees</code> to <code>Payroll</code> instead of\ncreating the instance. By doing that you can easily imagine to have another\nimplementation of your <code>Employess</code>.</p>\n<hr />\n<p>You also want some tips on formatting but you are already using <code>printf</code>. However\nyour column are still missaligned due to different name length.</p>\n<p>One solution would be to compute the minimum length of your columns to build the\nformatting pattern.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T13:02:19.313",
"Id": "243981",
"ParentId": "243941",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T19:53:51.240",
"Id": "243941",
"Score": "2",
"Tags": [
"java",
"object-oriented",
"console",
"formatting"
],
"Title": "Command Line app for calculating payroll in Java"
}
|
243941
|
<p>So I'm currently using python to unscramble words that are retrieved from an OCR program (pytesseract).</p>
<p>The current code I am using to unscramble words is this:</p>
<pre><code>import numpy as nm
import pytesseract
import cv2
import ctypes
from PIL import ImageGrab
def imToString():
# Path of tesseract executable
pytesseract.pytesseract.tesseract_cmd =r'C:\Program Files (x86)\Tesseract-OCR\tesseract'
while(True):
# ImageGrab-To capture the screen image in a loop.
# Bbox used to capture a specific area.
cap = ImageGrab.grab(bbox =(687, 224, 1104, 240))
# Converted the image to monochrome for it to be easily
# read by the OCR and obtained the output String.
tesstr = pytesseract.image_to_string(
cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY),
lang ='eng')
checkWord(tesstr)
def checkWord(tesstr):
dictionary =['orange', 'marshmellow']
scrambled = tesstr
for word in dictionary:
if sorted(word) == sorted(scrambled):
print(word)
imToString()
</code></pre>
<p>I wanna know if there is anyway to <strong>reduce</strong> the time it takes to:</p>
<ul>
<li>Scan/Process the image.</li>
<li>Look through the 'dictionary', as there are many more words to go through. Or another more efficient alternative.</li>
</ul>
<p>Thanks</p>
|
[] |
[
{
"body": "<p>You are sorting your dictionary each time you use it, do it once and store it.</p>\n\n<p>Also, you are sorting your scrambled word more than once, only do it once:</p>\n\n<pre><code>import numpy as nm \nimport pytesseract \nimport cv2 \nimport ctypes\nfrom PIL import ImageGrab \n\ndef imToString(dictionary): \n\n # Path of tesseract executable \n pytesseract.pytesseract.tesseract_cmd =r'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract'\n while(True): \n\n # ImageGrab-To capture the screen image in a loop. \n # Bbox used to capture a specific area. \n cap = ImageGrab.grab(bbox =(687, 224, 1104, 240))\n\n\n # Converted the image to monochrome for it to be easily \n # read by the OCR and obtained the output String. \n tesstr = pytesseract.image_to_string( \n cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY), \n lang ='eng') \n checkWord(tesstr, dictionary)\n\ndef checkWord(tesstr, dictionary):\n\n scrambled = tesstr\n sorted_scrambled = sorted(scrambled) # Only do this 1 time\n if sorted_scrambled in dictionary:\n print(dictionary[sorted_scrambled]\n\n# ... Create your dictionary somewhere else and pass it in:\ndictionary ={sorted('orange'): 'orange',sorted('marshmellow'): 'marshmellow'}\n\nimToString(dictionary) \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T17:03:36.093",
"Id": "478872",
"Score": "0",
"body": "I've tried this, and it's giving me an error: unhashable type: 'list'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T13:49:29.763",
"Id": "478873",
"Score": "0",
"body": "We need more of an error than that - what's the stack trace, etc..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T14:45:57.467",
"Id": "478874",
"Score": "0",
"body": "If you want code that is verified to be correct, mock your pytesseract stuff and post an example: https://stackoverflow.com/help/minimal-reproducible-example"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T11:27:04.730",
"Id": "243943",
"ParentId": "243942",
"Score": "2"
}
},
{
"body": "<p>I can't speak to the image processing, but you can easily make the word check faster by preprocessing into an actual dict:</p>\n\n<pre><code>from collections import defaultdict\n\ndef build_dict(words):\n sorted_words = defaultdict(set)\n for word in words:\n sorted_words[''.join(sorted(word))].add(word)\n return sorted_words\n\ndef check_word(word, sorted_words):\n return sorted_words.get(''.join(sorted(word)), {})\n</code></pre>\n\n<p>This way, you create a dictionary that maps the <em>sorted</em> version of the word to a set of all the words that it could be. You then check whether your scramble set exists, and if found returns all the possible words it could be. </p>\n\n<p>In use:</p>\n\n<pre><code>>>> sorted_words = build_dict(['orange', 'yellow', 'taco', 'coat'])\n>>> check_word('blue', sorted_words)\n{}\n>>> check_word('rngaeo', sorted_words)\n{'orange'}\n>>> check_word('octa', sorted_words)\n{'coat', 'taco'}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T11:32:33.657",
"Id": "243944",
"ParentId": "243942",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T11:21:56.993",
"Id": "243942",
"Score": "3",
"Tags": [
"python",
"sorting"
],
"Title": "Unscramble words faster in Python"
}
|
243942
|
<p>I have a class that imports the FX Rates produced by another department.</p>
<p>This works as intended, which is to return a Pandas DataFrame with all FX Rates by month.</p>
<p>The DataFrame it returns is then used by another 5 classes, that basically import other files and do some formatting and calculations with their own columns, always using the FX Rates from the FxRates class.</p>
<p>I run this code in a Jupyter Notebook.</p>
<p>I want to know if:</p>
<ol>
<li>Code is <strong>refactored enough</strong> or <strong>over-refactored</strong></li>
<li>Is it good practice to update the instance variables as I have done so?</li>
<li>Is there anything else that stands out as being bad practice?</li>
</ol>
<pre><code>class FxRates:
def __init__(self, reporting_date):
self.reporting_date = reporting_date
self.path = self.get_path()
def get_path(self):
"""Get path for the Fx Rates."""
content_list = listdir(os.path.join(os.getcwd(), 'Data'))
file_path = os.path.join(
os.getcwd(),
'Data',
list(filter(lambda x: 'FX rates' in x, content_list))[0]
)
return file_path
def reporting_date_check(self):
"""
Check if date input follows the criteria below:
31/12/yyyy, 31/03/yyyy, 30/06/yyyy, 30/09/yyyy
"""
accepted_dates = [
'31/12',
'31/03',
'30/06',
'30/09'
]
# Check if first 5 characters match accepted_dates
if self.reporting_date[:5] in accepted_dates:
reporting_date = pd.to_datetime(self.reporting_date,
dayfirst=True)
self.reporting_date = reporting_date
else:
# If not, raise ValueError
raise ValueError(
"""reporting_date does not match one of the following:
31/12/yyyy, 31/03/yyyy, 30/06/yyyy, 30/09/yyyy"""
)
def import_excel_rates(self):
"""Import FX Rates in Excel file from Group."""
rates = pd.read_excel(self.path,
sheet_name='historic rates',
skiprows=2,
header=None,
usecols='B:O',
skipfooter=1)
return rates
def EWI_check(self, rates):
"""
Check if the reporting month already has FX Rates defined.
If not, copy FX Rates from previous month.
"""
# For EWI we need to use FX Rates from 1 month before
if pd.isnull(rates.iloc[0, self.reporting_date.month]):
print("""
\n########## Warning ##########:
\nThere are no FX Rates for {0}/{1}.
\nFX Rates being copied from {2}/{3}.\n""".format(
rates.columns[self.reporting_date.month],
self.reporting_date.year,
rates.columns[self.reporting_date.month - 1],
self.reporting_date.year
))
# Copy FX Rates from previous month
rates.iloc[:, self.reporting_date.month] = \
rates.iloc[:, self.reporting_date.month - 1]
else:
pass
return rates
def import_rates(self):
"""
Import Group Fx rates into a Pandas Dataframe
"""
# Check if reporting date is correct
self.reporting_date_check()
# Import FX Rates in Excel file
rates = self.import_excel_rates()
# Set column headers manually
rates.columns = ['ISO Code',
'December ' + str(self.reporting_date.year - 1),
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December']
# Set ISO Code as Index
rates.index = rates['ISO Code'].values
rates.drop('ISO Code', axis=1, inplace=True)
# Check if we have FX Rates for the reporting month
# If not, copy from last month
return self.EWI_check(rates)
</code></pre>
|
[] |
[
{
"body": "<h2>A note on terminology</h2>\n<p>"Refactored enough" is only meaningful relative to the code's current state and how it was before; but "over-refactored" is kind of meaningless. I guess the only time that idea could even be applicable is if refactoring occupied too much time or too many corporate resources. Maybe you mean over-abstracted, but that's conjecture. Anyway.</p>\n<h2>Type hints</h2>\n<p><code>reporting_date</code> could stand to get a type hint, likely <code>: str</code> given your later usage of this variable.</p>\n<h2>Pathlib</h2>\n<p>Consider replacing <code>listdir</code>, <code>os.path.join</code> and <code>os.getcwd</code> with <code>pathlib.Path</code> equivalents, which are typically better-structured and have nice object representations for paths.</p>\n<h2>Parsing</h2>\n<p>Don't store the string representation of <code>reporting_date</code>. Do something in the constructor like <code>self.reporting_date = self.parse_date(reporting_date)</code>, where the latter is a static method to replace your current <code>reporting_date_check</code>. This method would not mutate member variables and would simply return the date once it's figured that out.</p>\n<h2>Sets</h2>\n<pre><code> accepted_dates = [\n '31/12',\n '31/03',\n '30/06',\n '30/09'\n ]\n</code></pre>\n<p>should be a class static, initialized via set literal - something like</p>\n<pre><code>class FxRates:\n ACCEPTED_DATES = {\n '31/12',\n '31/03',\n '30/06',\n '30/09',\n }\n</code></pre>\n<p>That said, the approach is a little backwards. You should not do string comparison on the string-formatted date. Parse it first, then do validation on its integer parts after. The accepted dates above can turn into a set of 2-tuples, <code>(day, month)</code>.</p>\n<h2>Heredocs</h2>\n<p>This:</p>\n<pre><code> print("""\n \\n########## Warning ##########:\n \\nThere are no FX Rates for {0}/{1}.\n...\n</code></pre>\n<p>is problematic. You're packing a bunch of whitespace in there that you shouldn't. One solution is to move the string to a global constant to avoid the indentation; you should also replace the explicit <code>\\n</code> with actual newlines in the string. Another solution is to keep the text where it is but replace it with a series of implicit-concatenated strings, one per line, i.e.</p>\n<pre><code>print(\n "########## Warning ##########:\\n"\n "There are no FX Rates for {0}/{1}.\\n"\n# ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T07:06:56.433",
"Id": "479172",
"Score": "0",
"body": "Thanks for the answer! And about the refactoring, I definitely meant \"over-abstracted\". I've read so much about functions that \"do one thing, and one thing only\" that now I'm paranoid about putting 2 actions in the same function. So, in your opinion, does the code above have a good balance between what each function does?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T12:11:32.717",
"Id": "479198",
"Score": "0",
"body": "Seems pretty good to me"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T04:14:28.080",
"Id": "244019",
"ParentId": "243946",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "244019",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T20:24:25.007",
"Id": "243946",
"Score": "6",
"Tags": [
"python",
"python-3.x"
],
"Title": "Class that imports FX Rates from Excel File"
}
|
243946
|
<p>I want to fill an array of strings with the name of each directory item. The issue is allocating memory. I either need to count the items before, allocate memory, then go over them again, or I will have to reallocate each iteration of the while loop. Both of these options seem slow. Surely there's a better way.</p>
<p>Which is faster:</p>
<pre><code>char **Names;
DIR *Dir = opendir("Some dir path");
struct dirent *Entry;
unsigned int Count = 0;
while ((Entry = readdir(Dir))) {
Count++;
}
Names = malloc(Count*sizeof(char*));
closedir(Dir);
Dir = opendir("Some dir path"); //Also, is there a better way to reset it, other than closing it and reopening?
for (int i = 0; (Entry = readdir(Dir); i++) {
unsigned short NamLen = strlen(Entry->d_name)+1;
Names[i] = malloc(NameLen);
memcpy(Names[i], entry->d_name, NameLen);
}
</code></pre>
<p>Or</p>
<pre><code>char **Names;
DIR *Dir = opendir("Some dir path");
Dir = opendir("Some dir path");
struct dirent *Entry;
for (int i = 0; (Entry = readdir(Dir); i++) {
Names = realloc(Names, i*sizeof(char*));
unsigned short NamLen = strlen(Entry->d_name)+1;
Names[i] = malloc(NameLen);
memcpy(Names[i], entry->d_name, NameLen);
}
closedir(Dir);
</code></pre>
<p>Please help, I'm stuck. Both of these seem less efficient than optimal, so surely there's a better way. What's the fastest way to record all the names of items in a directory to a string array? Is there a faster option aside these two?</p>
|
[] |
[
{
"body": "<p>Calling <code>realloc</code> in every iteration makes the code really slow. Algorithmically it is in <span class=\"math-container\">\\$\\mathcal O(n^2)\\$</span> since realloc already has complexity <span class=\"math-container\">\\$\\mathcal O(n)\\$</span>. Plus, you are calling it interleaved with <code>malloc</code> for the name of the directory entries.</p>\n<p>The performance of your program depends very much on the specific memory allocator. It might be very fast or very slow, probably somewhere between <span class=\"math-container\">\\$n\\$</span> and <span class=\"math-container\">\\$n^2\\$</span>.</p>\n<p>To fix this, you should use the well-known pattern of having a triplet <code>(pointer, length, capacity)</code> to represent the growing buffer of directory entries.</p>\n<p>Ideally you define a separate <code>struct</code> for this, together with an <code>append</code> function. That way, the function that reads the directory entries doesn't have to fiddle with <code>realloc</code> directly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T21:47:23.480",
"Id": "243952",
"ParentId": "243947",
"Score": "2"
}
},
{
"body": "<p>the fastest way is to keep a counter of the number of entries allocated. then on the first call to <code>realloc()</code> just allocate for a single entry. Only call <code>realloc()</code> when all the current allocation is used. each time `realloc() is called, double the allocation count. I.E. 1, 2, 4, 8, 16, 32, etc.</p>\n<p>Be sure to always assign the result of <code>realloc()</code> to a temp variable, check that variable to assure it is not NULL, before assigning to the target variable to avoid a unrecoverable memory leak when <code>realloc()</code> fails</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T08:12:20.407",
"Id": "244028",
"ParentId": "243947",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T20:39:51.357",
"Id": "243947",
"Score": "3",
"Tags": [
"performance",
"c",
"file",
"file-system"
],
"Title": "What is the fastest way to record the names of each file in a directory?"
}
|
243947
|
<p>I have a couple questions about this program</p>
<ol>
<li><p>Should I implement runnable instead of using thread class? I like the idea of the consumer and producer being thread objects, it seems simpler to me, but I have seen people argue the benefits if runnable interface.</p>
</li>
<li><p>Are static methods in the main class considered good/bad convention?</p>
</li>
<li><p>For a factory pattern like this, is the parent of the two bank accounts the best place to put the multithreading logic?</p>
</li>
<li><p>Should setters be included always? Or should they be left out if the constructor is the only method that should set values? Is one of these approaches bad practice?</p>
</li>
<li><p>Does an arraylist of accounts count as tight coupling and if so should it be abandoned? If so, what is the best way for a bank object to have access to each account?</p>
</li>
</ol>
<p>Thank you in advance</p>
<p>bank class:</p>
<pre class="lang-java prettyprint-override"><code> package Model;
import java.util.ArrayList;
public class Bank {
private ArrayList<BankAccount> accounts;
private static int numberOfBanks;
private int routingNumber;
public Bank() {
this.accounts = new ArrayList<BankAccount>();
this.routingNumber = ++numberOfBanks;
}
}
</code></pre>
<p>BankAccount.java:</p>
<pre class="lang-java prettyprint-override"><code>
package Model;
import java.util.Date;
abstract class BankAccount {
static private int numberOfAccounts;
private int accountNumber;
private double balance;
private String accountHolder;
private Date accountOpened;
private int withdrawsLeft;
public BankAccount(String name) {
this.accountNumber = ++numberOfAccounts;
this.balance = 0;
this.accountHolder = name;
this.accountOpened = new Date();
}
public BankAccount(String name, double initialBalance) {
this.balance = initialBalance;
this.accountHolder = name;
this.accountOpened = new Date();
}
public static int getNumberOfAccounts() {
return numberOfAccounts;
}
public static void setNumberOfAccounts(int numberOfAccounts) {
BankAccount.numberOfAccounts = numberOfAccounts;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public synchronized double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public String getAccountHolder() {
return accountHolder;
}
public void setAccountHolder(String accountHolder) {
this.accountHolder = accountHolder;
}
public Date getAccountOpened() {
return accountOpened;
}
public void setAccountOpened(Date accountOpened) {
this.accountOpened = accountOpened;
}
public int getWithdrawsLeft() {
return withdrawsLeft;
}
public void setWithdrawsLeft(int withdrawsLeft) {
this.withdrawsLeft = withdrawsLeft;
}
public synchronized void deposit(double d) {
try {
Thread.sleep(300);
}
catch(InterruptedException e) {
e.getMessage();
}
balance += d;
printReceipt();
}
public synchronized void withdraw(double w) {
while (w > balance) {
try {
wait(); // wait for funds
} catch (InterruptedException ie) {
System.err.println(ie.getMessage());
}
}
if (balance > 0) {
balance -= w;
printReceipt();
}
else System.out.println("ERROR: You are way too broke for that!");
}
public void printReceipt() {
System.out.println(getAccountHolder() + "\'s balance is " + getBalance() + "0 on " + accountOpened.toString());
}
}
</code></pre>
<p>Main.java:</p>
<pre class="lang-java prettyprint-override"><code>
package Model;
public class Main {
public static void main(String[] args) {
Bank bankOfJames = new Bank();
BankAccountFactory fact = new BankAccountFactory();
BankAccount james = fact.getAccount("savings account","james", 1000.0);
Thread[] users = new Thread[10];
int[] threadNames = new int[10];
for(int i = 0; i < users.length; i++) {
if(i % 2 == 0) users[i] = new Producer(james);
else users[i] = new Consumer(james);
}
for(int i = 0; i < users.length; i++) {
System.out.println("Starting thread " + users[i].getName());
users[i].start();
}
for(int i = 0; i < users.length; i++) {
try {
System.out.println("Joining thread " + users[i].getName());
users[i].join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
static class Producer extends Thread{
BankAccount a;
Producer(BankAccount ba){
this.a = ba;
}
public void run() {
a.deposit(100);
}
}
static class Consumer extends Thread{
BankAccount a;
Consumer(BankAccount ba){
this.a = ba;
}
public void run() {
a.withdraw(50);
}
}
}
</code></pre>
<p>CheckingAccount.java:</p>
<pre class="lang-java prettyprint-override"><code> package Model;
public class CheckingAccount extends BankAccount {
public CheckingAccount(String name) {
super(name);
// TODO Auto-generated constructor stub
}
public CheckingAccount(String name, double initialBalance) {
super(name, initialBalance);
// TODO Auto-generated constructor stub
}
public void writeCheck() {
System.out.println("writing check");
}
}
</code></pre>
<p>SavingsAccount.java:</p>
<pre class="lang-java prettyprint-override"><code> package Model;
public class SavingsAccount extends BankAccount {
private double interestRate;
public double getInterestRate() {
return interestRate;
}
public void setInterestRate(double interestRate) {
this.interestRate = interestRate;
}
public SavingsAccount(String name) {
super(name);
// TODO Auto-generated constructor stub
}
public SavingsAccount(String name, double initialBalance) {
super(name, initialBalance);
// TODO Auto-generated constructor stub
}
public void compoundInterest() {
double current = getBalance();
current *= interestRate;
setBalance(current);
}
}
</code></pre>
<p>BankAccountFactory.java</p>
<pre class="lang-java prettyprint-override"><code> package Model;
public class BankAccountFactory {
public BankAccount getAccount(String account, String name) {
if(account.equalsIgnoreCase("checkingaccount") || account.equalsIgnoreCase("checking account")) {
return new CheckingAccount(name);
}
else if(account.equalsIgnoreCase("savingsaccounts") || account.equalsIgnoreCase("savings account")) {
return new SavingsAccount(name);
}
else{
System.out.println("Please indicate savings or checking account");
return null;
}
}
public BankAccount getAccount(String account, String name, double balance) {
if(account.equalsIgnoreCase("checkingaccount") || account.equalsIgnoreCase("checking account")) {
return new CheckingAccount(name, balance);
}
else if(account.equalsIgnoreCase("savingsaccounts") || account.equalsIgnoreCase("savings account")) {
return new SavingsAccount(name, balance);
}
else{
System.out.println("Please indicate savings or checking account");
return null;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T22:51:52.053",
"Id": "479717",
"Score": "0",
"body": "Any feedback would be very helpful!"
}
] |
[
{
"body": "<h1>Naming</h1>\n<p>I'm sure you already know this, but naming matters. The few keystrokes that you save using <code>w</code> are paid for every time somebody reads the code. Consider always using more meaningful names <code>withdrawalAmount</code> etc.</p>\n<p>Be cautious about reusing names of classes from the standard library. Rather than <code>Consumer</code>, consider giving it a more specific name to reflect what it's consuming. This will both be more descriptive and remove the name conflict with <code>Consumer<T></code>.</p>\n<h1>Scenario</h1>\n<p>The scenario you've constructed feels a bit forced, which makes it more difficult to assess if the code really makes sense. Bank accounts don't really a producer/consumer relationship. Spinning up a new thread, in order to perform a single transaction feels very inefficient. On the face of it, your producer creates money and your consumer removes money. I can't help but feel like really, they are both producing transactions that would be better served by a <code>TransactionConsumer</code>.</p>\n<h1>Factory</h1>\n<p>Consider using an enum rather than a raw <code>String</code> for the account. Perhaps you need the flexibility of a string, however if you can use an enum it makes typo's less likely and removes the need for your 'else' conditions.</p>\n<p>Generally speaking, when you can't handle a situation you want to throw an exception. The error printed if an unsupported account is specified suggests that the caller does something else do you really want this method to return <code>null</code> in that scenario? If you do want to support 'possibly' creating the account, consider returning an <code>Optional</code> instead to give the caller a hint that it could fail. Currently your <code>main</code> doesn't check if null is returned, so you'll end up with <code>NullPointerException</code>s from your Producer/Consumers.</p>\n<p>If the intention is to only have the accounts created by your factory, I would consider dropping the non-balance constructor from your accounts. This would make it easier to overload the construction methods and chain them:</p>\n<pre><code>public BankAccount getAccount(String account, String name) {\n return getAccount(account, name, 0);\n}\n</code></pre>\n<h1>BankAccount</h1>\n<p>To answer question 4, no you shouldn't always include setters. If you don't want the value to be changed from outside the class after construction, don't include setters. In the future, people with less context may decide that since it's there, it must be ok to use it. <code>setBalance</code> is a good example of a confusing setter. Why would you want an external actor to be able to set the balance of this account? But what makes it stand out is that whilst <code>getBalance</code>, <code>deposit</code> and <code>withdrawal</code> are synchronised, <code>setBalance</code> isn't. So, somebody could do a deposit and have a receipt for a different balance entirely printed...</p>\n<p>Money is one of those things where people start getting upset if rounding errors start impacting their balance. Generally speaking you should be using <code>BigDecimal</code> for money, rather than relying on <code>double</code>.</p>\n<p>I'm not a huge fan of overly commented code, however in your deposit method you sleep for 300. Consider adding a comment as to why you're sleeping, or extracting the logic into a private method that indicates what the sleep is about, something like <code>simulateSlowProcessing</code> perhaps.</p>\n<p>To me, <strong>withdraw has a bug</strong>. If a withdrawal comes in that is more than the balance, the thread can't escape until after the balance goes above that value. This might be ok, if you were waiting for a message to process, however it doesn't really seem to make sense for a withdrawal. If you don't have money, you expect it to tell you that and move on. Indeed, if you escape the while loop, you perform a check that suggests you want to be able to fail transactions if there isn't sufficient funds. Because the scenario isn't entirely clear, it's difficult to know what you expect the behaviour to be. Changing <code>Main.Consumer</code> to withdraw 500, for example can result in the program never exiting.</p>\n<p>It also looks like there is an <strong>AccountNumber bug</strong>. Again, this is probably caused by the scenario, however you're using a static to set the account number for created accounts. However, you only do this through the 'name' constructor. You don't do it through the 'name' and 'initial balance' constructor, which is the one you're actually using.</p>\n<h1>SavingsAccount</h1>\n<p><strong>compoundInterest has a bug</strong> in my view. You're not currently calling it, however it makes use of <code>setBalance</code> on the base class. You get the balance, perform some calculation and then set the balance. It's possible for <code>deposit</code>/<code>withdrawal</code> to be called between the <code>getBalance</code> and the <code>setBalance</code> which meaning that money can be lost or gained as a consequence. If you want to do stuff like this, then it would be better to use the atomic adjustment methods in the base class. So, for example you could use <code>deposit</code> to add a calculated amount of interest to the balance...</p>\n<h1>Your questions</h1>\n<ol>\n<li><p>Whether or not to use runnable or thread class depends on what you're doing, at the moment I don't think it makes a lot of difference either way. As I've said, I'm not sure that spinning up a thread for each transaction really makes sense to me.</p>\n</li>\n<li><p><code>static</code> methods in your main class are fine, however, you want your main to be responsible for one thing, typically bootstrapping your application. With that in mind, the scope for having many static methods should be quite small. I think the same applies for <code>static</code> classes, they aren't 'bad', however they may be a sign that the Main class is doing too much.</p>\n</li>\n<li><p>For multi-threading, control performed at the right level. Typically, you want to minimise the amount of time when objects are locked, so protecting balance in the base object seems to make sense. However, as I've already indicated you need to be careful about what you do in derived classes to ensure you don't accidentally break that encapsulation.</p>\n</li>\n<li><p>Setters aren't always required, fields that you don't expect at all (open date, account number...) should also be marked as <code>final</code>. Some serialisation may require setters, but then you might want to reconsider your logic location.</p>\n</li>\n<li><p>An arraylist of accounts sounds OK in principal, however you've not done anything with it the code. Whether or not it's tightly coupled really depends on what you do with it and how/if you expose it to other classes. A <code>HashMap</code> of accountNumber to Account might make more sense... but consider how/if your Bank needs to know the type of account and how it will identify them.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T21:03:08.537",
"Id": "480631",
"Score": "0",
"body": "I really appreciate all the time you put into this response. thank you. Your comments/answers/critiques are very helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T08:37:32.800",
"Id": "244701",
"ParentId": "243950",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244701",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T21:07:07.780",
"Id": "243950",
"Score": "4",
"Tags": [
"java",
"object-oriented",
"multithreading",
"factory-method",
"static"
],
"Title": "Bank with factory method for accounts, multithreaded deposit and withdraw"
}
|
243950
|
<p>I want to fill an array of <code>dirent</code> pointers with each entry of a specified directory. I either need to count the items before, allocate memory, then go over them again, or I will have to reallocate each iteration of the while loop. Both of these options seem slow. Surely there's a better way.</p>
<p>Are these my only option:</p>
<pre><code>struct dirent **Entries;
DIR *Dir = opendir("Some dir path");
struct dirent *Entry;
unsigned int Count = 0;
while ((Entry = readdir(Dir))) {
Count++;
}
Entries = malloc(Count*sizeof(struct dirent*));
rewinddir(Dir);
for (int i = 0; (Entry = readdir(Dir); i++) {
Entries[i] = Entry;
}
</code></pre>
<p>Or</p>
<pre><code>struct dirent **Entries;
DIR *Dir = opendir("Some dir path");
Dir = opendir("Some dir path");
struct dirent *Entry;
for (int i = 0; (Entry = readdir(Dir); i++) {
Entries = realloc(Entries, i*sizeof(struct dirent*));
Entries[i] = Entry;
}
closedir(Dir);
</code></pre>
<p>Or is there some faster way?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T23:09:47.610",
"Id": "478900",
"Score": "0",
"body": "C and the standard C library have no ways to read a directory. Fastest way is implementation dependent - if it exists. I recommend to add a tag to the implementation used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T23:11:01.617",
"Id": "478901",
"Score": "0",
"body": "@chux-ReinstateMonica But surely there's a cross platform way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T23:13:10.577",
"Id": "478902",
"Score": "0",
"body": "Not in general. Again, recommend to add a tag to the implementation used. Not all platforms have a file system."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T23:15:06.393",
"Id": "478903",
"Score": "0",
"body": "Curious, why `char*` in `malloc(Count*sizeof(char*));`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T00:08:09.127",
"Id": "478910",
"Score": "0",
"body": "@chux-ReinstateMonica I made a boo boo. I MADE A BOO BOO!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T00:08:28.490",
"Id": "478911",
"Score": "1",
"body": "We could provide better suggestions if you included more of the code rather than just snippets."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T00:26:41.287",
"Id": "478925",
"Score": "1",
"body": "Please do not edit the code after an answer has been posted. The code that everyone sees should be the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T00:28:21.580",
"Id": "478926",
"Score": "0",
"body": "@pacmaninbw That was a boo boo and none of the answers rely on it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T00:30:25.090",
"Id": "478927",
"Score": "1",
"body": "It was observed by the person that wrote the review, and the rules are clear that code should not be edited after an answer has been posted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T00:30:57.103",
"Id": "478928",
"Score": "0",
"body": "@user226181 Use `Entries = malloc(Count*sizeof *Entries);` and 1) not make boo boos, easier to review and maintain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T00:27:34.960",
"Id": "478929",
"Score": "0",
"body": "I decided to use [`scandir()`](https://linux.die.net/man/3/scandir) for this purpose."
}
] |
[
{
"body": "<p>OP poses 2 approaches</p>\n<ol>\n<li><p>Iterate twice through <code>opendir(), readdir(), closedir()</code> with one <code>malloc()</code>.</p>\n</li>\n<li><p>Iterate one through <code>opendir(), readdir(), closedir()</code> with multiple <code>realloc()</code>.</p>\n</li>\n</ol>\n<p>For performance, I would use a 3rd option: linked list instead of using an array of <code>struct dirent</code></p>\n<ol start=\"3\">\n<li>Iterate once through <code>opendir(), readdir(), closedir()</code> with one <code>malloc()</code> per entry.</li>\n</ol>\n<hr />\n<p>As with such performance issue: strive for reduced <a href=\"https://en.wikipedia.org/wiki/Time_complexity\" rel=\"nofollow noreferrer\">big O</a>, not linear ones.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T23:27:07.270",
"Id": "478906",
"Score": "0",
"body": "I like how you understand my question. You put my problems in better words than I did :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T23:22:25.610",
"Id": "243955",
"ParentId": "243951",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243955",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T21:40:48.357",
"Id": "243951",
"Score": "1",
"Tags": [
"c",
"file-system"
],
"Title": "What is the fastest way to record the listed files in a directory in C?"
}
|
243951
|
<p>Here I'm posting my code for the <a href="https://leetcode.com/problems/reorganize-string/" rel="nofollow noreferrer">Reorganize String problem on LeetCode</a>. If you have time and would like to review, please do so, I'd appreciate that.</p>
<p>On LeetCode, we are only allowed to change the argument names and brute force algorithms are discouraged, usually fail with TLE (Time Limit Error) or MLE (Memory Limit Error).</p>
<h3>Problem</h3>
<blockquote>
<p>Given a string S, check if the letters can be rearranged so that two
characters that are adjacent to each other are not the same.</p>
<p>If possible, output any possible result. If not possible, return the
empty string.</p>
<p>Example 1:</p>
<p>Input: S = "aab" Output: "aba" Example 2:</p>
<p>Input: S = "aaab" Output: "" Note:</p>
<p>S will consist of lowercase letters and have length in range [1, 500].</p>
</blockquote>
<h3>Java</h3>
<pre><code>class Solution {
public String reorganizeString(String baseString) {
int[] charMap = initializeCharMap26(baseString);
int max = 0;
int letter = 0;
for (int iter = 0; iter < charMap.length; iter++)
if (charMap[iter] > max) {
max = charMap[iter];
letter = iter;
}
if (max > ((-~baseString.length()) >> 1))
return "";
char[] reorganized = new char[baseString.length()];
int index = 0;
while (charMap[letter] > 0) {
reorganized[index] = (char) (letter + 97);
index += 2;
charMap[letter]--;
}
for (int iter = 0; iter < charMap.length; iter++) {
while (charMap[iter] > 0) {
if (index >= reorganized.length)
index = 1;
reorganized[index] = (char) (iter + 97);
index += 2;
charMap[iter]--;
}
}
return String.valueOf(reorganized);
}
private int[] initializeCharMap26(String baseString) {
int[] charMap = new int[26];
for (int i = 0; i < baseString.length(); i++)
charMap[baseString.charAt(i) - 97]++;
return charMap;
}
}
</code></pre>
<h3>Reference</h3>
<p><a href="https://leetcode.com/problems/reorganize-string/" rel="nofollow noreferrer">767. Reorganize String (Problem)</a></p>
<p><a href="https://leetcode.com/problems/reorganize-string/solution/" rel="nofollow noreferrer">767. Reorganize String (Solution)</a></p>
|
[] |
[
{
"body": "<p>Nice work! It's an efficient solution (linear in the length of the input string), using a simple yet quite clever logic to reorganize the letters, reasonably easy to read and well-formatted.</p>\n<h3>Improving readability</h3>\n<p>It's good to extract logical steps to helper methods, as you did for <code>initializeCharMap26</code>. You could split <code>reorganizeString</code> a bit further, extracting the logic of creating the reorganized string from parameters: the count of letters, the most common letter, and the target length.</p>\n<p>Instead of the hardcoded <code>97</code>, you could use <code>'a'</code>. That explains it better where the magic number comes from, and it's also easier to remember. To make the code even easier to understand, and to eliminate some duplicate logic, it would be good to create helper functions <code>charToIndex</code> and <code>indexToChar</code>.</p>\n<p>I think this part is cryptic and difficult to understand:</p>\n<blockquote>\n<pre><code>if (max > ((-~baseString.length()) >> 1))\n return "";\n</code></pre>\n</blockquote>\n<p>The idea is that given the count of the most frequent character, if there are not enough other characters, then the string cannot be reorganized. That is, if the length of the string is <code>n</code>, the most frequent character happens <code>k</code> times, then there must be at least <code>k - 1</code> other characters. In other words, <code>n - k >= k - 1</code> must hold. If we rewrite the condition to reflect this logic, I think it will be easier to understand:</p>\n<pre><code>if (baseString.length() - max < max - 1)\n return "";\n</code></pre>\n<h3>Using better names</h3>\n<p>I think some of the names could be better to be more descriptive, for example:</p>\n<ul>\n<li><code>charMap</code> -> <code>charCounts</code></li>\n<li><code>letter</code> -> <code>mostFrequentLetter</code></li>\n<li><code>max</code> -> <code>mostFrequentLetterCount</code></li>\n<li><code>initializeCharMap26</code> -> <code>stringToCharCounts</code>, or even just <code>toCharCounts</code></li>\n</ul>\n<p>I'm used to seeing <code>iter</code> (or <code>it</code>) when iterating of the <em>values</em> of an iterable, and <code>i</code> or <code>index</code> in simple counting loops iterating over array indexes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-16T19:54:42.510",
"Id": "269046",
"ParentId": "243956",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T23:43:29.107",
"Id": "243956",
"Score": "3",
"Tags": [
"java",
"performance",
"beginner",
"algorithm",
"programming-challenge"
],
"Title": "LeetCode 767: Reorganize String"
}
|
243956
|
<p>I have a <code>writeOnFile()</code> method with too many <code>fwrite()</code>.
I think it is not a good implementation because too many system calls may produce a high overhead.</p>
<p>What can I do?</p>
<hr />
<h2>Code</h2>
<pre class="lang-c prettyprint-override"><code>void writeOnFile()
{
char cr[1] = {'\n'}; //Usefull characters
char sp[1] = {' '};
char header1[] = "Instant "; //Headers
fwrite(header1, 1, strlen(header1), out);
char header2[] = "Playing (1 yes, 0 no) ";
fwrite(header2, 1, strlen(header2), out);
char header3[] = "Segment ID ";
fwrite(header3, 1, strlen(header3), out);
char header4[] = "Encode level\n";
fwrite(header4, 1, strlen(header4), out);
char strNumber[50]; //Data writing
for (int i = 0; i < global_index; i++)
{
snprintf(strNumber, 50, "%f", instants[i]);
fwrite(strNumber, 1, strlen(strNumber), out);
//Adds spaces
for (int i = 0; i < strlen(header1) - strlen(strNumber); i++)
fwrite(sp, 1, 1, out);
snprintf(strNumber, 50, "%d", playing[i]);
fwrite(strNumber, 1, strlen(strNumber), out);
for (int i = 0; i < strlen(header2) - strlen(strNumber); i++)
fwrite(sp, 1, 1, out);
snprintf(strNumber, 50, "%li", segment_index[i]);
fwrite(strNumber, 1, strlen(strNumber), out);
fwrite(sp, 1, 1, out);
for (int i = 0; i < strlen(header3) - strlen(strNumber) - 1; i++)
fwrite(sp, 1, 1, out);
snprintf(strNumber, 50, "%d", encode_level_buff[i]);
fwrite(strNumber, 1, strlen(strNumber), out);
//Inserts a \n at the end of the row but not at the end of file
if (i != global_index - 1)
fwrite(cr, 1, 1, out);
}
}
</code></pre>
<h2>Output example</h2>
<p><a href="https://i.stack.imgur.com/yZwgS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yZwgS.png" alt="enter image description here" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T03:10:24.027",
"Id": "478930",
"Score": "2",
"body": "You could greatly simplify your code - and gain the benefit of buffering - If you use `fprintf` and its variants instead of `fwrite`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T12:48:29.057",
"Id": "478976",
"Score": "1",
"body": "Isn't `fwrite` buffered as well? To actually count the number of system calls, use a tool such as `strace`, `truss` or `ktrace`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T18:41:29.433",
"Id": "479020",
"Score": "0",
"body": "Why \"Inserts a \\n at the end of the row but not at the end of file\"? Far more common to desire a final `'\\n'`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T07:37:53.180",
"Id": "479066",
"Score": "1",
"body": "The variable: `int i`, in all but the first `for()` statement, is shadowing the initial `i` variable. This can result in problems. Suggest all but the first `for()` loop use `int j` However, the function `strlen()` returns a `size_t` so the variable `i` and `j` should be defined as: `size_t i` and `size_t j`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T07:42:36.733",
"Id": "479068",
"Score": "0",
"body": "when ever calling: `fwrite()`, always check the returned value ( if not the same as the 3rd parameters, then some error has occurred.)"
}
] |
[
{
"body": "<blockquote>\n<p>I have a writeOnFile() method with too many fwrite(). ...</p>\n</blockquote>\n<p>A way to reduce <code>fwrite()</code> calls is to simply write all text to a large <code>char buffer[]</code> and then write that once per <code>for (int i = 0; i < global_index; i++)</code> loop.</p>\n<p>Use the return vale of <code>snprintf()</code> to speed calculation of next offset. Use <code>*printf()</code> features for padding.</p>\n<pre><code>for (int i = 0; i < global_index; i++) {\n char buf[N];\n int offset = 0;\n\n //snprintf(strNumber, 50, "%f", instants[i]);\n //fwrite(strNumber, 1, strlen(strNumber), out);\n //for (int i = 0; i < strlen(header1) - strlen(strNumber); i++)\n // fwrite(sp, 1, 1, out);\n\n // vv---- pad on right\n int len = snprintf(buf+offset, N - offset, "%-*f", (int) (sizeof header1 - 1), instants[i]);\n assert(len >= 0 && len < N - offset);\n offset += len;\n\n //snprintf(strNumber, 50, "%d", playing[i]);\n //fwrite(strNumber, 1, strlen(strNumber), out);\n //for (int i = 0; i < strlen(header2) - strlen(strNumber); i++)\n // fwrite(sp, 1, 1, out);\n\n len = snprintf(buf+offset, N - offset, "%-*d", (int) (sizeof header2 - 1), playing[i]);\n assert(len >= 0 && len < N - offset);\n offset += len;\n\n ....\n\n fwrite(buf, 1, offset, out);\n}\n</code></pre>\n<hr />\n<p>Some other ideas to linearly improve performance.</p>\n<p><strong>Why run down string again to find length?</strong></p>\n<pre><code>//snprintf(strNumber, 50, "%f", instants[i]);\n//fwrite(strNumber, 1, strlen(strNumber), out);\nint len = snprintf(strNumber, 50, "%f", instants[i]);\nfwrite(strNumber, 1, len, out);\n</code></pre>\n<p><strong>No need for <code>strlen()</code> for a constant string</strong></p>\n<pre><code>char header1[] = "Instant ";\n// fwrite(header1, 1, strlen(header1), out);\nfwrite(header1, 1, sizeof header1 - 1, out);\n</code></pre>\n<p><strong>Questionable "safe:" concerns</strong></p>\n<p><code>sprintf()</code> is certainly faster (or as fast) as <code>snprintf()</code> ....</p>\n<pre><code>// snprintf(strNumber, 50, "%d", playing[i]);\nsprintf(strNumber, "%d", playing[i]);\n</code></pre>\n<p>... yet by some coding standards, better to use <code>snprintf()</code> even though <code>"%d"</code> will not overfill 50 <code>char</code> array.</p>\n<p>What is curious about this "safe" code is the lack of checks of <code>fwrite()</code> return, a more likely issue.</p>\n<pre><code> // fwrite(strNumber, 1, strlen(strNumber), out);\n size_t nmemb = strlen(strNumber);\n size_t written = fwrite(strNumber, 1, nmemb, out);\n if (written != nmemb) Handle_Error();\n</code></pre>\n<hr />\n<p><strong>Watch out for <em>unsigned</em> bugs</strong></p>\n<p>Consider what happens when <code>strlen(header1) < strlen(strNumber)</code></p>\n<pre><code>for (int i = 0; i < strlen(header1) - strlen(strNumber); i++)\n</code></pre>\n<p>is like</p>\n<pre><code>for (int i = 0; i < strlen(header1) + (SIZE_MAX - strlen(strNumber) - 1); i++)\n</code></pre>\n<p>due to <em>unsigned</em> math wrap around.</p>\n<p>Better coded as</p>\n<pre><code>for (size_t i = strlen(strNumber); i < strlen(header1); i++)\n// or \nfor (size_t i = strlen(strNumber); i < sizeof header1 - 1; i++)\n</code></pre>\n<hr />\n<p><strong>Watch out for <em>long</em> <code>"%f"</code></strong></p>\n<p><code>"%f"</code> may takes 100s of characters for large FP values.</p>\n<p>Consider <code>"%g"</code>.</p>\n<hr />\n<p>Curious that OP's code did not start with <code>fprintf()</code> rather than <code>snprintf()/fwrite()</code>. This is another option.</p>\n<p>Conceptually, <code>fprintf()</code> is effectively doing the <code>char buffer[]</code> mentioned above albeit without many <code>fwrite()/fprintf()</code> calls.</p>\n<p>Switching to <code>fprintf()</code> and using the suggested padding format will be sufficient for a first level speed-up.</p>\n<p>For me, I do like the idea of writing a <em>line</em> with one I/O call. It is symmetric with the idea of reading one <em>line</em> on input code with <code>fgets()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T13:41:52.953",
"Id": "243985",
"ParentId": "243960",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "243985",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T01:23:02.603",
"Id": "243960",
"Score": "4",
"Tags": [
"c",
"file-system"
],
"Title": "Writing with too many system calls"
}
|
243960
|
<p>Hi :) I am a beginner coder who just learnt C++ and I wanted to apply it in projects to solidify my learning process. However, I only took a short tutorial before trying this out hence I'm pretty unsure about my C++ coding practices and I would like to know what areas I can improve on - and perhaps what kind of resources are available to do so. Additionally, I do feel that my project is a little sparse as of now so I would like suggestions on any features that I could add in to challenge my learning process and also make the bot a little cooler? Thanks for your thoughts in advance!</p>
<p><strong>Context</strong><br />
I used the API 'tgbot' created for coding Telegram Bots using C++ here: <a href="https://github.com/reo7sp/tgbot-cpp" rel="nofollow noreferrer">https://github.com/reo7sp/tgbot-cpp</a>.<br />
I coded and ran this program a Macbook Air on OSX 10.15 Catalina.</p>
<p><strong>Main Overview of the Bot</strong><br />
The user starts the bot function using '/start' - the bot prompts the user and this brings us to the main interface where:</p>
<ul>
<li>The program accepts a string from the user which details any troubles or any general concerns the user has regarding life</li>
<li>Parses through to check for keywords that indicate a certain genre/topic of quotes</li>
<li>If a topic is identified: a random quote from the topic will be returned</li>
</ul>
<p>After this, the a feedback interface is initialised and the user is asked if the quote was useful</p>
<ul>
<li>Some form of yes would redirect the user to the main interface</li>
<li>An ambiguous answer not detected to be either yes or no would prompt the user to key in only either one</li>
<li>Some form of no would allow the user to choose the reason of this: Was it the correct topic and wrong quote or the wrong topic?</li>
</ul>
<p>Wrong Topic: leads user to an interface of inline buttons where they can choose the relevant topic.
Wrong Quote: would simply generate another random quote of the same topic.</p>
<p>Note: In some of my main.cpp and my other files I may have mixed in the method of 'using namespace std;' and just using 'std::' wherever required because halfway through I heard the latter is better practice XD</p>
<p>Below is the main code with all the header and other source files.</p>
<p><strong>main.cpp</strong></p>
<pre><code>#include <string>
#include <random>
#include <fstream>
#include <vector>
#include <stdexcept>
#include <sstream>
#include <tgbot/tgbot.h>
#include <iostream>
#include "QuoteData.hpp"
#include "Functions.hpp"
using namespace std;
using namespace TgBot;
int main() {
//Setting up API
string token(getenv("TOKEN"));
cout << "Token: " << token.c_str() << endl;
//Telegram Bot object created using API token
Bot bot(token);
//Declaring/initializing important variables
std::vector<std::shared_ptr<QuoteTopic>> AllTopics = store_QuoteTopics();
// flag controls the segment of the chat we are in.
int flag = 1;
int TopicIndex;
std::string Return_Quote;
std::vector<string> favourites;
//Start page of the bot
bot.getEvents().onCommand("start", [&bot, &flag](const Message::Ptr& message) {
bot.getApi().sendMessage(message->chat->id,
"Hello, I'm InspoBot. I trade in your worries with a good inspirational quote to help you start the day right. "
"Think of me as a friend and type in whatever's been worrying you lately."
"\n \nYou can also key in the command '/topics' to choose from our list of quote topics." );
flag = 1;
});
//To look at and store favourites
bot.getEvents().onCommand("favourites", [&bot, &favourites](const Message::Ptr& message){
if (favourites.empty())
bot.getApi().sendMessage(message->chat->id, "Whoops, looks like you haven't saved any favourites yet. \n"
"First, find a quote by typing in what's been bothering you, or using the command"
" '/topics' to choose from our list of quote topics.");
else{
for (int n=0;n<favourites.size();n++){
bot.getApi().sendMessage(message->chat->id, favourites[n] + "\n \n");
}
}
});
//Creating Inline Keyboards: (Formatting and Respective Queries sent)
// 1. Quote Keyboard Configurations
InlineKeyboardMarkup::Ptr keyboard(new InlineKeyboardMarkup);
vector<InlineKeyboardButton::Ptr> topic_row;
//Creating Buttons
for(int n=0; n<AllTopics.size(); n++){
topic_row.clear();
InlineKeyboardButton::Ptr KeyboardButton (new InlineKeyboardButton);
KeyboardButton->text = AllTopics[n]->Topic;
KeyboardButton->callbackData = to_string(n);
topic_row.push_back(KeyboardButton);
keyboard->inlineKeyboard.push_back(topic_row);
}
//Manual method of access
bot.getEvents().onCommand("topics", [&bot, &keyboard] (const Message::Ptr& message) {
bot.getApi().sendMessage(message->chat->id, "Buttons."
,false, 0, keyboard, "Markdown");
});
//2. Choice Keyboard Configurations
InlineKeyboardMarkup::Ptr choice(new InlineKeyboardMarkup);
vector<InlineKeyboardButton::Ptr> choice_row;
//Creating Buttons
InlineKeyboardButton::Ptr KeyboardButton_1 (new InlineKeyboardButton);
KeyboardButton_1->text = "Wrong Subject";
KeyboardButton_1->callbackData = "Change Subject";
choice_row.push_back(KeyboardButton_1);
InlineKeyboardButton::Ptr KeyboardButton_2 (new InlineKeyboardButton);
KeyboardButton_2->text = "Wrong Quote";
KeyboardButton_2->callbackData = "Change Quote";
choice_row.push_back(KeyboardButton_2);
choice->inlineKeyboard.push_back(choice_row);
// Actions to be executed depending on what queries are sent
bot.getEvents().onCallbackQuery([&bot, &AllTopics, &flag, &TopicIndex, &keyboard, &Return_Quote] (const CallbackQuery::Ptr& query) {
if (query->data.find("Change")!=std::string::npos){
if (query->data=="Change Subject") {
bot.getApi().sendMessage(query->message->chat->id,
"Oh no. Here's a few buttons you can choose between to indicate your area of concern instead.",
false, 0, keyboard, "Markdown");
}
else{
Return_Quote = AllTopics[TopicIndex]->generate_quote();
bot.getApi().sendMessage(query->message->chat->id, "Here's another quote just for you: ");
bot.getApi().sendMessage(query->message->chat->id, Return_Quote + "\n");
bot.getApi().sendMessage(query->message->chat->id, "Was the quote useful for you?");
flag = 2;
}
}
else {
Return_Quote = AllTopics[stoi(query->data)]->generate_quote();
bot.getApi().sendMessage(query->message->chat->id, "Here's a quote just for you: ");
bot.getApi().sendMessage(query->message->chat->id, Return_Quote + "\n");
bot.getApi().sendMessage(query->message->chat->id, "Was this quote useful for you?");
flag = 2;
}
});
//Main Telegram Logic
bot.getEvents().onAnyMessage([&bot, &AllTopics, &flag, &choice, &TopicIndex, &favourites, &Return_Quote](const Message::Ptr &message) {
printf("User wrote %s\n", message->text.c_str());
if (StringTools::startsWith(message->text, "/start") || (message->text == "/end") ||
(message->text == "/topics")|| (message->text == "/favourites")) {
return;
}
//Main Chat
if (flag == 1) {
TopicIndex = which_topic(message->text, AllTopics);
if (TopicIndex == -1) {
bot.getApi().sendMessage(message->chat->id,
"Sorry, I couldn't quite understand you. Would you like to try again?");
return;
} else {
Return_Quote = AllTopics[TopicIndex]->generate_quote();
bot.getApi().sendMessage(message->chat->id, "Here's a quote just for you: ");
bot.getApi().sendMessage(message->chat->id, Return_Quote + "\n");
bot.getApi().sendMessage(message->chat->id, "Was the quote useful for you?");
flag = 2;
return;
}
}
//Feedback Chat
if (flag == 2) {
if (check_yes(message->text)) {
bot.getApi().sendMessage(message->chat->id,
"That's great! Would you like to store the quote in your list of favourites?");
flag = 3;
return;
} else if (check_no(message->text)) {
bot.getApi().sendMessage(message->chat->id, "Oh no. Why so?", false, 0, choice, "Markdown");
return;
} else
bot.getApi().sendMessage(message->chat->id,"Well that's confusing... :0 \nHelp me out here and key in a simple 'yes' or 'no' please.");
}
if (flag == 3) {
if (check_yes(message->text)) {
favourites.push_back(Return_Quote);
std::cout << Return_Quote << std::endl;
bot.getApi().sendMessage(message->chat->id, "Okay stored! ;)\nYou can view your list of favourites by typing in the command '/favourites'.\n"
"In the meantime, feel free to tell me anything else that's troubling you.");
flag = 1;
return;
} else if (check_no(message->text)) {
bot.getApi().sendMessage(message->chat->id,
"Alrighty then. Feel free to let me know of any more of your worries.");
flag = 1;
return;
} else
bot.getApi().sendMessage(message->chat->id,"Well that's confusing... :0 \nHelp me out here and key in a simple 'yes' or 'no' please.");
}
});
//Capturing unexpected events
signal(SIGINT, [](int s) {
printf("SIGINT got\n");
exit(0);
});
// Receiving user inputs via long poll
try {
printf("Bot username: %s\n", bot.getApi().getMe()->username. c_str());
bot.getApi().deleteWebhook();
TgLongPoll LongPoll (bot);
int poll_on=1;
while (poll_on) {
printf("Long poll started\n");
LongPoll.start();
// Command to end polling
bot.getEvents().onCommand("end", [&poll_on](const Message::Ptr& message){ poll_on = 0; });
}
}
catch (exception& e) {
printf("error: %s\n", e.what()); }
return 0;
}
</code></pre>
<p><strong>QuoteData.hpp</strong></p>
<pre><code>#ifndef CSV_TESTING_QUOTEDATA_HPP
#define CSV_TESTING_QUOTEDATA_HPP
struct QuoteTopic{
explicit QuoteTopic (std::string const topic);
~QuoteTopic() = default;
std::string generate_quote();
std::vector<std::string> quotelist;
int match_keywords (std::string const& sentence);
std::string const Topic;
private:
std::vector<std::string> generate_quotelist(std::string const topic);
};
#endif
</code></pre>
<p><strong>QuoteData.cpp</strong></p>
<pre><code>#include <string>
#include <iostream>
#include <random>
#include <fstream>
#include <vector>
#include <utility> // std::pair
#include <stdexcept> // std::runtime_error
#include <sstream> // std::stringstream
#include "QuoteData.hpp"
#include "Functions.hpp"
//QuoteTopic Functions
QuoteTopic:: QuoteTopic(std::string const topic): Topic(topic){
quotelist = generate_quotelist(topic);
}
std::string QuoteTopic:: generate_quote() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distr(0, quotelist.size()-1);
return quotelist[distr(gen)];
}
std::vector<std::string> QuoteTopic::generate_quotelist(std::string const topic) {
std::ifstream QuotesFile("quote_database.txt", std::ios::in | std::ios::binary);
if (!QuotesFile.is_open())
throw std::runtime_error("Could not open file");
std::string line, word;
if (QuotesFile.good()) {
while (getline(QuotesFile, line, '\r')) {
std::istringstream s(line);
getline(s, word, '/');
if (word == topic) {
while (getline(s, word, '/')) {
quotelist.push_back(word);
}
break;
}
}
}
return quotelist;
}
int QuoteTopic::match_keywords(std::string const& sentence){
//storing related keywords into a temporary vector
std::ifstream KeywordsFile("topic_keywords.csv", std::ios::in | std::ios::binary);
if (!KeywordsFile.is_open())
throw std::runtime_error("Could not open file");
std::string line, key;
std::vector<std::string> keywords;
if (KeywordsFile.good()) {
while (getline(KeywordsFile, line, '\r')) {
std::istringstream s(line);
getline(s, key, ',');
if (key == Topic) {
while (getline(s, key, ',')) {
keywords.push_back(key);
}
break;
}
}
}
//counting the number of matched keywords
int count = 0;
std::string word;
std::stringstream ss(sentence);
while(ss>>word) {
//if present, removes commas from strings
word.erase(std::remove(word.begin(), word.end(), ','), word.end());
for (const auto& e : keywords) {
if (e == word)
count++;
}
}
return count;
}
</code></pre>
<p><strong>Functions.hpp</strong> (functions not in QuoteTopic struct)</p>
<pre><code>#ifndef INSPOBOT_FUNCTIONS_HPP
#define INSPOBOT_FUNCTIONS_HPP
std::vector<std::shared_ptr<QuoteTopic>> store_QuoteTopics();
int which_topic(std::string const& sentence, std::vector<std::shared_ptr<QuoteTopic>> AllTopics);
bool check_yes(std::string const& word);
bool check_no(std::string const& word);
bool compare_char (char const& a, char const& b);
bool compare_str (std::string const& a, std::string const& b);
bool operator==(std::string const& a, std::string const& b);
bool operator!=(std::string const& a, std::string const& b);
#endif
</code></pre>
<p><strong>Functions.cpp</strong></p>
<pre><code>#include <string>
#include <iostream>
#include <random>
#include <fstream>
#include <vector>
#include <utility> // std::pair
#include <stdexcept> // std::runtime_error
#include <sstream> // std::stringstream
#include <boost/algorithm/string.hpp>
#include "QuoteData.hpp"
#include "Functions.hpp"
std::vector<std::shared_ptr<QuoteTopic>> store_QuoteTopics(){
std::vector<std::shared_ptr<QuoteTopic>> AllTopics;
std::ifstream QuoteFile("quote_database.txt", std::ios::in | std::ios::binary);
if (!QuoteFile.is_open())
throw std::runtime_error("Could not open file");
std::string line, word;
if (QuoteFile.good()) {
while (getline(QuoteFile, line, '\r')) {
std::istringstream s(line);
getline(s, word, '/');
AllTopics.push_back(std::shared_ptr<QuoteTopic>(new QuoteTopic(word)));
}
}
return AllTopics;
}
int which_topic(std::string const& sentence, std::vector<std::shared_ptr<QuoteTopic>> AllTopics){
int index = -1;
int NumKeywords = 0;
for(int n=0;n<AllTopics.size();n++){
if (AllTopics[n]->match_keywords(sentence)>NumKeywords) {
index = n;
NumKeywords = AllTopics[index]->match_keywords(sentence);
}
else if ((AllTopics[n]->match_keywords(sentence)==NumKeywords)&&(NumKeywords!=0)){
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distr(1,2);
index = (distr(gen) == 1)? index : n;
NumKeywords = AllTopics[index]->match_keywords(sentence);
}
}
return index;
}
//General Use Functions
bool check_yes(std::string const& word){
std::string yes_words = "yep yes yeap sure of course indeed affirmative absolutely yup yah yeh yeet";
if (yes_words.find(word) != std::string::npos)
return true;
else{
std::string lower_word = boost::to_lower_copy(word);
std::cout << lower_word << std::endl;
return yes_words.find(lower_word) != std::string::npos;
}
}
bool check_no(std::string const& word){
std::string no_words = "no nope negative not at all nah no way naw not really absolutely not of course not";
if (no_words.find(word) != std::string::npos)
return true;
else{
std::string lower_word = boost::to_lower_copy(word);
std::cout << lower_word << std::endl;
return (no_words.find(lower_word) != std::string::npos);
}
}
bool compare_char (char const& a, char const& b){
return (a == b) || (std::toupper(a) == std::toupper(b));
}
bool compare_str (std::string const& a, std::string const& b){
return ((a.size() == b.size())&&(std::equal(a.begin(), a.end(),b.begin(), &compare_char)));
}
bool operator==(std::string const& a, std::string const& b) {
return compare_str(a, b);
}
bool operator !=(std::string const& a, std::string const& b) {
return !(compare_str(a, b));
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T09:23:28.680",
"Id": "478957",
"Score": "0",
"body": "Resist featurism!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T09:34:44.493",
"Id": "478960",
"Score": "1",
"body": "`Here's my main code without function files if you're too busy to visit the [hyperlink to the source code repository]` au contraire: [The question shall contain enough **real code** from your project for meaningful reviews](https://codereview.stackexchange.com/help/how-to-ask) - hyperlinks welcome for reference and dispensable detail."
}
] |
[
{
"body": "<p>You are right about <code>using namespace</code>. The purpose of a namespace is to allow types and functions to have the same name in two or more areas of code. Think about the class <code>configuration</code>, its quite a common name for something in code so if you and I are both writing a module for an all singing all dancing app and we both have a <code>configuration</code> class we are screwed when we come to integrate it, if we are lucky it won't compile. So this is why you have namespaces, <code>CodeGorilla::configuration</code> and <code>JessLim::configuration</code>, don't have a problem being integrated and the project succeeds and we become millionaires.\nThen someone decided to stick a <code>using namespace Bob;</code> statement at the top of the code and everything turned ugly, because no one knows who's configuration was who's.</p>\n<p>I think if you are going to use namespaces then there is almost never a reason to use a <code>using namespace</code> statement. There are always exceptions to any rule, but std is never one of them :)</p>\n<p>I am sorry to say this so bluntly but <strong>IN MY OPINION</strong> your code is ugly. Its one monolithic function, it takes 8 scrolls to get to the bottom of it and sorry but my finger doesn't need that much exercise.</p>\n<p>What can we do about it?\nFirstly you have these large strings dotted through the code. If you extracted each of those out into a constant that would make the code look better (assuming you named the constants nicely). Also that bit of refactoring allows you to make this multilingual.</p>\n<p>Functions should not be ~200 lines I normally stick to less than a screen full which is about 40 lines. To be honest most of the functions I have written in the last few years and been 10 lines or less. You have to balance the increased readability from having short functions with the decreased readability from having to jump between functions. There is no one size fits all answer.</p>\n<p>Lambda functions are great, but sometime they get to big and should be refactored into a separate function. <code>bot.getEvents().onCallbackQuery()</code> and <code>bot.getEvents().onAnyMessage()</code> could both do with being separated out.</p>\n<p>Enums are your friend because they document the code without you having to write a comment. <code>flag==1</code> and <code>flag==2</code> are not very self explanatory, but <code>flag == eMainChat</code> and <code>flag == eFeedbackChat</code> are much more instantly recognisable.</p>\n<p>Braces or { and } are really good at making code readable. Everyone has there own preference and I'm old school. You have written C++ and then formatted it as JavaScript, personally I go with an open and closing brace should almost always be on their own line, it just makes the code a little neater. Also always use braces, even on a single line. Again its just consistent and nice. When the code always looks the same then you don't read the code you just see it, I'm sorry that it's a bit of an airy fairy statement, but I can't think of a better way to describe it. You don't want to waste you time reading code you want to find the bug, fix it and move on.</p>\n<p>You need to make sure all your variables are initialised. Compilers do this in debug builds but not normally in release builds. Classes are normally initialised in the constructor so <code>std::string Return_Quote;</code> is fine, but <code>int TopicIndex;</code> is not fine.</p>\n<p>You also need to ensure that any memory you allocate is deallocated.<br />\nInlineKeyboardButton::Ptr KeyboardButton(new InlineKeyboardButton); is one occurrence but there are more.</p>\n<p>Try and be consistent with your variable and function naming convention. Some variables are in lower case, some are capitalised, etc. And never, ever get lazy and use a single letter as a variable (n I am looking at you), It just means you have to add an extra comment where you could just have said <code>topicIndex</code>.</p>\n<p>Oh and like the others said if you put all the information in the question people are more likely to answer it. I haven't followed your link, god knows what is there it could be a virus it could be wonderful code. Like I said my finger doesn't need more exercise and that extra click could just push it over the edge :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T00:27:13.430",
"Id": "479035",
"Score": "0",
"body": "`there is almost never a reason to use a using namespace statement.` But like you said there is always the exception. **The place to use them** is for your own code in your own compilation units. They make writing your code easier. But you should have a `using namespace` for a third party header. For third-party code if it is too lang winded use a namespace alias: `namespace BMP = boost::MetaProgramming::Library;` Now prefix all the code from that namespace with `BMP`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T21:06:43.473",
"Id": "244005",
"ParentId": "243961",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T01:41:13.433",
"Id": "243961",
"Score": "3",
"Tags": [
"c++",
"object-oriented",
"c++14",
"telegram"
],
"Title": "Simple C++ Telegram Bot"
}
|
243961
|
<h1>Python3 - Recursive XML Files to Large Text File</h1>
<p>I have a recursive function that looks through a directory (<em>there are 6000+ files</em>).</p>
<p>For each <code>XML</code> file found - the XML is converted to a string and appended to an array.</p>
<p>At the end of the recursion - All these arrays are joined to return a (very) large string.</p>
<p>The error I am getting is <code>MemoryError</code> - <em>How can I optimise my code?</em></p>
<pre><code>import os
import xml.etree.ElementTree as ET
# Cycle through a directory and concat files together - recursive dive.
# NOTE:
# Have a folder called 'PLC 2360' in the immediate directory.
# The output is a huge text file
path = 'PLC 2360'
big_text = []
def big_file(path):
try:
for i in next(os.walk(path))[2]: # For each XML file read and convert to string
xml = ET.parse(path + '/' + i).getroot()
big_text.append(ET.tostring(xml, encoding='unicode')) # Append string of XML
except:
print('Error on', path)
if next(os.walk(path))[1]: # If folders exist - cycle through
for i in next(os.walk(path))[1]:
big_file(path + '/' + i) # Enter next recursion layer
return ''.join(str(i) for i in big_text) # Return one big string
lis = big_file(path)
print(len(lis))
print(lis[:500])
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T07:07:57.977",
"Id": "478942",
"Score": "1",
"body": "\"and appended to an array\" Why? If you want to append to a file, append to a file. What's the array for? There are only files being read by your code, not written. I don't see a target text file anywhere, so it looks like the code as written does not produce the required result yet. Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T07:11:09.363",
"Id": "478943",
"Score": "1",
"body": "I'm assuming you're doing this to create plain-text exports of PLC tag data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T08:14:57.097",
"Id": "478946",
"Score": "0",
"body": "@Mast - I am appending to an array currently in case I need to do some specific preprocessing of certain files - my output is currently a string from the function to which I can write to a file later. Yes, PLC tags, good spot - I am also considering using Threading to shoot off threads but not sure how well that will work with recursion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T08:29:05.623",
"Id": "478948",
"Score": "1",
"body": "Threading may only make your problem worse at this point, since you'll run out of memory even faster. Keeping the data in memory because you may need to do something sounds like a good reason, but it's really not feasible with the amount of data you're handling. Is keeping one file in memory at once an acceptable alternative? I can't help but feel there must be more code than you're showing. On Code Review, details matter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T08:55:02.417",
"Id": "478950",
"Score": "0",
"body": "@Mast Appreciate the informative feedback - I think that is a good idea and I will try writing to a file as I go. Would there be options for compression (dynamic as the function is running)? Or are there any tensor (perhaps not the correct term) libraries/options for running computations on the GPU? I'm fresh from SO, I'll remember that advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T09:08:11.550",
"Id": "478953",
"Score": "1",
"body": "There are options for compressing, but as long as you have the storage space, it does not matter initially. Your tag files are not going to fill your entire memory if you load them one-by-one, they're not big enough for that. The problem is you're trying to keep them all in memory at once. That's not going to work if you have thousands of files."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T09:23:46.807",
"Id": "478958",
"Score": "0",
"body": "@Mast Makes perfect sense - much appreciated for your knowledge and advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T10:12:25.017",
"Id": "478963",
"Score": "0",
"body": "is the order of the iteration important?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T10:54:37.487",
"Id": "478967",
"Score": "0",
"body": "@MaartenFabré Not important in my case"
}
] |
[
{
"body": "<h1>functions</h1>\n<p>Your script does a few things</p>\n<ul>\n<li>iterate over the files</li>\n<li>recursively iterate over the subdirectories</li>\n<li>parse the files</li>\n<li>concatenate the results</li>\n</ul>\n<p>Better would be to separate those in different functions.</p>\n<p>The extra advantages is that you can test these functions separately, you can document them with a docstring, and add typing information</p>\n<h1>comments</h1>\n<p>You comment what the code does. Python is luckily so expressive that almost anyone can understand what a particular line does. what is more difficult is the why you do certain steps, and why you do them in a certain order. This is what should be commented</p>\n<h1>global variables</h1>\n<p>Your <code>big_file</code> method changes the global state of the program. That makes it more difficult to reason about, and also makes it difficult if you want to use this methon on 2 separate directories. Here you append to <code>big_text</code>. If you want to keep it like this, I would pass it on as a function parameter, instead of a global variable</p>\n<pre><code>def big_file(path, big_text = None):\n if big_text is None:\n big_text = []\n \n ...\n big_file(path + '/' + i, big_text=big_text) \n</code></pre>\n<h1><code>pathlib.Path</code></h1>\n<p>Most file operations are simpler when using the <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib</code></a> module. It will be a lot more robust than manually concatenating paths like in <code>path + '/' + i</code></p>\n<h1>error handling</h1>\n<p>You have a <code>try-except</code> block with a bare except. Better here would be to catch the errors you expect specifically and handle those, and let other, unexpected error bubble up. <code>Fail hard, fail fast</code>, instead of covering up bugs can help you write more stable and correct software</p>\n<h1>logging</h1>\n<p>Instead of using <code>print</code>, you can use the <code>logging</code> module. That way you can make a distinction between different levels of importance, and filter some out if needed</p>\n<h1>generators</h1>\n<p>To prevent a <code>MemoryError</code> you can use generators. these are special functions that do their work piece by piece, and can work without keeping the whole structure in memory</p>\n<p>You can have 1 generator generate the files</p>\n<pre><code>def iterate_files(path: Path) -> typing.Iterator[Path]:\n """Recursively iterates over `path`, yielding all the correct files"""\n for file in path.glob("*"):\n if file.is_dir():\n yield from iterate_files(file)\n else:\n # or a check that the file has a certain suffix\n yield file\n</code></pre>\n<p>Then you feed this iterator to the parser generator</p>\n<pre><code>def parse_files(files: typing.Iterator[Path]) -> typing.Iterator[str]:\n """Parse the xml files."""\n for file in files:\n try:\n xml = ET.parse(path + '/' + i).getroot()\n yield ET.tostring(xml, encoding='unicode')\n except <stricter exception>:\n logging.warn(f"error in {file}")\n raise\n</code></pre>\n<p>In the last except, you can have different <code>except</code> blocks with different result</p>\n<p>You can then feed this to another generator which writes it to a file:</p>\n<pre><code>def write_to_file(\n text_iterator: Typing.Iterable[str], output_filehandle: typing.TextIO\n) -> Typing.Iterable[str]:\n for chunk in text_iterator:\n output_filehandle.write(chunk)\n yield chunk\n</code></pre>\n<h1>putting it together</h1>\n<pre><code>if __name__ == "__main__":\n path = Path("PLC 2360")\n files = iterate_files(path)\n parsed_filed = parse_files(files)\n \n with Path(<output_path>).open("w") as output_filehandle:\n parsed_filed_after_writing = write_to_file(\n text_iterator=parse_files, output_filehandle=output_filehandle\n )\n ...\n</code></pre>\n<p>In that last part, I've opened the file in the main part of the script, taking into account the principles of <a href=\"https://rhodesmill.org/brandon/talks/#clean-architecture-python\" rel=\"nofollow noreferrer\">clean</a> <a href=\"https://rhodesmill.org/brandon/talks/#hoist\" rel=\"nofollow noreferrer\">architecture</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T11:03:46.650",
"Id": "478968",
"Score": "0",
"body": "*Very Much Appreciated* - These are all valuable and incredibly neat points - I hope to develop my programming structure skills to this kind of standard - Awesome! Learned tonnes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T11:49:23.907",
"Id": "478972",
"Score": "1",
"body": "You don't have to accept straight away. You can wait a bit and give other people some time give their feedback as well"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T11:51:46.707",
"Id": "478973",
"Score": "0",
"body": "I'll do that in future, thanks"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T10:56:12.220",
"Id": "243973",
"ParentId": "243963",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T06:45:52.580",
"Id": "243963",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"recursion"
],
"Title": "What is the most optimal way to concat XML files as one large string/text file?"
}
|
243963
|
<p>I am learning about clean and maintainable code. I heard that functions should be no more than 20 lines long (<em>preferably 5 - 10 lines</em>). I have come across this Bob Martin quote where he said:</p>
<blockquote>
<p>“The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that”.</p>
</blockquote>
<p>And also this one</p>
<blockquote>
<p>“Functions should do one thing. They should do it well. They should do it only”.</p>
</blockquote>
<p>This all sounds great in theory but when a new programmer starts out - their code looks nothing like the above. And I'm not sure how to start to refactor this function to be small and do only one thing.</p>
<p>This function is taken from my Cash Register app that I'm making using Vue.js + Laravel. When a user clicks on the green "Pay" button - there are many things that need to happen so how can my function still be small?</p>
<p><code><button @click="processPayment('cash')">Pay</button></code></p>
<ol>
<li>Check if a user has ordered a regular sandwich and show a notification to offer a special sandwitch.</li>
<li>Give some "special" tables a discount</li>
<li>Validate if there are any items selected</li>
<li>If there has been a discount, check if there is also a comment - else show an error</li>
<li>Deal with Food Delivery services (special treatment)</li>
<li>Call the Pay backend API</li>
<li>Refresh all the data</li>
<li>Call the Print Receipt API</li>
<li>Start Table Timers (so we know how long the customer has been waiting for their order)</li>
<li>Play the new order sound (ding!)</li>
<li>Reset everything at the end</li>
</ol>
<p>Whoa! That's a lot of things going on there when the <code>Pay</code> button is pressed. How can we possibly make this function do only one thing and be short? I'm confused.</p>
<p>Here is my long method:</p>
<pre><code>async processPayment(payment_method, options = null)
{
this.checkIfOrderContainsRegularSandwitch()
if (store.orderContainsRegularSandwitch && !store.isConfirmedOrder) {
store.showOrderConfirmationModal = true
return
}
// comment for special tables
if (this.specialTableSelected()) {
store.orderComment = store.pickedTable.description
}
/**
* discounts for special tables
*/
if (this.specialTableSelected() && payment_method != 'Uber' && payment_method != 'DoorDash') {
Order.applySpecialTableDiscounts()
}
if (!store.orderedItems.length) {
CashRegister.reset()
return
}
if (store.order.discount > 0 && !store.orderComment) {
if (payment_method != 'Uber' && payment_method != 'DoorDash' ) {
store.infoModalTitle = this.lang('order_with_discount')
store.infoModalMessage = this.lang('order_with_discount_msg')
store.showInfoModal = true
return;
}
}
if (payment_method == 'Uber') {
store.isUber = true
store.orderComment = 'Uber'
}
if (payment_method == 'DoorDash') {
store.isDoorDash = true
store.orderComment = 'DoorDash'
}
// 30% discount for Uber or DoorDash
if (payment_method == 'Uber' || payment_method == 'DoorDash') {
store.orderDiscount = 30
store.orderDiscountType = '%'
Order.applyTotalDiscount()
Order.calculateTotals()
}
if (!store.order.isPaid)
{
store.isPaymentLoading = true
// Save the order
let order_id = await OrderApi.pay({
order: store.order,
orderedItems: store.orderedItems,
payment_method: payment_method,
table: store.pickedTable.description,
table_id: store.pickedTable.id,
order_mode: store.orderMode,
order_comment: store.orderComment,
takeaway_time : store.takeawayTime,
is_takeaway: (store.isTakeaway) ? 1 : 0,
ml_delivery_phone: store.MLDeliveryPhone,
is_ml_delivery: (store.isMLDelivery) ? 1 : 0,
applied_discount: store.orderDiscount,
applied_discount_type: store.orderDiscountType,
has_coupon: store.hasCoupon,
pay_cash: options?.pay_cash ?? 0,
pay_card: options?.pay_card ?? 0,
})
order_id = order_id.data
store.isPaymentLoading = false
// Refresh order history
OrderHistory.getTotalOrderHistory({
date: moment().format('YYYY-MM-DD'),
})
// Refresh tables
Data.getTables().then(({ data }) => {
store.tables = data
})
// Refresh popular today
Data.getPopularToday().then(({ data }) => {
store.popularToday = data
})
// Print receipt
if (store.shouldPrint) {
await this.printReceipt({})
}
// Refresh Bar Items
Data.getBarItems().then(({ data }) => {
store.barItems = data
if (store.barItems.length) {
store.isBarCarouselMinimized = false
}
})
if (payment_method != 'Uber' && payment_method != 'DoorDash') {
if (store.order.payment_method != 'Pay later') {
if (store.settings.settings?.table_timers == true) {
this.startTableTimer(store.pickedTable.id, order_id, 0)
}
}
}
if (store.settings.settings.new_order_notification_sound) {
this.playNewOrderSound(store.orderedItems)
}
CashRegister.reset(order_id)
}
},
<span class="math-container">````</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T08:32:49.263",
"Id": "478949",
"Score": "1",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T09:14:22.763",
"Id": "478954",
"Score": "0",
"body": "The core of your problem is that the name of the function is wrong. You're not processing a payment, you're processing an order. Part of that order is payment. You put way too much logic into one function. Please provide the `CashRegister`, `Order`, `OrderHistory` and other relevant classes in your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T09:15:24.633",
"Id": "478955",
"Score": "0",
"body": "By what I'm seeing so far, I'd suggest you leave this project alone for a while and practice first with cutting-up smaller projects into functions. Refactoring this entire project is going to take a while."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T09:26:49.703",
"Id": "478959",
"Score": "0",
"body": "Looks like there could be one `handleClick` function that contains 11 calls to other functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-21T16:07:01.593",
"Id": "482843",
"Score": "0",
"body": "You've listed 11 things the \"`pay()`\" function should do - Great! \nWrite 11 functions to do just that, all called from within the \"`pay()`\" function, and use descriptive names = compartmentalization, \"easier\" to figure out where a problem might be, and more! :)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T07:03:53.430",
"Id": "243964",
"Score": "2",
"Tags": [
"javascript",
"performance",
"design-patterns"
],
"Title": "How to split and refactor a large function so it would do only one thing?"
}
|
243964
|
<p>I've written the following custom event system module and I'm planning to use it in production in the future. Before I do that, I'd like to ask for general suggestions on how to improve it. Thanks a lot.</p>
<pre><code>const event = (function() {
let registry = {};
function on(event, callback) {
if(!registry[event]) registry[event] = [];
registry[event].push(callback);
}
function once(event, callback) {
if(!registry[event]) registry[event] = [];
registry[event].push(function(message) {
callback(message);
off(event, callback);
});
}
function off(event, callback) {
if(registry[event]) {
registry[event].splice(registry[event].indexOf(callback), 1);
if(!registry[event].length) delete registry[event];
}
}
function emit(event, message) {
if(registry[event]) {
registry[event].forEach(callback => {
callback(message);
});
}
}
function getListeners(event) {
return registry[event] ? registry[event] : null;
}
return {
on: on,
once: once,
off: off,
emit: emit,
getListeners: getListeners
}
})();
export { event };
</code></pre>
<p><strong>Usage:</strong></p>
<p>Add event listener:</p>
<pre><code>event.on('someEvent', someEventhandler);
</code></pre>
<p>Remove event listener:</p>
<pre><code>event.off('someEvent', someEventhandler);
</code></pre>
<p>Add event listener and remove it after first use:</p>
<pre><code>event.once('someEvent', someEventhandler);
</code></pre>
<p>Fire the event:</p>
<pre><code>event.emit('someEvent');
</code></pre>
<p>Get all eventhandlers for an event:</p>
<pre><code>event.getListeners('someEvent');
</code></pre>
|
[] |
[
{
"body": "<p>While there are examples of how the code can be used, it would be helpful for anyone reading the code (including your future self) to have a comment block above each method to describe the purpose, parameters, return value and any possible error that could be thrown.</p>\n<hr />\n<p>The question is tagged with <a href=\"/questions/tagged/performance\" class=\"post-tag\" title=\"show questions tagged 'performance'\" rel=\"tag\">performance</a>- are you trying to optimize the code for speed? If so, it would be better to use a <code>for</code> loop instead of functional methods that use iterators - e.g. <code>Array.prototype.forEach()</code>, <code>Array.prototype.indexOf()</code>.</p>\n<hr />\n<p>Has the code been tested? Are there any unit tests for the module? If not, it would be wise to create tests to cover all aspects of the code.</p>\n<p>Correct me if I am wrong but looking at how the <code>off()</code> method is implemented my presumption is that the call from <code>once()</code> will not actually remove any callback, given that a wrapped function is registered instead of the callback parameter.</p>\n<hr />\n<p>There appears to be no validation that the <code>callback</code> is a function. This could lead to an error if some other type is passed in that parameter.</p>\n<hr />\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Property_definitions\" rel=\"nofollow noreferrer\">The shorthand property definition notation</a> can be used to simplify the following lines:</p>\n<blockquote>\n<pre><code> return {\n on: on,\n once: once,\n off: off,\n emit: emit,\n getListeners: getListeners\n }\n</code></pre>\n</blockquote>\n<p>To this:</p>\n<pre><code>return {\n on,\n once,\n off,\n emit,\n getListeners\n }\n</code></pre>\n<hr />\n<p>You may be interested in reading the responses I received on similar code I wrote- see <a href=\"https://codereview.stackexchange.com/q/201326/120114\">Event emitter npm module</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T11:48:39.060",
"Id": "248311",
"ParentId": "243967",
"Score": "3"
}
},
{
"body": "<p><code>getListeners</code> should not return <code>null</code> but rather an empty array <code>[]</code>. Usually this is easier to handle and less error prone for clients. And so you need not delete fields with empty arrays in function <code>off</code>.</p>\n<p>Function <code>once</code> can be defined by using function <code>on</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T21:05:03.303",
"Id": "248386",
"ParentId": "243967",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248311",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T07:23:44.630",
"Id": "243967",
"Score": "6",
"Tags": [
"javascript",
"performance",
"ecmascript-6"
],
"Title": "JS Custom Event System"
}
|
243967
|
<p>I have the code below, which works successfully, and is used to parse, clean log files (very large in size) and output into smaller sized files. This would take about 12-14 mins to process 1 GB worth of logs (on my laptop). Can this be made faster? Could Dask or parallelism or asyncio or another help speed this up?</p>
<p>I am new to python and pandas, and I have googled around, but am totally confused and cant seem to adopt any of the examples I saw.</p>
<pre><code>import os
import pandas as pd
asciireg = "[^\x00-\x7F]+"
emailreg = "^\w+(?:[-+.']\w+)*@\w+(?:[-.]\w+)*\.\w+(?:[-.]\w+)*$"
for root, dirs, files in os.walk('.', topdown=True):
for file in files:
try:
for df in pd.read_csv(file, sep='\n', header=None, engine='python', quoting=3, chunksize=1200000):
df = df[0].str.strip(' \t"').str.split('[,|;: \t]+', 1, expand=True).rename(columns={0: 'email', 1: 'data'})
mask = (df.email.str.contains(emailreg, regex=True, na=False)) & (~df.data.str.contains(asciireg, regex=True, na=False))
df2 = df[~mask].copy()
df = df[mask].copy()
df2[['email', 'data']].to_csv("errorfile", sep=':', index=False, header=False, mode='a', compression='gzip')
del df2
del mask
for x in "abcdefghijklmnopqrstuvwxyz0123456789":
df2 = df[df.email.str.startswith(x)]
if (df.email.size > 0):
df2[['email', 'data']].to_csv(x, sep=':', index=False, header=False, mode='a')
except Exception as e:
print ("Error: ", file)
print(str(e))
else:
os.remove(file)
</code></pre>
<p><strong>Sample log file</strong></p>
<pre><code>"email1@foo.com:datahere2
email2@foo.com:datahere2
email3@foo.com datahere2
email5@foo.com;dtat'ah'ere2
wrongemailfoo.com
email3@foo.com:datahere2
</code></pre>
<p><strong>Expected Output</strong></p>
<blockquote>
<pre><code>$ cat e
</code></pre>
</blockquote>
<pre><code>email1@foo.com:datahere2
email2@foo.com:datahere2
email3@foo.com:datahere2
email5@foo.com:dtat'ah'ere2
email3@foo.com:datahere2
</code></pre>
<blockquote>
<pre><code>$ cat errorfile
</code></pre>
</blockquote>
<pre><code>wrongemailfoo.com
</code></pre>
|
[] |
[
{
"body": "<p>I think there is quite a lot that could be improved on in your approach.\nMy main piece of advice is to try and process each line in the data only once, since each line is independent you should be able to do this.</p>\n<p>I'm not too familiar with pandas but it seems like there are two main areas of concern.</p>\n<ol>\n<li>The section where you clean up the data and filter out all the bad emails, you create a mask by executing two regexs on each line and then read through and make copies of the data frame twice using the mask. At this point you have passed over every line in the data 3 times.</li>\n</ol>\n<pre><code> df = df[0].str.strip(' \\t"').str.split('[,|;: \\t]+', 1, expand=True).rename(columns={0: 'email', 1: 'data'}) \n mask = (df.email.str.contains(emailreg, regex=True, na=False)) & (~df.data.str.contains(asciireg, regex=True, na=False))\n df2 = df[~mask].copy()\n df = df[mask].copy()\n df2[['email', 'data']].to_csv("errorfile", sep=':', index=False, header=False, mode='a', compression='gzip')\n del df2\n del mask\n</code></pre>\n<ol start=\"2\">\n<li>The second section where you breakdown each email into a different file if it is valid. you go through every line in the dataframe for every possible starting letter, and copy the result over to process again. At this point you have gone through each line in the data about 40 times.</li>\n</ol>\n<pre><code>for x in "abcdefghijklmnopqrstuvwxyz0123456789":\n df2 = df[df.email.str.startswith(x)]\n if (df.email.size > 0):\n df2[['email', 'data']].to_csv(x, sep=':', index=False, header=False, mode='a')\n</code></pre>\n<p>Running cProfile on the code, when it just has to read one file with 6 lines in it produces this: <code>336691 function calls (328148 primitive calls) in 0.974 seconds</code>. Nearly a second to just read and process 6 lines into different files is not good.</p>\n<p>Rather than taking a pandas approach I have just written a pure python script that sketches out an alternative strategy. Doing the same test with cProfile produces <code>11228 function calls (11045 primitive calls) in 0.038 seconds</code>. It might not fit your needs exactly but you could look at it for ideas about how to tweak your script.</p>\n<pre><code>import re\nimport logging\n\nEMAIL_REGEX = r"^\\w+(?:[-+.']\\w+)*@\\w+(?:[-.]\\w+)*\\.\\w+(?:[-.]\\w+)*$"\nOUTPUT_FILES = "abcdefghijklmnopqrstuvwxyz0123456789"\n\n\ndef configure_logging():\n """\n Configure a logger for each possible email start. \n """\n\n # TODO - Tweak the handlers, output formats and locations \n # to suit your needs\n\n error_handler = logging.FileHandler("error.log", mode="a")\n error_handler.setLevel(logging.ERROR)\n error_handler.setFormatter(logging.Formatter('%(message)s'))\n\n for entry in OUTPUT_FILES:\n logger = logging.getLogger(entry)\n handler = logging.FileHandler(f"{entry}.log", mode="a")\n handler.setFormatter(logging.Formatter('%(message)s'))\n handler.setLevel(logging.INFO)\n logger.addHandler(handler)\n logger.addHandler(error_handler)\n logger.setLevel(logging.INFO)\n \ndef gather_files():\n """\n Return all the log files that need to be processed.\n """\n # TODO - replace with your own logic to find files.\n return ["test_input.csv"]\n\ndef process_log_file(log_file_path):\n """\n For each line in the log file, process it once.\n """\n with open(log_file_path, "r") as log_file:\n for line in log_file:\n process_line(line)\n \ndef process_line(line):\n """\n Find the email and user from a line, test if the email is valid. Log the data\n to the appropriate place.\n """\n\n # TODO you may wish to change to logic \n # to decide if the line is valid or not.\n\n line = line.strip(' \\t"\\n')\n data = re.split(r'[,|;: \\t]+', line, maxsplit=1)\n logger = logging.getLogger(data[0][0])\n if len(data) == 2 and re.match(EMAIL_REGEX, data[0]):\n logger.info(":".join(data))\n else:\n logger.error(line)\n\ndef main():\n """\n Processes each log file in turn.\n """\n for log_file_path in gather_files():\n process_log_file(log_file_path)\n\nif __name__ == "__main__":\n configure_logging()\n main()\n\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T05:59:43.313",
"Id": "479166",
"Score": "0",
"body": "Thanks, interesting idea. And agreed that pandas is not fit for purpose. However, your code did not speed things up too much. Can this code be run in parallel ? async or similar?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T13:21:27.833",
"Id": "479204",
"Score": "0",
"body": "It would be possible to adapt it in that way, you would need to make sure that different threads don't start reading from the same files and that different threads can output to the same log file in a safe way."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T11:37:28.573",
"Id": "244035",
"ParentId": "243970",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T09:22:28.673",
"Id": "243970",
"Score": "2",
"Tags": [
"python",
"asynchronous",
"pandas"
],
"Title": "Parse and clean log files"
}
|
243970
|
<p>I wanted to create an AES encryption service which will use a custom key/iv.</p>
<p>I want 2 methods: dycrypt/encrypt byte[]</p>
<p>The code works as expected, any remarks/issues?</p>
<pre><code>public class AesGenericEncryptionService
{
private readonly byte[] m_Key;
private readonly byte[] m_IV;
public AesGenericEncryptionService(byte[] key, byte[] iv)
{
if (key == null || key.Length <= 0)
throw new ArgumentNullException(nameof(key));
if (iv == null || iv.Length <= 0)
throw new ArgumentNullException(nameof(iv));
m_Key = key;
m_IV = iv;
}
public byte[] Encrypt(byte[] data)
{
byte[] encrypted;
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Mode = CipherMode.CBC;
rijAlg.KeySize = m_Key.Length * 8;
rijAlg.Key = m_Key;
rijAlg.BlockSize = m_IV.Length * 8;
rijAlg.IV = m_IV;
using (ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV))
{
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
csEncrypt.Write(data, 0, data.Length);
csEncrypt.FlushFinalBlock();
encrypted = msEncrypt.ToArray();
}
}
}
}
return encrypted;
}
public byte[] Decrypt(byte[] cipher)
{
// Check arguments.
if (cipher == null || cipher.Length <= 0)
throw new ArgumentNullException(nameof(cipher));
byte[] dycrypted = null;
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Mode = CipherMode.CBC;
rijAlg.KeySize = m_Key.Length * 8;
rijAlg.Key = m_Key;
rijAlg.BlockSize = m_IV.Length * 8;
rijAlg.IV = m_IV;
using (ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV))
{
using (MemoryStream ms = new MemoryStream(cipher))
{
using (var cryptoStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
dycrypted = new byte[cipher.Length];
var bytesRead = cryptoStream.Read(dycrypted, 0, cipher.Length);
dycrypted = dycrypted.Take(bytesRead).ToArray();
}
}
}
}
return dycrypted;
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>ctor</strong></p>\n<p>Neither <code>key.Length</code> nor <code>iv.Length</code> can be smaller than <code>0</code> you only need to check if it is equal to <code>0</code>. But for me as a user of that class it would look strange to receive an <code>ArgumentNullException</code> if I pass e.g a key with Length == 0. I would expect an <code>ArgumentOutOfRangeException</code>.</p>\n<p>Omitting braces althougth they might be optional can lead to hidden and therfor hard to find bugs.</p>\n<p><strong>Encrypt()</strong></p>\n<ul>\n<li><p>The default <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.rijndaelmanaged.mode?view=netcore-3.1#System_Security_Cryptography_RijndaelManaged_Mode\" rel=\"nofollow noreferrer\">Mode</a> of <code>RijndaelManaged</code> is already <code>CipherMode.CBC</code> so there is no need to set it again.</p>\n</li>\n<li><p>By returning out of the most inner <code>using</code> you can remove <code>byte[] encrypted</code>.</p>\n</li>\n<li><p>By stacking the <code>using</code>'s you save some levels of indentation.</p>\n</li>\n<li><p>You can use the parameterless <code>CreateEncryptor()</code> method because you already set the <code>Key</code> and <code>IV</code>.</p>\n</li>\n<li><p>As the method is <code>public</code> you should validate its parameter.</p>\n</li>\n</ul>\n<p><strong>Decrypt()</strong></p>\n<ul>\n<li><p>The default <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.rijndaelmanaged.mode?view=netcore-3.1#System_Security_Cryptography_RijndaelManaged_Mode\" rel=\"nofollow noreferrer\">Mode</a> of <code>RijndaelManaged</code> is already <code>CipherMode.CBC</code> so there is no need to set it again.</p>\n</li>\n<li><p>By returning out of the most inner <code>using</code> you can remove <code>byte[] decrypted</code>.</p>\n</li>\n<li><p>By stacking the <code>using</code>'s you save some levels of indentation.</p>\n</li>\n<li><p>You can use the parameterless <code>CreateDecryptor()</code> method because you already set the <code>Key</code> and <code>IV</code>.</p>\n</li>\n<li><p>You shouldn't mix styles. In the <code>using</code>'s you sometimes use the concrete type and sometimes you use <code>var</code>.</p>\n</li>\n</ul>\n<p><strong>General</strong></p>\n<p>Naming things in a good way is hard. Mostly it is sufficient and just more readable to just use a classname in <code>camelCase</code> casing. If you stumble in a few months over the variable <code>rijAlg</code> you will need to ask yourself what it stands for. By naming it <code>rijndaelManaged</code> you will see at first glance what it is about.<br />\nAnother example of "bad" naming is in <code>Encrypt()</code> you name the MemoryStream <code>msEncrypt</code> but in <code>Decrypt()</code> you name it <code>ms</code> the same is true for <code>csEncrypt</code> vs <code>cryptoStream</code>.</p>\n<p>Implementing the mentioned points leads to</p>\n<pre><code>public class AesGenericEncryptionService\n{\n private readonly byte[] m_Key;\n private readonly byte[] m_IV;\n\n public AesGenericEncryptionService(byte[] key, byte[] iv)\n {\n if (key == null)\n {\n throw new ArgumentNullException(nameof(key));\n }\n else if (key.Length == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(key));\n }\n\n if (iv == null || iv.Length <= 0)\n {\n throw new ArgumentNullException(nameof(iv));\n }\n else if (iv.Length == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(iv));\n }\n\n m_Key = key;\n m_IV = iv;\n }\n\n public byte[] Encrypt(byte[] data)\n {\n if (data == null)\n {\n throw new ArgumentNullException(nameof(data));\n }\n\n using (var rijndaelManaged = new RijndaelManaged())\n {\n rijndaelManaged.KeySize = m_Key.Length * 8;\n rijndaelManaged.Key = m_Key;\n rijndaelManaged.BlockSize = m_IV.Length * 8;\n rijndaelManaged.IV = m_IV;\n\n using (var encryptor = rijndaelManaged.CreateEncryptor())\n using (var ms = new MemoryStream())\n using (var cryptoStream = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))\n {\n cryptoStream.Write(data, 0, data.Length);\n cryptoStream.FlushFinalBlock();\n\n return ms.ToArray();\n }\n }\n }\n public byte[] Decrypt(byte[] cipher)\n {\n // Check arguments.\n if (cipher == null)\n {\n throw new ArgumentNullException(nameof(cipher));\n }\n else if (cipher.Length == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(cipher));\n }\n\n using (var rijndaelManaged = new RijndaelManaged())\n {\n rijndaelManaged.KeySize = m_Key.Length * 8;\n rijndaelManaged.Key = m_Key;\n rijndaelManaged.BlockSize = m_IV.Length * 8;\n rijndaelManaged.IV = m_IV;\n\n using (var decryptor = rijndaelManaged.CreateDecryptor())\n using (var ms = new MemoryStream(cipher))\n using (var cryptoStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))\n {\n\n var dycrypted = new byte[cipher.Length];\n var bytesRead = cryptoStream.Read(dycrypted, 0, cipher.Length);\n\n return dycrypted.Take(bytesRead).ToArray();\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T07:56:08.197",
"Id": "479072",
"Score": "0",
"body": "fair enough, agree with almost all of what you wrote, thx a lot"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T06:48:59.863",
"Id": "244022",
"ParentId": "243971",
"Score": "4"
}
},
{
"body": "<pre><code>public class AesGenericEncryptionService\n</code></pre>\n<p>That's not a very good name. The AES method itself already performs "generic" encryption. I'm also not sure if you would currently name anything "generic" if it doesn't perform authenticated encryption (encryption + MAC) such as AES/GCM. See the bottom of my answer for such an implementation. If you'd use this "generic encryption" for transport mode security then you are vulnerable to plaintext / padding oracle attacks as well as undetected change of the plaintext during transit.</p>\n<pre><code>private readonly byte[] m_IV;\n</code></pre>\n<p>Storing a static IV makes this object single use. That's not something that is wrong in particular, but it is something to keep in mind. You would wonder if a single method call would not achieve the same. Key + IV reuse makes a cipher vulnerable after all.</p>\n<pre><code>rijAlg.Mode = CipherMode.CBC;\n</code></pre>\n<p>I'm glad that you are setting this explicitly, contrary to the other answer. Using defaults for cryptographic methods leads to unreadable code, where the reader has to guess which mode has been used.</p>\n<pre><code>rijAlg.KeySize = m_Key.Length * 8;\n</code></pre>\n<p>This, on the other hand, is directly the same as just assigning the key, the key size will be set automatically.</p>\n<pre><code>rijAlg.BlockSize = m_IV.Length * 8;\n</code></pre>\n<p>This is dangerous, as Rijndael accepts different block sizes, while AES doesn't. So if you allow this then you've named your class incorrectly. And again, it's not really needed. You should instead make sure that your IV is always 128 bits if you want AES.</p>\n<hr />\n<p>In general, this class is just hiding detail from <code>RijndaelManaged</code>. It does this in such a way that using the actual class is possibly a better idea (as I've found out when I wrote my own "wrapper" classes).</p>\n<p>Finally, <code>RijndaelManaged</code> is, as the name suggests, the managed version of AES, i.e. executed byte code instead of using a native implementation. In general, I'd prefer just <code>Aes.Create()</code> so you can use the hardware acceleration that the native implementation provides (on a system with AES-NI or something supported & similar anyway). It can fall back on <code>RijndaelManaged</code> where required.</p>\n<hr />\n<p>Here is a new <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.aesgcm?view=netcore-3.1\" rel=\"nofollow noreferrer\">AES / GCM implementation</a> by Microsoft. Note that it provides "one shot" encryption like your class. However, it only uses the key as field, not the nonce (which replaces the IV).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T14:10:21.843",
"Id": "247949",
"ParentId": "243971",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T09:27:44.487",
"Id": "243971",
"Score": "3",
"Tags": [
"c#",
"aes",
"encryption"
],
"Title": "C# AES Encryption/Decryption or byte[] array with a custom Key/IV"
}
|
243971
|
<p>For self learning purpose, I have created some xUnit unit test for these 2 Atm classes. At the moment, data is store in the in-memory object. This version is extended from <a href="https://codereview.stackexchange.com/questions/243921/atm-program-xunit-unit-test">previous version</a>. For brevity, I excluded <code>Withdraw</code> method and <code>ThirdPartyTransfer</code></p>
<pre><code>public class BankAccount : IBankAccount
{
public int Id { get; private set; }
public int BankAccountNo { get; private set; }
public decimal Balance { get; private set; }
public BankAccount()
{
}
public BankAccount(int BankAccountNo, decimal Balance)
{
this.BankAccountNo = BankAccountNo;
if(Balance <= 0)
{
throw new ArgumentException("Create bank account failed. Balance should be more than zero.");
}
this.Balance = Balance;
}
public void Deposit(BankTransaction bankTransaction)
{
if (bankTransaction.TransactionAmount <= 0)
{
throw new ArgumentException("Deposit failed. Transaction amount is more than account balance.");
}
this.Balance += bankTransaction.TransactionAmount;
// Insert transaction record at BankTransaction Repository class
}
public void Withdraw(BankTransaction bankTransaction)
{
if (bankTransaction.TransactionAmount <= 0)
{
throw new ArgumentException("Withdraw failed. Transaction amount is more than account balance.");
}
if (bankTransaction.TransactionAmount > this.Balance)
{
throw new ArgumentException("Withdraw failed. Transaction amount is more than account balance.");
}
this.Balance -= bankTransaction.TransactionAmount;
// Insert transaction record at BankTransaction Repository class
}
}
public class BankTransaction
{
public int Id { get; set; }
public decimal TransactionAmount { get; set; }
public TransactionTypeEnum TransactionType { get; set; }
public int BankAccountId { get; set; }
public BankTransaction(decimal TransactionAmount)
{
this.TransactionAmount = TransactionAmount;
}
}
public enum TransactionTypeEnum
{
Deposit, Withdraw, ThirdPartyTransfer
}
public class BankTransactionRepository : IBankTransactionRepository
{
// Mock DB
public List<BankTransaction> bankTransactions { get; private set; }
public BankTransactionRepository()
{
bankTransactions = new List<BankTransaction>();
}
public void InsertTransaction(BankTransaction bankTransaction)
{
bankTransactions.Add(bankTransaction);
}
public List<BankTransaction> SearchTransactionByDates(DateTime? startDate, DateTime? endDate)
{
if((startDate == null && endDate != null)
|| (startDate != null && endDate == null))
{
throw new ArgumentNullException("Start date or end date should not be null");
}
if (startDate > endDate)
{
throw new ArgumentException("Start date should not be greater than end date");
}
// If both also null, return all.
// todo: add LINQ to filter start and end date before return
return bankTransactions;
}
}
</code></pre>
<p>And here are my xUnit unit test methods and tiny bit of Fluent Assertions.</p>
<pre><code>public class BankAccountTest
{
private BankAccount _bankAccount;
public BankAccountTest()
{
_bankAccount = new BankAccount();
}
[Theory, MemberData(nameof(BankAccountConstructorShouldPass_Data))]
public void BankAccountConstructorShouldPass(BankAccount account, BankAccount accountExpected)
{
// Act
_bankAccount = new BankAccount(account.BankAccountNo, account.Balance);
// Assert
//Assert.True(accountExpected.Equals(_bankAccount));
// Doesn't work due to object needs to be serialized first before compare.
// Fluent Assertions
accountExpected.Should().BeEquivalentTo(_bankAccount);
// Default (Without Fluent Assertions)
Assert.Equal(accountExpected.Balance, _bankAccount.Balance);
}
[Fact]
public void BankAccountConstructorInvalidBalanceShouldFail()
{
// Act
var bankAccountNo = new Random().Next();
var balance = -1;
BankAccount TestCode() => new BankAccount(bankAccountNo, balance);
// Assert
var exception = Assert.Throws<ArgumentException>(TestCode);
Assert.StartsWith("Create bank account failed. Balance should be more than zero.", exception.Message);
}
#region "TheoryData"
public static TheoryData<BankAccount, BankAccount> BankAccountConstructorShouldPass_Data()
{
return new TheoryData<BankAccount, BankAccount>
{
{
new BankAccount(123, 250.00M),
new BankAccount(123, 250.00M)
},
{
new BankAccount(321, 150.50M),
new BankAccount(321, 150.50M)
}
};
}
public static TheoryData<BankAccount, BankTransaction, BankAccount> DepositShouldPass_Data()
{
return new TheoryData<BankAccount, BankTransaction, BankAccount>
{
{
new BankAccount(123, 250.00M),
new BankTransaction(50.00M),
new BankAccount(123, 300.00M)
},
{
new BankAccount(321, 150.50M),
new BankTransaction(10.50M),
new BankAccount(321, 160.00M)
}
};
}
#endregion
}
public class BankTransactionsTest
{
private BankTransactionRepository _bankTransaction;
public BankTransactionsTest()
{
_bankTransaction = new BankTransactionRepository();
}
// Arrange
[Theory, MemberData(nameof(InsertTransaction_InsertShouldPass_Data))]
public void InsertTransaction_InsertShouldPass(BankTransaction trans, List<BankTransaction> expected)
{
// Act
_bankTransaction.InsertTransaction(trans);
// Assert
Assert.Equal(expected.Count, _bankTransaction.bankTransactions.Count);
// Fluent Assertions to check if trans is in 'expected' list.
// todo: got issue here.
//expected.Should().Contain(trans);
}
// Arrange
[Theory, MemberData(nameof(SearchTransactionByDates_NullDatesShouldFail_Data))]
public void SearchTransactionByDates_NullDatesShouldFail(DateTime? startDate, DateTime? endDate)
{
Assert.Throws<ArgumentNullException>(() =>
_bankTransaction.SearchTransactionByDates(startDate, endDate));
}
// Arrange
[Theory, MemberData(nameof(SearchTransactionByDates_StartDateGreaterThanEndDateShouldFail_Data))]
public void SearchTransactionByDates_StartDateGreaterThanEndDateShouldFail(DateTime? startDate, DateTime? endDate)
{
Assert.Throws<ArgumentNullException>(() =>
_bankTransaction.SearchTransactionByDates(startDate, endDate));
}
public static TheoryData<BankTransaction, List<BankTransaction>>
InsertTransaction_InsertShouldPass_Data()
{
return new TheoryData<BankTransaction, List<BankTransaction>>
{
{
new BankTransaction(200.00M),
new List<BankTransaction>(){new BankTransaction(200.00M)}
},
{
new BankTransaction(50.50M),
new List<BankTransaction>(){new BankTransaction(50.50M)}
},
};
}
public static TheoryData<DateTime?, DateTime?>
SearchTransactionByDates_NullDatesShouldFail_Data()
{
return new TheoryData<DateTime?, DateTime?>
{
{ null, new DateTime(2020,06,09) },
{ new DateTime(2020,06,09), null },
};
}
public static TheoryData<DateTime?, DateTime?>
SearchTransactionByDates_StartDateGreaterThanEndDateShouldFail_Data()
{
return new TheoryData<DateTime?, DateTime?>
{
{ new DateTime(2020,06,09), new DateTime(2020,06,08) }
};
}
}
</code></pre>
<p>Any comments of the code structure, coding style and best practices?</p>
|
[] |
[
{
"body": "<p>This is a decent improvement over your first posting. Let's start off with some things you are doing right.</p>\n<ul>\n<li>Your use of <code>Decimal</code> is correct. Many first attempts will incorrectly use <code>double</code>.</li>\n<li>Nice indentation.</li>\n<li>Most names are fairly good. Whereas many will over-abbreviate, you tend to make the names too long.</li>\n</ul>\n<p>Let's think of how an ATM should work. A customer inserts a card, inputs a PIN, and at that instant the ATM knows who the customer is and what account(s) belong to that customer. I note that your <code>BankAccount</code> class lacks any customer info. I bring it up as food for thought, but will (like you) ignore it for now.</p>\n<p>I don't see where <code>BankAccount.ID</code> is used. I wouldn't recommend getting rid of it, but rather trying to integrate it. In real life, I would expect banking info to be stored in a SQL database, and most likely it a bank account record would have a GUID as the ID. That record would include the account no, which unlike the GUID could change albeit very rarely, and a customer GUID.</p>\n<p>I would not expect to see a public parameter-less constructor for <code>BankAccount</code>.</p>\n<p>Purists would say you should not throw an exception in a constructor. I find it acceptable in limited cases. An alternative would be to make the constructor's <code>private</code> and have a public static <code>Create</code> method. Before we get to that, let's address 2 other points:</p>\n<ol>\n<li>Parameter names should begin with a lowercase letter.</li>\n<li>You should omit <code>this</code>.</li>\n</ol>\n<p>I also think property <code>BankAccountNo</code> is too wordy. It should be <code>AccountNo</code>.</p>\n<pre><code>private BankAccount(int accountNo, decimal balance)\n{\n AccountNo = accountNo;\n Balance = balance;\n}\n\npublic static BankAccount Create(int accountNo, decimal balance)\n{\n if(balance <= 0)\n {\n throw new ArgumentException("Create bank account failed. Balance should be more than zero.");\n }\n return new BankAccount(accountNo, balance);\n}\n</code></pre>\n<p>You have private setters for some properties. You should identify which of those properties should not change and make them read-only. Off the top, it would be the unused <code>ID</code> and <code>AccountNo</code>:</p>\n<pre><code>public int ID { get; }\npublic int AccountNo { get; }\n</code></pre>\n<p>This means they can only be assigned during initialization/construction. Couple this thought to using a static Create method, I trust you can envision many other such methods. Maybe you want the Create to read info from SQL. Or if you were given a customer ID, then you would fetch all accounts for that customer.</p>\n<p><code>TransactionTypeEnum</code> is too long of a name. Tacking <code>Enum</code> on the end is no better than prefixing it on the start. It should be <code>TransactionType</code>.</p>\n<p>The <code>BankTransaction</code> could also employ a static create. I've already covered this, so let's consider another alternative. Rather than throw an exception on a negative transaction, you could have a <code>bool IsValid</code> property. Something similar to:</p>\n<pre><code>public class BankTransaction\n{\n public int Id { get; set; }\n public decimal Amount { get; set; }\n public TransactionType TransactionType { get; set; }\n public bool IsValid => Amount <= 0;\n\n public BankTransaction(decimal amount)\n {\n Amount = amount;\n }\n}\n</code></pre>\n<p>[Sorry. Running out of time and must get back to my job.]</p>\n<p>My last remarks are for you to consider IF and HOW you should expose things to others. Making it read-only is one way. For example, in <code>BankTransactionRepository</code> the <code>bankTransactions</code> is a List. Things to correct:</p>\n<p>The property name should begin with an uppercase, so <code>BankTransactions</code>.\nIt should either be an <code>IList<BankTransaction></code> or most likely should be an <code>IReadOnlyList<BankTransaction></code>.</p>\n<p>Sorry. Gotto go.</p>\n<p><strong>UPDATE READ ONLY LISTS</strong></p>\n<p>In the comments you say you cannot use a read-only list. I disagree. What I want to walk away with is that you may have objects internal to a class that allow certain things, but what you expose publicly to others should be more restrictive. This is particular true with something as sensitive as bank accounts.</p>\n<p>With just a small change, you can have it both ways:</p>\n<pre><code>public class BankTransactionRepository : IBankTransactionRepository\n{\n // Mock DB\n private List<BankTransaction> _transactions = new List<BankTransaction>();\n public IReadOnlyList<BankTransaction> BankTransactions => _transactions;\n\n public BankTransactionRepository()\n {\n _transactions = new List<BankTransaction>();\n }\n\n public void InsertTransaction(BankTransaction bankTransaction)\n {\n _transactions.Add(bankTransaction);\n }\n\n // more code \n\n}\n</code></pre>\n<p>Within the class, you would be interacting with object <code>_transactions</code>. But publicly you restrict what others can do with those transactions. The important thing is not the specific code, but rather the reasoning of why you want to do this.</p>\n<p>Also, while I appreciate the speedy upvote from yesterday, I would suggest you not be too quick to accept an answer. Give it a day to see if others would chime in.</p>\n<p><strong>UPDATE #2 WHY A PRIVATE SETTER IS USELESS</strong></p>\n<p>OP commented asked why not use a private setter on a list? The answer is because while someone cannot change the reference to the overall list, they can still change individual items.</p>\n<p>Example code:</p>\n<p>A very simple User class</p>\n<pre><code>public class User\n{\n // Intentionally a very simplified DTO class\n public string Name { get; set; }\n public bool IsAdmin { get; set; }\n}\n</code></pre>\n<p>Some class that works with some users. Note no user is an Admin.</p>\n<pre><code>public class SomeClassWithUsers\n{\n public List<User> UserList1 { get; private set; }\n\n private List<User> _users = new List<User>();\n public IReadOnlyList<User> UserList2 => _users;\n\n public static SomeClassWithUsers CreateSample()\n {\n var x = new SomeClassWithUsers();\n x.CreateSampleUsers();\n return x;\n }\n\n public void CreateSampleUsers()\n {\n _users = new List<User>()\n {\n new User() {Name = "Alice", IsAdmin = false },\n new User() {Name = "Bob", IsAdmin = false },\n new User() {Name = "Carl", IsAdmin = false },\n new User() {Name = "Dan", IsAdmin = false },\n new User() {Name = "Eve", IsAdmin = false },\n };\n\n UserList1 = _users.ToList(); // independent copy\n }\n}\n</code></pre>\n<p>Okay, so we have 2 different user lists. Are both of them protected from external changes? No. Even though <code>UserList1</code> has a private setter, someone can still alter individual items.</p>\n<p>Example:</p>\n<pre><code>static void Main(string[] args)\n{\n var x = SomeClassWithUsers.CreateSample();\n\n // Even though UserList1 has a private setter, I can still change individual members.\n for (var i = 0; i < x.UserList1.Count; i++)\n {\n x.UserList1[i] = new User() { Name = $"Evil {x.UserList1[i].Name}", IsAdmin = true };\n }\n\n Console.WriteLine("UserList1 has been modifed!");\n foreach (var user in x.UserList1)\n {\n Console.WriteLine($"{user.Name} {(user.IsAdmin ? "IS" : "is NOT")} an Admin.");\n }\n\n // But I cannot altger UserList2 in any way since it is properly marked as a IReadOnlyList.\n // You cannot compile the code below.\n //for (var i = 0; i < x.UserList2.Count; i++)\n //{\n // x.UserList2[i] = new User() { Name = $"Evil {x.UserList1[2].Name}", IsAdmin = true };\n //}\n\n Console.WriteLine("\\nUserList2 remains unchanged.");\n foreach (var user in x.UserList2)\n {\n Console.WriteLine($"{user.Name} {(user.IsAdmin ? "IS" : "is NOT")} an Admin.");\n }\n\n Console.WriteLine("\\nPress ENTER key to close");\n Console.ReadLine();\n}\n</code></pre>\n<p><strong>Console output:</strong></p>\n<pre><code>UserList1 has been modifed!\nEvil Alice IS an Admin.\nEvil Bob IS an Admin.\nEvil Carl IS an Admin.\nEvil Dan IS an Admin.\nEvil Eve IS an Admin.\n\nUserList2 remains unchanged.\nAlice is NOT an Admin.\nBob is NOT an Admin.\nCarl is NOT an Admin.\nDan is NOT an Admin.\nEve is NOT an Admin.\n\nPress ENTER key to close\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T14:26:19.620",
"Id": "478991",
"Score": "0",
"body": "thanks a lot for your precious time to code review. learned a lot here. Will make more improvement for the next version. Will also try to implement moq for the next version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T23:36:40.253",
"Id": "479033",
"Score": "0",
"body": "I couldn't use `IReadOnlyList` because of `BankTransactions.Add(bankTransaction);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T14:03:22.550",
"Id": "479109",
"Score": "1",
"body": "@SteveNgai You can still use IReadOnlyList if you have a private list backing it. See updated answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T14:13:45.917",
"Id": "479110",
"Score": "0",
"body": "But what is the difference if I just set the setter as private? `public List<BankTransaction> bankTransactions { get; private set; }`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T15:02:48.680",
"Id": "479114",
"Score": "1",
"body": "@SteveNgai See Update 2 for why private setter is insufficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T18:38:23.930",
"Id": "479130",
"Score": "0",
"body": "Thanks for the clear example"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T06:48:17.750",
"Id": "479317",
"Score": "0",
"body": "your way of using `Create` static method to create the instance instead of using the constructor is it considered as `Factory pattern`?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T13:28:05.723",
"Id": "243983",
"ParentId": "243974",
"Score": "4"
}
},
{
"body": "<h2>Pick your framework</h2>\n<p>You're learning new stuff, so your style will develop as you progress. While the code is still fresh, try to refactor as you go, so that the code moves towards a consistent style. If you want to move towards FluentAssertions, then try to use it for all of your assertions. Rather than this:</p>\n<blockquote>\n<pre><code>// Fluent Assertions\naccountExpected.Should().BeEquivalentTo(_bankAccount);\n\n// Default (Without Fluent Assertions)\nAssert.Equal(accountExpected.Balance, _bankAccount.Balance);\n</code></pre>\n</blockquote>\n<p>Anybody moving into the code base will need to learn <strong>all</strong> for the frameworks that are used, so if you can standardise on them then it will mean there's a lower barrier to entry.</p>\n<h2>The 3As</h2>\n<p>Arrange, Act, Assert breaks the test into three sections.</p>\n<ul>\n<li>Arrange - Prepare/Setup for the test</li>\n<li>Act - Typically invoke the method on the test</li>\n<li>Assert - Validate the expected results</li>\n</ul>\n<p>I typically don't include AAA comments in my tests because if the tests are small it's usually fairly obvious which bit is which and sometimes I'll merge sections together for conciseness, i.e. Act and Assert:</p>\n<pre><code>Assert.Throws<ArgumentException>(() => new BankAccount(bankAccountNo, balance));\n</code></pre>\n<p>Since you are adding comments, try to keep them up to date, so that they match what the test is doing. If you don't, it can be create confusion in code reviews (do you not know what is in each stage, or has the code progressed and the comment not been moved) and for new developers who may follow the approach. So, for example this:</p>\n<blockquote>\n<pre><code>[Fact]\npublic void BankAccountConstructorInvalidBalanceShouldFail()\n{\n // Act\n var bankAccountNo = new Random().Next();\n var balance = -1;\n BankAccount TestCode() => new BankAccount(bankAccountNo, balance);\n</code></pre>\n</blockquote>\n<p>Is really all Arrange, not Act. The code isn't actually invoked until the AssertThrows executes.</p>\n<h2>Remove Dead code</h2>\n<p>Code that's commented out causes noise and makes the code more difficult to follow, use source control to track previous versions of files and delete code when it's not required rather than comment it out.</p>\n<blockquote>\n<pre><code>// Assert\n//Assert.True(accountExpected.Equals(_bankAccount)); \n// Doesn't work due to object needs to be serialized first before compare.\n</code></pre>\n</blockquote>\n<p>In the middle of a test, does this mean that the code doesn't work as expected? If so, do you really want the test to be Green? It feels wrong...</p>\n<h2>Copy and paste</h2>\n<p>Some of your exception code looks like it's been copy and pasted and as a consequence you've got what looks like an error:</p>\n<blockquote>\n<pre><code>if (bankTransaction.TransactionAmount <= 0)\n{\n throw new ArgumentException("Deposit failed. Transaction amount is more than account balance.");\n}\n</code></pre>\n</blockquote>\n<p>This is really "Transaction amount must be positive", not "Transaction amount is more than account balance"...</p>\n<h2>(Null && !Null) || (!Null && Null) != (Null || Null)</h2>\n<blockquote>\n<pre><code>if( (startDate == null && endDate != null) \n || (startDate != null && endDate == null))\n{\n throw new ArgumentNullException("Start date or end date should not be null");\n}\n</code></pre>\n</blockquote>\n<p>If one of <code>startDate</code> or <code>endDate</code> is null, the argument exception triggers. However, if they are both null it doesn't. Again, this feels like a bug... Consider what you're actually trying to test here, is it just that one of the values is null, or something else...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T00:21:26.147",
"Id": "479156",
"Score": "0",
"body": "Thanks for the code review. About the `startDate` and `endDate`, my idea is if both date are null, it will return all the result without filter without creating another method for method overloading. Maybe it is better to create another method overloading instead to simplify the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T08:34:58.840",
"Id": "479182",
"Score": "1",
"body": "@SteveNgai Then the error should be 'Either startDate and endDate should be supplied, or neither' ? Alternately, consider using the dates to filter if supplied (no error). So, all transactions before endDate if supplied, after startDate if supplied. If both are supplied then 'and' the filters to create a window."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T11:50:32.207",
"Id": "479197",
"Score": "1",
"body": "@SteveNgai With Nullable's, the preferred condition would be `(!startDate.HasValue)` rather than `(startDate == null)`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T22:54:59.930",
"Id": "244079",
"ParentId": "243974",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243983",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T11:14:07.437",
"Id": "243974",
"Score": "4",
"Tags": [
"c#",
"unit-testing",
"xunit",
"fluent-assertions"
],
"Title": "Mock Atm program basic functions and xUnit unit test"
}
|
243974
|
<p>I am using <code>c++17</code> and wide characters.</p>
<p>I have created a function to create a wchar_t* using a variable number of parameters ...</p>
<pre>#include <stdarg.h>
// the caller will free the memory
wchar_t* GetMessage( const wchar_t* format, ... )
{
va_list args;
va_start(args, format);
// get the size of the final string
const auto size = vswprintf(nullptr, 0, format, args);
// create the buffer
const auto buffSize = size + 1;
const auto buffer = new wchar_t[buffSize];
memset(buffer, 0, buffSize * sizeof(wchar_t) );
// create the string
vswprintf_s(buffer, buffSize, format, args);
va_end(args);
// all done
return buffer;
}
</pre>
<p>Can you suggest a more efficient, standard, way of achieving the above?</p>
|
[] |
[
{
"body": "<p>The code you have written is fine, apart from three small issues:</p>\n<ol>\n<li>You need to check that format isn't null before calling vswprintf otherwise it crashes.</li>\n<li>There seems to be the potential for memory leaking, you are assuming the caller will always release the memory. It would return a std::wstring instead, no need to new the buffer and it is "automatically" released.</li>\n<li>Check the results of vswprintf_s() it will almost never fail, but when it does you'll be trying to track down what went wrong for days. :)</li>\n</ol>\n<p>This is my version:</p>\n<pre><code>// the caller will free the memory\nstd::wstring getMessage(const wchar_t* format, ...)\n{\n std::wstring output; // function return value.\n if (format != nullptr)\n {\n va_list args;\n va_start(args, format);\n const auto size = vswprintf(nullptr, 0, format, args); // get the size of the final string\n if (size > 0) // If the above call worked\n { \n const auto buffSize = 1 + size;\n output.reserve(buffSize); // create the buffer\n if (vswprintf_s(output.data, buffSize, format, args) < 0)// create the string\n {\n output.clear(); // Empty the string if there is a problem\n }\n }\n va_end(args);\n }\n return output;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T15:12:18.950",
"Id": "479115",
"Score": "0",
"body": "Thanks for the review, I like your suggestions, I wonder if there is any measurable performance difference in using `std::wstring` vs `new wchar_t`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T07:10:18.250",
"Id": "479173",
"Score": "0",
"body": "I would guess it would be worse, but safer. By coding wchar_t safely it would probably be slower. It depends on which is more important."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T20:17:20.800",
"Id": "244001",
"ParentId": "243975",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244001",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T11:49:18.090",
"Id": "243975",
"Score": "1",
"Tags": [
"c++17",
"variadic"
],
"Title": "Using vswprintf( ... ) to create wchar_t* with variable argument list"
}
|
243975
|
<p>The task is to represent a Matrix as a class and to instantiate it from a string such as <code>"1 2 3 4\n5 6 7 8\n9 8 7 6"</code>
The class must provide methods for accessing individual rows and columns by index starting at 1.<br />
While my solution is relatively short and more or less clear, I'm wondering about the ways to make it better.</p>
<p>One thing I'm not sure about is calling <code>_get_rows()</code> in different places inside the class, instead of assigning its result to class attribute.</p>
<p>Here is my code.</p>
<pre><code>class Matrix:
"""Class representation of a matrix"""
def __init__(self, matrix_string):
self.matrix_string = matrix_string
def _get_rows(self):
"""Produce a list of rows of the matrix."""
rows = []
for row_string in self.matrix_string.split('\n'):
rows.append([int(char) for char in row_string.split()])
return rows
def _get_columns(self):
"""Produce a list of columns of the matrix."""
rows = self._get_rows()
return [list(row) for row in zip(*rows)]
def row(self, index):
"""Produce i-th row of the matrix with first index being 1"""
return self._get_rows()[index - 1]
def column(self, index):
"""Produce i-th column of the matrix with first index being 1"""
return self._get_columns()[index - 1]
</code></pre>
<p>And the unit tests provided by exercism.</p>
<pre><code>import unittest
from matrix import Matrix
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.3.0
class MatrixTest(unittest.TestCase):
def test_extract_row_from_one_number_matrix(self):
matrix = Matrix("1")
self.assertEqual(matrix.row(1), [1])
def test_can_extract_row(self):
matrix = Matrix("1 2\n3 4")
self.assertEqual(matrix.row(2), [3, 4])
def test_extract_row_where_numbers_have_different_widths(self):
matrix = Matrix("1 2\n10 20")
self.assertEqual(matrix.row(2), [10, 20])
def test_can_extract_row_from_non_square_matrix_with_no_corresponding_column(self):
matrix = Matrix("1 2 3\n4 5 6\n7 8 9\n8 7 6")
self.assertEqual(matrix.row(4), [8, 7, 6])
def test_extract_column_from_one_number_matrix(self):
matrix = Matrix("1")
self.assertEqual(matrix.column(1), [1])
def test_can_extract_column(self):
matrix = Matrix("1 2 3\n4 5 6\n7 8 9")
self.assertEqual(matrix.column(3), [3, 6, 9])
def test_can_extract_column_from_non_square_matrix_with_no_corresponding_row(self):
matrix = Matrix("1 2 3 4\n5 6 7 8\n9 8 7 6")
self.assertEqual(matrix.column(4), [4, 8, 6])
def test_extract_column_where_numbers_have_different_widths(self):
matrix = Matrix("89 1903 3\n18 3 1\n9 4 800")
self.assertEqual(matrix.column(2), [1903, 3, 4])
if __name__ == "__main__":
unittest.main()
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I would make a few suggestions, rather than just saving the input string it would be better, as you suggest, to save the output of the <code>get_rows</code> function in memory, so you don't have to recreate it every time.\nSimilarly when you want an individual row or column, it seems inefficient to gather all the rows, (and then all the columns) just to reject all but one of them.\nYour comments say <code>produces i-th (column/row)...</code> but the variable is referred to as <code>index</code></p>\n<p>Minor points:\nYou don't need to save <code>rows</code> as a variable in _get_columns, you can just use <code>[list(row) for row in zip(*self._get_rows())]</code></p>\n<p>you could reduce _get_rows to one line : <code>[[int(char) for char in row_string.split()] for row_string in self.matrix_string.split('\\n')]</code></p>\n<p>I'm assuming that you don't need to check if the input is invalid, because that isn't part of the testing suite. However you may want to do it anyway if you plan on using this class again.</p>\n<p>In terms of style the code is good. The first comment under <code>class Matrix</code> doesn't really say anything and there are more newlines than are necessary, but other than that everything looks good.</p>\n<p>You could try something like:</p>\n<pre><code>class Matrix:\n """Class representation of an integer matrix indexed from 1\n ...\n\n Attributes\n ----------\n rows: List[List(int)]\n A list of the rows of values in the matrix.\n\n Methods\n -------\n row(self, i)\n returns the i-th row.\n\n column(self, i)\n returns the i-th column.\n """\n\n def __init__(self, matrix_string):\n """Save a list of rows from the input string.\n - matrix_string: A space and new line seperated string of values\n in the matrix.\n """\n self.rows = self._get_rows(matrix_string)\n\n def _get_rows(self, matrix_string):\n """Produce a list of rows of the matrix.\n - matrix_string: A space and new line seperated string of values\n in the matrix.\n """\n rows = []\n for row_string in matrix_string.split('\\n'):\n rows.append([int(char) for char in row_string.split()])\n return rows\n\n def _get_columns(self):\n """Produce a list of columns of the matrix."""\n return [list(row) for row in zip(*self.rows)]\n\n def row(self, i):\n """Produce i-th row of the matrix with first index being 1."""\n return self.rows[i - 1]\n\n def column(self, i):\n """Produce i-th column of the matrix with first index being 1."""\n return [row[i - 1] for row in self.rows]\n\n</code></pre>\n<p>or you could drop the <code>_get_rows</code> and change the <code>__init__</code> to:</p>\n<pre><code> def __init__(self, matrix_string):\n """Save a list of rows from the input string.\n - matrix_string: A space and new line seperated string of values\n in the matrix.\n """\n self.rows = [[int(x) for x in row.split()] for row in matrix_string.split("\\n")]\n\n</code></pre>\n<p>In terms of performance:</p>\n<p>using cProfile and the following script:</p>\n<pre><code>if __name__ == "__main__":\n for _ in range(100000):\n matrix = Matrix("1 2 3 4\\n5 6 7 8\\n9 8 7 6\\n1000 2000 3000 4000")\n for i in range(1, 5):\n matrix.column(i)\n matrix.row(i)\n\n</code></pre>\n<p>Produces for the old matrix definition:\n<code>12900228 function calls (12900222 primitive calls) in 10.239 seconds</code>\nFor the my definition:\n<code>1900228 function calls (1900222 primitive calls) in 1.359 seconds</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T13:50:06.710",
"Id": "478982",
"Score": "0",
"body": "Thanks for your suggestions! I'm aware that `_get_rows()` and `_get_columns()` can be one-liners, though I didn't want to make too long list comprehensions. I'm wondering what's wrong with my newlines, shouldn't we put a new line after a docstring?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T13:55:36.307",
"Id": "478983",
"Score": "0",
"body": "It's up to your sense of style, I would say that too many new lines spread the code out unnecessarily. Just do what ever is clearest to your eye or what matches the other code in your code base."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T14:01:13.237",
"Id": "478984",
"Score": "0",
"body": "In terms of performance:"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T14:11:09.167",
"Id": "478986",
"Score": "0",
"body": "Yeah, that's clear that my version does redundant computations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T14:17:09.193",
"Id": "478988",
"Score": "0",
"body": "Have you any ideas how to define `_get_columns()` via list comprehensions or similar elegant mechanism without using `_get_rows_()`?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T13:26:40.257",
"Id": "243982",
"ParentId": "243977",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243982",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T12:17:58.373",
"Id": "243977",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"matrix"
],
"Title": "Exercism: Class representation of a matrix in Python"
}
|
243977
|
<p>I did the Nth Prime problem on exercism.io. Now I need feedback what can be done better / improved to make the most of rust. The code calculates the nth prime. I chose to provide the sieve of Eratosthenes as iterator in Rust. The code can be seen here: <a href="https://exercism.io/tracks/rust/exercises/nth-prime/solutions/22ef08ba47d0401b9ef506ee426de5cd" rel="nofollow noreferrer">https://exercism.io/tracks/rust/exercises/nth-prime/solutions/22ef08ba47d0401b9ef506ee426de5cd</a></p>
<pre class="lang-rust prettyprint-override"><code>///implements a sieve of Eratosthenes as iterator
///https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
///The iterator skips non-primes and does the necessary
///calculations for the next.
struct Sieve {
///current index from where the next prime is searched
index: usize,
///the sieve
marked_numbers: Vec<bool>,
}
///largest number to be checked to be prime
///could be optimized to actually point to
///a prime number.
const MAX_SIEVE_SIZE: usize = 1_000_000;
impl Sieve {
fn new() -> Self {
let mut numbers = vec![true; MAX_SIEVE_SIZE];
numbers[0] = false; //no prime
numbers[1] = false; //no prime - 2 is the first prime
Sieve {
index: 0,
marked_numbers: numbers,
}
}
///marks all multiples of value to be non-prime
///to be used by next
fn mark_multiples(&mut self, value: usize) {
self.marked_numbers[self.index..]
.iter_mut()
.step_by(value)
.for_each(|x| *x = false);
}
}
impl std::iter::Iterator for Sieve {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
let slice = &self.marked_numbers[self.index + 1..];
let position = slice.iter().position(|x| *x == true);
match position {
Some(x) => {
self.index = x + self.index + 1;
self.mark_multiples(self.index);
Some(self.index)
}
None => None,
}
}
}
pub fn nth(n: usize) -> usize {
let mut sieve = Sieve::new();
sieve.nth(n).unwrap() //not nice but the API works this way
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn first_prime_is_2() {
let mut sieve = Sieve::new();
assert_eq!(sieve.next().unwrap(), 2);
}
#[test]
fn first_few_primes_are() {
let sieve = Sieve::new();
let expected = [2, 3, 5, 7];
sieve
.zip(expected.iter())
.for_each(|x| assert_eq!(x.0, *x.1 as usize));
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T15:09:51.860",
"Id": "478997",
"Score": "2",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T12:02:46.323",
"Id": "510499",
"Score": "0",
"body": "This could be made, such there are upper bound to the primes in the sieve."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T14:01:57.027",
"Id": "243986",
"Score": "1",
"Tags": [
"rust"
],
"Title": "Nth Prime via Sieve of Erastothenes as iterator"
}
|
243986
|
<p>Here I'm posting my Java code for <a href="https://leetcode.com/problems/the-skyline-problem/" rel="nofollow noreferrer">the skyline problem</a>. If you have time and would like to review, please do so, I'd appreciate that.</p>
<h3>Problem</h3>
<blockquote>
<p>A city's skyline is the outer contour of the silhouette formed by all
the buildings in that city when viewed from a distance. Now suppose
you are given the locations and height of all the buildings as shown
on a cityscape photo (Figure A), write a program to output the skyline
formed by these buildings collectively (Figure B).</p>
<p>Buildings Skyline Contour The geometric information of each building
is represented by a triplet of integers [Li, Ri, Hi], where Li and Ri
are the x coordinates of the left and right edge of the ith building,
respectively, and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤
INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0. You may assume all
buildings are perfect rectangles grounded on an absolutely flat
surface at height 0.</p>
<p>For instance, the dimensions of all buildings in Figure A are recorded
as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .</p>
<p>The output is a list of "key points" (red dots in Figure B) in the
format of [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines a
skyline. A key point is the left endpoint of a horizontal line
segment. Note that the last key point, where the rightmost building
ends, is merely used to mark the termination of the skyline, and
always has zero height. Also, the ground in between any two adjacent
buildings should be considered part of the skyline contour.</p>
<p>For instance, the skyline in Figure B should be represented as:[ [2
10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].</p>
<p>Notes:</p>
<p>The number of buildings in any input list is guaranteed to be in the
range [0, 10000]. The input list is already sorted in ascending order
by the left x position Li. The output list must be sorted by the x
position. There must be no consecutive horizontal lines of equal
height in the output skyline. For instance, [...[2 3], [4 5], [7 5],
[11 5], [12 7]...] is not acceptable; the three lines of height 5
should be merged into one in the final output as such: [...[2 3], [4
5], [12 7], ...]</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/wKVRR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wKVRR.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/ILjEf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ILjEf.png" alt="enter image description here" /></a></p>
<h3>Code</h3>
<pre><code>import java.util.Arrays;
import java.util.List;
import java.util.LinkedList;
import java.util.TreeMap;
import java.util.Collections;
class Solution {
public List<List<Integer>> getSkyline(int[][] buildings) {
List<List<Integer>> heights = new LinkedList<List<Integer>>();
TreeMap<Integer, Integer> heightTreeMap = new TreeMap<Integer, Integer>();
List<List<Integer>> contour = new LinkedList<List<Integer>>();
int lastHeight = 0;
for (int[] building : buildings) {
heights.add(Arrays.asList(building[0], -building[2]));
heights.add(Arrays.asList(building[1], building[2]));
}
Collections.sort(heights, (a, b) -> (
a.get(0).intValue() != b.get(0).intValue() ? a.get(0) - b.get(0) : a.get(1) - b.get(1)
));
heightTreeMap.put(0, 1);
for (List<Integer> val : heights) {
int height = val.get(1);
if (height < 0)
heightTreeMap.put(-height, -~heightTreeMap.getOrDefault(-height, 0));
else if (heightTreeMap.getOrDefault(height, 0) > 1)
heightTreeMap.put(height, heightTreeMap.get(height) - 1);
else
heightTreeMap.remove(height);
if (heightTreeMap.lastKey() != lastHeight) {
lastHeight = heightTreeMap.lastKey();
contour.add(Arrays.asList(val.get(0), lastHeight));
}
}
return contour;
}
}
</code></pre>
<p>On LeetCode, we are only allowed to change the argument names and brute force algorithms are discouraged, usually fail with TLE (Time Limit Error) or MLE (Memory Limit Error).</p>
<h3><a href="https://leetcode.com/problems/the-skyline-problem/solution/" rel="nofollow noreferrer">LeetCode's Solution</a> - Not for review</h3>
<pre><code>class Solution {
/**
* Divide-and-conquer algorithm to solve skyline problem,
* which is similar with the merge sort algorithm.
*/
public List<List<Integer>> getSkyline(int[][] buildings) {
int n = buildings.length;
List<List<Integer>> output = new ArrayList<List<Integer>>();
// The base cases
if (n == 0) return output;
if (n == 1) {
int xStart = buildings[0][0];
int xEnd = buildings[0][1];
int y = buildings[0][2];
output.add(new ArrayList<Integer>() {{add(xStart); add(y); }});
output.add(new ArrayList<Integer>() {{add(xEnd); add(0); }});
// output.add(new int[]{xStart, y});
// output.add(new int[]{xEnd, 0});
return output;
}
// If there is more than one building,
// recursively divide the input into two subproblems.
List<List<Integer>> leftSkyline, rightSkyline;
leftSkyline = getSkyline(Arrays.copyOfRange(buildings, 0, n / 2));
rightSkyline = getSkyline(Arrays.copyOfRange(buildings, n / 2, n));
// Merge the results of subproblem together.
return mergeSkylines(leftSkyline, rightSkyline);
}
/**
* Merge two skylines together.
*/
public List<List<Integer>> mergeSkylines(List<List<Integer>> left, List<List<Integer>> right) {
int nL = left.size(), nR = right.size();
int pL = 0, pR = 0;
int currY = 0, leftY = 0, rightY = 0;
int x, maxY;
List<List<Integer>> output = new ArrayList<List<Integer>>();
// while we're in the region where both skylines are present
while ((pL < nL) && (pR < nR)) {
List<Integer> pointL = left.get(pL);
List<Integer> pointR = right.get(pR);
// pick up the smallest x
if (pointL.get(0) < pointR.get(0)) {
x = pointL.get(0);
leftY = pointL.get(1);
pL++;
}
else {
x = pointR.get(0);
rightY = pointR.get(1);
pR++;
}
// max height (i.e. y) between both skylines
maxY = Math.max(leftY, rightY);
// update output if there is a skyline change
if (currY != maxY) {
updateOutput(output, x, maxY);
currY = maxY;
}
}
// there is only left skyline
appendSkyline(output, left, pL, nL, currY);
// there is only right skyline
appendSkyline(output, right, pR, nR, currY);
return output;
}
/**
* Update the final output with the new element.
*/
public void updateOutput(List<List<Integer>> output, int x, int y) {
// if skyline change is not vertical -
// add the new point
if (output.isEmpty() || output.get(output.size() - 1).get(0) != x)
output.add(new ArrayList<Integer>() {{add(x); add(y); }});
// if skyline change is vertical -
// update the last point
else {
output.get(output.size() - 1).set(1, y);
}
}
/**
* Append the rest of the skyline elements with indice (p, n)
* to the final output.
*/
public void appendSkyline(List<List<Integer>> output, List<List<Integer>> skyline,
int p, int n, int currY) {
while (p < n) {
List<Integer> point = skyline.get(p);
int x = point.get(0);
int y = point.get(1);
p++;
// update output
// if there is a skyline change
if (currY != y) {
updateOutput(output, x, y);
currY = y;
}
}
}
}
</code></pre>
<h3>Reference</h3>
<p><a href="https://leetcode.com/problems/the-skyline-problem/" rel="nofollow noreferrer">218. The Skyline Problem</a></p>
<p><a href="https://leetcode.com/problems/the-skyline-problem/discuss/?currentPage=1&orderBy=most_votes&query=" rel="nofollow noreferrer">218. The Skyline Problem (Discussion)</a></p>
<p><a href="https://briangordon.github.io/2014/08/the-skyline-problem.html" rel="nofollow noreferrer">Additional Details</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T15:41:16.257",
"Id": "478998",
"Score": "2",
"body": "Your link for the problem is incorrect. https://leetcode.com/problems/the-skyline-problem"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T16:06:54.760",
"Id": "479000",
"Score": "1",
"body": "Your solution is O(nlogn). A more efficient algorithm would avoid the sorting."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T15:12:47.703",
"Id": "243988",
"Score": "2",
"Tags": [
"java",
"performance",
"beginner",
"algorithm",
"programming-challenge"
],
"Title": "LeetCode 218: The Skyline Problem II"
}
|
243988
|
<p>I am working on the Project Euler, number 3 project (finding the largest prime factor of 600851475143), but I wanted to take it a step further and write something that will list all factors and prime factors of any inputted number. I'm also using this project to learn about classes (I'm putting all my different Proj. Euler challanges in their own class). Anyway, I know my code works, but when i put in the number they wanted me to use -- 600851475143 --, it sat for over five minutes and hadn't finished yet. Is there a way to optimize my code to work more efficiently?</p>
<blockquote>
<p>challangesEuler.py</p>
</blockquote>
<pre><code>class ChallangeThree:
"""Challange Three: Find the largest prime factor of 600,851,475,143
>> Takes a number, and finds it's prime factor. From there figures out
which is the largest"""
def __init__(self, value): # Defines variables
self.val = value
self.dividend = 2
# self.maxfactor = math.sqrt(value)... NOT USED
self.listdivids = []
self.listprimes = []
def isprime(self, val): # Called by 'findprimes' after getting all factors
for factor in range(2, val):
if val % factor == 0:
break # If not prime, stop trying
else:
self.listprimes.append(val) # Add new prime to list
def factor(self): # Called by 'findprimes' to find all factors
while self.val / self.dividend != 1:
if self.val % self.dividend == 0:
self.listdivids.append(self.dividend)
pass
else:
pass
self.dividend += 1
continue
self.listdivids.sort()
return self.listdivids # Returns list of dividends
def findprimes(self): # The part called in execution module
self.factor() # Finds factors
print(self.listdivids) # Prints list of factors
for dividend in self.listdivids: # For each dividend in the list, see if it's a factor
self.isprime(dividend) # Runs each dividend through the code
return self.listprimes # Returns list of prime factors
</code></pre>
<blockquote>
<p>runEuler.py</p>
</blockquote>
<pre><code>
import challangesEuler as Pr
def challangethree(x): # Creates a function to run challange three in other
ct = Pr.ChallangeThree(x)
return ct.findprimes()
print(challangethree(600851475143))
</code></pre>
|
[] |
[
{
"body": "<p>Correct me if I am wrong but I think your code in <code>findprimes</code> is checking every number to see if it is a factor and then checking every factor to see if it is prime.</p>\n<p>Rather than doing this I suggest you want to find all the prime factors, and then making the list of all factors just comes from all the combinations of prime factors in two subsets.</p>\n<p>When you look for the prime factors of a number you can save yourself some time buy only checking odd numbers (and 2) up to the square root of the number. Whenever you find a new prime factor reduce you target by that factor. There are more advanced algorithms that you may want to explore <a href=\"https://en.wikipedia.org/wiki/Integer_factorization#Factoring_algorithms\" rel=\"nofollow noreferrer\">here</a></p>\n<p>In terms of coding style you might want to change your inline comments to doc strings, remove double new lines between functions and add hyphens to your function names e.g <code>findprimes</code> >> <code>find_primes</code></p>\n<p>In terms of function names I would have expected <code>isprime</code> to return True or False if the number was or wasn't prime.</p>\n<p>I've made a quick sketch of the method I am describing:</p>\n<pre><code>import math\n\ndef find_prime_factors(target, floor=2):\n prime_factors = []\n \n while floor == 2 and target % 2 == 0:\n target = target // 2\n prime_factors.append(2)\n \n candidate = floor + 1 if floor == 2 else floor\n\n while candidate <= target:\n while target % candidate == 0:\n target = target // candidate\n prime_factors.append(candidate)\n candidate += 2\n return prime_factors\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T22:37:00.907",
"Id": "479150",
"Score": "0",
"body": "Thank you for all the feedback!! Your method does work better than mine, so thats really useful, and it uses a some neat things I hadn't seen before too! Thx! As for styling, I'll definitely keep it in mind, the double line breaks were put in place by PyCharm, but everything else definitely makes sense!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T22:57:42.703",
"Id": "479153",
"Score": "0",
"body": "Curious why you use so many while statements? for the `target % candidate` couldn't you use an if statement and just add `else: pass` since the `candidate <= target` will already continue iterating?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T12:41:40.127",
"Id": "244040",
"ParentId": "243991",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "244040",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T16:04:58.643",
"Id": "243991",
"Score": "5",
"Tags": [
"python",
"performance",
"programming-challenge"
],
"Title": "Finding all factors and prime factors of a number"
}
|
243991
|
<p>I'm going through the eBook <a href="https://books.apple.com/us/book/intro-to-app-development-with-swift/id1118575552" rel="nofollow noreferrer">Intro to App Development with Swift</a> by Apple and I am making the Rock, Paper, Scissors app in lesson 20.</p>
<p>This is the assignment that I got:</p>
<blockquote>
<p>[...] Name the enum <code>Sign</code>. Add a calculated property to give the emoji that represents the <code>Sign</code>.
[...]
You need to be able to compare two <code>Sign</code> instances to give a <code>GameState</code>.
For example, a player’s <code>.rock</code> and the app’s <code>.paper</code> would give you <code>.lose</code>.
Add an instance method to <code>Sign</code> that takes another <code>Sign</code>, representing the opponent’s turn, as a parameter. The method should return a <code>GameState</code> based on a comparison between self and the opponent’s turn. [...]</p>
</blockquote>
<p>The code that I wrote works but I feel like this can be done a lot cleaner. Maybe it's Xcode's indentation that looks a bit weird to me, maybe there's a better solution?</p>
<p>I'll start with GameState.swift (these 4 gamestates were given in the instructions):</p>
<pre><code>import Foundation
enum GameState {
case start, win, lose, draw
}
</code></pre>
<p>And here's Sign.swift:</p>
<pre><code>import Foundation
enum Sign {
case rock, paper, scissors
var emoji: String {
switch self {
case .rock: return ""
case .paper: return "✋"
case .scissors: return "✌️"
}
}
func beats(otherSign: Sign) -> GameState {
switch self {
case .rock: do {
if otherSign == .paper {
return .lose
} else if otherSign == .scissors {
return .win
}
return .draw
}
case .scissors: do {
if otherSign == .rock {
return .lose
} else if otherSign == .paper {
return .win
}
return .draw
}
case .paper: do {
if otherSign == .rock {
return .win
} else if otherSign == .scissors {
return .lose
}
return .draw
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T19:44:22.750",
"Id": "479022",
"Score": "1",
"body": "Just wanted to add that you might want to name `beats` to `playAgainst` or something else, since it implies a boolean return type"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T20:21:43.133",
"Id": "479024",
"Score": "0",
"body": "@user good catch, I still need to master good naming principles :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T13:29:57.827",
"Id": "479455",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*.\nConsider posting a new question instead."
}
] |
[
{
"body": "<p>First, the <code>do { ... }</code> blocks inside the cases are not needed:</p>\n<pre><code>func beats(otherSign: Sign) -> GameState {\n switch self {\n case .rock:\n if otherSign == .paper {\n return .lose\n } else if otherSign == .scissors {\n return .win\n }\n return .draw\n case .scissors:\n\n // ...\n}\n</code></pre>\n<p>But why use a switch-statement for <code>self</code> and an if-statement for <code>otherSign</code>? The if-statement is error-prone (we might e.g. forget a case), whereas the switch-statement perfectly matches the enum declaration and the compiler checks the exhaustiveness, i.e. that all cases are treated exactly once:</p>\n<pre><code>func beats(otherSign: Sign) -> GameState {\n switch self {\n case .rock:\n switch otherSign {\n case .paper: return .lose\n case .scissors: return .win\n case .rock: return .draw\n }\n case .scissors:\n\n // ...\n}\n</code></pre>\n<p>This is already more compact than the original code, but still clear and easy to read.</p>\n<p>Now we go one step further: A <em>single</em> switch-statement is sufficient because you can switch on a <em>tuple</em> in Swift:</p>\n<pre><code>func beats(otherSign: Sign) -> GameState {\n switch (self, otherSign) {\n case (.rock, .rock): return .draw\n case (.rock, .paper): return .lose\n case (.rock, .scissors): return .win\n \n case (.paper, .rock): return .win\n case (.paper, .paper): return .draw\n case (.paper, .scissors): return .lose\n \n case (.scissors, .rock): return .lose\n case (.scissors, .paper): return .win\n case (.scissors, .scissors): return .draw\n }\n}\n</code></pre>\n<p>It is clear to the reader that (and how) all possible combinations are handled. Repeated or missing cases are detected by the compiler.</p>\n<p>There is also another, completely different option. We can assign the integer values 0, 1, 2 to rock, paper, scissors, respectively, e.g. by making it an integer based enumeration:</p>\n<pre><code>enum Sign: Int {\n case rock, paper, scissors\n\n // ...\n}\n</code></pre>\n<p>then the outcome of the comparison can efficiently be computed from the difference of the integer values:</p>\n<pre><code>func beats(otherSign: Sign) -> GameState {\n let diff = self.rawValue - otherSign.rawValue\n\n // ...\n}\n</code></pre>\n<p>I'll leave it to you to work out the details (<em>hint:</em> modulo arithmetic), and to decide which variant your prefer: A (verbose) switch-statement with 9 cases, or a compact mathematical calculation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T20:16:00.110",
"Id": "479023",
"Score": "0",
"body": "Wow, very valuable answer! I never heard of a tuple before, for now I'll just assume that I can switch 2 identical datatypes and hope I encounter a better explanation in one of my next eBooks or courses. Modular arithmetic was giving me a bit of a headache, but I think I got a workable solution: 2 beats 1 beats 0 beats 2. So ... If the first Int is 1 bigger than the second Int, or the first Int is 2 lower than the second Int, it's a win. Else if the two Ints are the same it's a draw. Else it's a loss."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T20:25:00.990",
"Id": "479025",
"Score": "1",
"body": "@Max: You can switch on arbitrary tuples, the elements need not have the same type: `switch (someInt, someString) { case (123, \"abc\"): ...`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T20:35:05.943",
"Id": "479026",
"Score": "1",
"body": "See for example https://medium.com/the-traveled-ios-developers-guide/tuples-pattern-matching-1f4ae9817112. – Another example (sorry for the self-promotion): https://stackoverflow.com/a/25280179/1187415"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T18:30:10.603",
"Id": "243998",
"ParentId": "243992",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "243998",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T16:39:13.373",
"Id": "243992",
"Score": "4",
"Tags": [
"swift"
],
"Title": "Rock Paper Scissors in Swift"
}
|
243992
|
<p>It's a simple timed event template class. It's used in a 3D multiplayer game!</p>
<pre><code>template <class T>
class CTimeEventDecorator : public CBaseDecorator, public CPooledObject<CTimeEventDecorator<T>>
{
public:
typedef CTimeEvent<T> TTimeEventType;
typedef std::vector<TTimeEventType> TTimeEventContainerType;
CTimeEventDecorator(const TTimeEventContainerType& TimeEventContainer, T* pValue = 0)
: it_start(TimeEventContainer.begin())
, it_cur(TimeEventContainer.begin())
, it_next(TimeEventContainer.begin())
, it_end(TimeEventContainer.end())
, pData(pValue)
{
if (it_start == it_end)
*pValue = T();
else
++it_next;
}
void SetData(T* pValue)
{
pData = pValue;
}
protected:
CTimeEventDecorator(CTimeEventDecorator<T>& ted, CParticleInstance* pFirstInstance, CParticleInstance* pInstance)
: it_start(ted.it_start)
, it_end(ted.it_end)
, it_cur(ted.it_cur)
, it_next(ted.it_next)
, pData((T*)((unsigned char*)ted.pData - (DWORD)pFirstInstance + (DWORD)pInstance))
{
if (it_start == it_end)
*pData = T();
}
virtual CBaseDecorator* __Clone(CParticleInstance* pFirstInstance, CParticleInstance* pInstance)
{
return new CTimeEventDecorator(*this, pFirstInstance, pInstance);
}
virtual void __Execute(const CDecoratorData& d)
{
if (it_start == it_end)
Remove();
else if (it_cur->m_fTime > d.fTime)
*pData = it_cur->m_Value;
else
{
while (it_next != it_end && it_next->m_fTime <= d.fTime)
++it_cur, ++it_next;
if (it_next == it_end)
{
*pData = it_cur->m_Value;
Remove();
}
else
{
float length = it_next->m_fTime - it_cur->m_fTime;
*pData = it_cur->m_Value * (1 - (d.fTime - it_cur->m_fTime) / length) ;
*pData += it_next->m_Value * ((d.fTime - it_cur->m_fTime) / length);
}
}
}
typename TTimeEventContainerType::const_iterator it_start;
typename TTimeEventContainerType::const_iterator it_end;
typename TTimeEventContainerType::const_iterator it_cur;
typename TTimeEventContainerType::const_iterator it_next;
T* pData;
};
</code></pre>
<p>What optimizations, refactor I can do?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T18:46:29.310",
"Id": "479021",
"Score": "4",
"body": "Ok, what's it supposed to do? What problem does it solve? How is it called by the rest of the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T00:33:53.837",
"Id": "479036",
"Score": "1",
"body": "You should check the rules on using underscore. [Rules on Underscore](https://stackoverflow.com/q/228783/14065) Both `__Clone` and `__Execute` are reserved for use by the implementation."
}
] |
[
{
"body": "<p>This answer may come across as harsh, but it is not supposed to be.</p>\n<p>Your code looks good, BUT it lacks any comments so it’s quite difficult for other people to understand what it’s purpose is. I have no doubt that today you know what your code does, but if you are working in a professional capacity in three months time when you have written another several thousand lines you won’t remember.</p>\n<p>You have used base classes, but we can’t see them, this means we have even less understanding of the code.</p>\n<p>Your coding styles are nice and clean, but you need to decide which one to use for instance you’ve got camel case and underscores in variable names.</p>\n<p>It’s possible that things are being done in the base classes that I can’t see, but you seem to be dereferencing pointers without verifying they are not null. See *pData, which isn’t initialised.</p>\n<p>And a really minor thing length could be a const variable.</p>\n<p>You say you want to optimise the code. What problems are there with it? Have you benchmarked it’s current performance, where is most of the time spent?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T00:35:22.133",
"Id": "479037",
"Score": "1",
"body": "Personally I think most comments are bad (though there are exceptions). Self documenting code is better. But one or the other is required. In this case we have neither."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T19:49:59.310",
"Id": "243999",
"ParentId": "243995",
"Score": "2"
}
},
{
"body": "<h2>Overview</h2>\n<p>I have no idea what is happening inside the code or how it works.</p>\n<p>@Code Gorilla has suggested comments. I would suggest writing self documenting code. Better type/method/variable names would be nice. Obtuse things should definitely be explained.</p>\n<h2>Code Review</h2>\n<p>Typedef's are old school.</p>\n<pre><code> typedef TimeEvent<T> TTimeEventType;\n typedef std::vector<TTimeEventType> TTimeEventContainerType;\n</code></pre>\n<p>The modern equivalent is a using statement.</p>\n<pre><code> using TTimeEventType = TimeEvent<T>;\n using TTimeEventContainerType = std::vector<TTimeEventType>;\n</code></pre>\n<hr />\n<p>Haveing zero (<code>0</code>) as the default value of a pointer is untidy.</p>\n<pre><code> CTimeEventDecorator(const TTimeEventContainerType& TimeEventContainer, T* pValue = 0)\n</code></pre>\n<p>Use the modern <code>nullptr</code>.</p>\n<pre><code> CTimeEventDecorator(const TTimeEventContainerType& TimeEventContainer, T* pValue = nullptr)\n</code></pre>\n<hr />\n<p>Pointers are dangerous. Why are we allowing a dangerous item into your class. I would wrap that in a class to protect against accidental usage.</p>\n<hr />\n<p>Well that look particularly dangerious.</p>\n<pre><code> , pData((T*)((unsigned char*)ted.pData - (DWORD)pFirstInstance + (DWORD)pInstance))\n</code></pre>\n<p>I know I don't like comments. But this absolutely needs some explaining. I have no idea what is happening here.</p>\n<p>Also you are using <code>C</code> cast <code>(T*)</code>. Please work out what the C++ equivalent is and use that. Probably <code>reinterpret_cast<T*></code>. That will at least let automated tools find and warn people that you are trying to crash the program.</p>\n<hr />\n<p>Don't use pointers if you don't need to:</p>\n<pre><code> virtual CBaseDecorator* __Clone(CParticleInstance* pFirstInstance, CParticleInstance* pInstance)\n {\n return new CTimeEventDecorator(*this, pFirstInstance, pInstance);\n }\n</code></pre>\n<p>You could simply return an object here. The code would work just as well.</p>\n<pre><code> virtual CBaseDecorator __Clone(CParticleInstance* pFirstInstance, CParticleInstance* pInstance)\n {\n return CTimeEventDecorator(*this, pFirstInstance, pInstance);\n }\n</code></pre>\n<p>Now with no dynamic allocation.</p>\n<p>OK. If you must use dynamic allocation (I can't tell because you don't show the base class so I can't see if this is inherited. Then at least return a smart pointer so that we can correctly control the lifespan of the object without worrying to much:</p>\n<pre><code> virtual std::unique_ptr<CBaseDecorator> __Clone(CParticleInstance* pFirstInstance, CParticleInstance* pInstance)\n {\n return std::make_unique<CTimeEventDecorator>(*this, pFirstInstance, pInstance);\n }\n</code></pre>\n<hr />\n<p>In modern C++ you should probably add <code>overrides</code> if this overrides a virtual function in the base class.</p>\n<p>If your base class does not have virtual functions then you should probably have a virtual destructor for this class (or your base class).</p>\n<hr />\n<p>I am going to say what are you trying to pull!!!!</p>\n<pre><code> while (it_next != it_end && it_next->m_fTime <= d.fTime)\n ++it_cur, ++it_next;\n\n // Your using the comma operator to get multile actions\n // actions into a single statement. Even if that was a\n // a good idea (and its not) I would still tell you to\n // add braces around the sub block to make it clear.\n\n // But this is truly horrible.\n // A lot of developer's will not even know what you did there.\n</code></pre>\n<p>Be clear concise and write like the next maintainer owns an axe and knows where you live.</p>\n<pre><code> while (it_next != it_end && it_next->m_fTime <= d.fTime)\n {\n ++it_cur;\n ++it_next;\n }\n</code></pre>\n<p>It will not be any less effecient spread over two lines.</p>\n<hr />\n<p>This might have been a place to add your own types to the class:</p>\n<pre><code> typename TTimeEventContainerType::const_iterator it_start;\n typename TTimeEventContainerType::const_iterator it_end;\n typename TTimeEventContainerType::const_iterator it_cur;\n typename TTimeEventContainerType::const_iterator it_next;\n</code></pre>\n<p>I would have written:</p>\n<pre><code> using const_iterator = TTimeEventContainerType::const_iterator;\n \n const_iterator it_start;\n ...\n</code></pre>\n<hr />\n<p>I hope that is not an owned pointer.</p>\n<pre><code> T* pData;\n</code></pre>\n<p>Otherwise your compiler generated copy and assignment operators are not going to work as expected. Which is another reason to wrap pointers. To make their use clear. As a maintainer I now have to go and find out if you are accidentally leaking pointers.</p>\n<pre><code> using NowOwnedRawPointer = T*;\n NowOwnedRawPointer pData;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T01:02:28.003",
"Id": "244015",
"ParentId": "243995",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T17:54:58.247",
"Id": "243995",
"Score": "0",
"Tags": [
"c++"
],
"Title": "Simple timed event template class"
}
|
243995
|
<p>I've made this Function <code>gradient()</code> that returns a list of <strong>rbg</strong> of all the colors in an order.</p>
<p><em><strong>Issues:-</strong></em></p>
<ul>
<li><p>What should be the condition for while loop to stop the loop. Though <code>b == 0</code> in the last <code>elif</code> block works fine.</p>
</li>
<li><p>How can I reduce the code of the function keeping the functionality the same. Like if there is any better approach to doing this.</p>
</li>
<li><p>Also, How can I calculate the length of the <code>rbg_list</code> just with the value of <code>gap</code> parameter without running the function. <em>Let's say the length of the <code>rbg_list</code> will be 1529 if <code>gap=1</code> so I can iterate it with <code>range(1529)</code>.</em></p>
</li>
</ul>
<hr />
<p><em><strong><code>gradient()</code> function:-</strong></em></p>
<pre class="lang-py prettyprint-override"><code>def gradient(gap=1):
r, g, b = 255, 0, 0
if gap<=0:
return (r, g, b)
rbg_list = []
while True:
if r == 255 and g >= 0 and g < 255 and b == 0: # 1
g += gap
if g > 255:
g = 255
elif r <= 255 and g == 255 and r > 0 and b == 0: # 2
r -= gap
if r < 0:
r = 0
elif r == 0 and g == 255 and b < 255 and b >= 0: # 3
b += gap
if b > 255:
b = 255
elif r == 0 and g <= 255 and g > 0 and b == 255: # 4
g -= gap
if g < 0:
g = 0
elif r >= 0 and g == 0 and r < 255 and b == 255: # 5
r += gap
if r > 255:
r = 255
elif r == 255 and g == 0 and b > 0 and b <= 255: # 6
b -= gap
if b < 0:
b = 0
if b == 0: break
# print(r, g, b)
rbg_list.append((r, g, b))
return rbg_list
print(gradient(5))
</code></pre>
<p><em><strong>Note:-</strong></em> I want the function to be compatible with both Python 2 and Python 3</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T18:32:17.873",
"Id": "479018",
"Score": "0",
"body": "Is this in python 2 or python 3?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T18:33:31.103",
"Id": "479019",
"Score": "0",
"body": "@Linny: I want it to run on both Python versions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T09:28:38.837",
"Id": "479086",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>I rarely do python nowadays, but cleanup of the conditions would be:</p>\n<pre><code>def add(c, gap):\n return min(255, c + gap)\n \ndef sub(c, gap):\n return max(0, c - gap)\n\ndef gradient(gap=1):\n r, g, b = 255, 0, 0\n\n if gap<=0: \n return (r, g, b)\n\n rbg_list = []\n while True:\n if r == 255 and g < 255 and b == 0: # 1\n g = add(g, gap)\n\n elif r > 0 and g == 255 and b == 0: # 2\n r = sub(r, gap)\n \n elif r == 0 and g == 255 and b < 255: # 3\n b = add(b, gap)\n \n elif r == 0 and g > 0 and b == 255: # 4\n g = sub(g, gap)\n \n elif r < 255 and g == 0 and b == 255: # 5\n r = add(r, gap)\n \n elif r == 255 and g == 0 and b > 0: # 6\n b = sub(b, gap)\n \n if b == 0: break\n \n # print(r, g, b)\n rbg_list.append((r, g, b))\n return rbg_list\n \n</code></pre>\n<p>Now let me understand what happens. Let us on paper name the 3 states for a color component x (r, g or b):</p>\n<pre><code> a = x == 0\n b = 0 < x < 255\n c = x == 255 \n \n a : == 0\n bc : > 0\n c : == 255\n ab : < 255\n \n start: c a a\n \n c ab a .+. -->> c c a\n bc c a -.. -->> a c a\n a c ab ..+ -->> a c c\n a bc c .-. -->> a a c\n ab a c +.. -->> c a c\n c a bc ..- -->> c a a\n \n</code></pre>\n<p>A very limited kind of gradient, restricted to one color component.\nThis could be written as 6 loops:</p>\n<pre><code> while g < 255: # 1\n g += gap\n rbg_list.append((r, g, b))\n\n g = 255\n rbg_list.append((r, g, b))\n \n while r > 0: # 2\n r -= gap\n \n r = 0\n rbg_list.append((r, g, b))\n\n ...\n</code></pre>\n<p>However you have just increasing from 0 by <code>gap</code>, and decreasing from 255 by <code>gap</code>.\nThese would give two component value arrays which can then be used with the two other components 0 or 255. That should be exploitable in Python.</p>\n<p>You might also calculate how many <code>gap</code> steps are needed for 255, times 6, and have a function that gives for the ith step the (r, g, b). <strong>That would be the simplest.</strong></p>\n<p>I admit I might be mistaken in what gradient calculation you want to achieve.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T21:00:07.850",
"Id": "479027",
"Score": "0",
"body": "Thank you for a good explanation, I really like how you simplify the function with `add` and `sub` functions. I've figured a calculation to find the total iterations according to the value given to `gap` by this `len([c for c in range(0, 255, gap)])*6-1`, this gives me the accurate value and also I've tested it by comparing to the length of the list with different `gap` values, but I'm not sure if this is how it should be calculated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T21:21:20.470",
"Id": "479028",
"Score": "0",
"body": "You forget to return the values of functions `add` and `sub`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T06:32:08.210",
"Id": "479061",
"Score": "2",
"body": "Thanks, @StephenRauch corrected that. If you write out the loop, add/siub are not needed too, only for the <= 0, >= 255 value one, which then becomes an assignment = 0, resp. = 255. The total number of iterations could also be done with approx. (255/gap) * 6 with careful rounding. Maybe faster then range."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T20:43:06.353",
"Id": "244002",
"ParentId": "243996",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "244002",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T18:06:36.337",
"Id": "243996",
"Score": "7",
"Tags": [
"python",
"performance"
],
"Title": "Gradient function that returns a list of all colors in order"
}
|
243996
|
<p>I am trying to create a navbar menu from JSON data. Actually I have achieved it but I am looking for feedback not to call <code>getItems</code> twice? How can I improve my code?</p>
<p>Thank you</p>
<pre><code>var _ = require('lodash');
let menuConfig = [
{
ID: 1,
TAG: "M:A",
PARENT_TAG: "MAIN",
TITLE: "A Title"
},
{
ID: 2,
TAG: "AS1",
PARENT_TAG: "M:A",
TITLE: "A Subtitle 1"
},
{
ID: 3,
TAG: "AS2",
PARENT_TAG: "M:A",
TITLE: "A Subtitle 2"
},
{
ID: 4,
TAG: "AS3",
PARENT_TAG: "M:A",
TITLE: "A Subtitle 3"
},
{
ID: 5,
TAG: "M:B",
PARENT_TAG: "MAIN",
TITLE: "B Title"
},
{
ID: 6,
TAG: "BS1",
PARENT_TAG: "M:B",
TITLE: "B Subtitle 1"
},
{
ID: 7,
TAG: "BS2",
PARENT_TAG: "M:B",
TITLE: "B Subtitle 2"
},
{
ID: 8,
TAG: "M:C",
PARENT_TAG: "MAIN",
TITLE: "C Title"
},
{
ID: 8,
TAG: "CS1",
PARENT_TAG: "M:C",
TITLE: "C Subtitle 1"
}
]
function getMenu() {
let grouped = _.groupBy(menuConfig, "PARENT_TAG");
let menu = getItems(grouped.MAIN, grouped);
console.log(JSON.stringify(menu, null, 3));
}
function getItems(items, grouped) {
let subMenu = [];
_.forEach(items, (item) => {
let newItem = getItem(item, grouped)
if (newItem) {
subMenu.push(newItem);
}
});
return subMenu;
}
function getItem(item, grouped) {
if (grouped[item.TAG]) {
let subMenu = getItems(grouped[item.TAG], grouped);
if (subMenu && subMenu.length) {
return {
title: item.TITLE,
subMenu: subMenu
}
}
} else {
let newItem = {
title: item.TITLE
}
return newItem;
}
}
getMenu();
</code></pre>
<p>Output needs to be like this;</p>
<pre><code>[
{
"title": "A Title",
"subMenu": [
{
"title": "A Subtitle 1"
},
{
"title": "A Subtitle 2"
},
{
"title": "A Subtitle 3"
}
]
},
{
"title": "B Title",
"subMenu": [
{
"title": "B Subtitle 1"
},
{
"title": "B Subtitle 2"
}
]
},
{
"title": "C Title",
"subMenu": [
{
"title": "C Subtitle 1"
}
]
}
]
</code></pre>
|
[] |
[
{
"body": "<p>You can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce\" rel=\"nofollow noreferrer\">Array.prototype.reduce</a> to group items by <code>TAG</code> as the key and using the relationship between <code>PARENT_TAG</code> and <code>TAG</code>.</p>\n<p>This approach will give the expected result by running the array only <code>once</code>.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const menuConfig = [{\n ID: 1,TAG: \"M:A\", PARENT_TAG: \"MAIN\", TITLE: \"A Title\"\n}, {\n ID: 2, TAG: \"AS1\", PARENT_TAG: \"M:A\", TITLE: \"A Subtitle 1\"\n}, {\n ID: 3, TAG: \"AS2\", PARENT_TAG: \"M:A\", TITLE: \"A Subtitle 2\"\n}, {\n ID: 4, TAG: \"AS3\", PARENT_TAG: \"M:A\", TITLE: \"A Subtitle 3\"\n}, {\n ID: 5, TAG: \"M:B\", PARENT_TAG: \"MAIN\", TITLE: \"B Title\"\n}, {\n ID: 6, TAG: \"BS1\", PARENT_TAG: \"M:B\", TITLE: \"B Subtitle 1\"\n}, {\n ID: 7, TAG: \"BS2\", PARENT_TAG: \"M:B\", TITLE: \"B Subtitle 2\"\n}, {\n ID: 8, TAG: \"M:C\", PARENT_TAG: \"MAIN\", TITLE: \"C Title\"\n}, {\n ID: 8, TAG: \"CS1\", PARENT_TAG: \"M:C\", TITLE: \"C Subtitle 1\"\n}]\n\nfunction getMenu() {\n const menu = getItems(menuConfig, 'MAIN');\n console.log(menu);\n}\n\nfunction getItems(items, grandParentTag) {\n const newItems = items.reduce((modifiedObj, currentItem) => {\n const parentTag = currentItem.PARENT_TAG;\n const tag = currentItem.TAG;\n\n if (!modifiedObj[grandParentTag]) {\n modifiedObj[parentTag] = {};\n }\n\n if (!modifiedObj[grandParentTag][parentTag]) {\n modifiedObj[parentTag][tag] = {\n title: currentItem.TITLE,\n subMenu: [],\n };\n } else {\n modifiedObj[grandParentTag][parentTag].subMenu.push({\n title: currentItem.TITLE,\n });\n }\n\n return modifiedObj;\n\n }, {});\n\n return Object.values(newItems[grandParentTag]);\n}\n\ngetMenu();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T10:34:34.857",
"Id": "244100",
"ParentId": "244003",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "244100",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T20:46:33.233",
"Id": "244003",
"Score": "1",
"Tags": [
"javascript",
"array",
"node.js",
"json"
],
"Title": "Creating a Navbar Menu from JSON data with Lodash"
}
|
244003
|
<p>This is my implementation of Quick Sort Algorithm :</p>
<pre class="lang-py prettyprint-override"><code>def quick_sort(sequence):
if len(sequence)<= 1:
return sequence
else:
pivot = sequence.pop() # To take the last item of "sequence" list
greater =[]
lower = []
for n in sequence:
if n > pivot :
greater.append(n)
else:
lower.append(n)
""" return the quiqk sorted "lower" and "greater" lists ,and pivot as a list in between """
return quick_sort[lower] + [pivot] + quick_sort[greater]
</code></pre>
<p><strong>How can I improve it ?</strong></p>
|
[] |
[
{
"body": "<p>The main single advantage of quicksort is that it sorts in-place. Your implementation does not. It requires an additional memory for <code>left</code> and <code>right</code> lists, linear in terms of the initial array length.</p>\n<p>Returning the concatenation of the three lists also doesn't help performance.</p>\n<p>An obvious improvement is to reimplement it in-place.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T23:55:59.420",
"Id": "244013",
"ParentId": "244004",
"Score": "2"
}
},
{
"body": "<ol>\n<li><p>In-place quicksort:<br />\nYou can make your quicksort inplace, so that it only uses O(log(N)) memory or O(1) memory. Memory is how much computer data your function uses (different from speed).</p>\n</li>\n<li><p>Choosing a better pivot:<br />\nChoosing the last element as your pivot will make quicksort converge to O(N²) for sorted lists, which is quite common in real world scenarios. O(N²) is very, very slow so you definitely do not want to choose the last element as your pivot.\nHere are some pivots that you can consider:</p>\n<ul>\n<li><p>The middle element of your list. If you choose this, you will not get O(N²) time for nearly sorted lists, but it's still very easy to make a list that makes your program go to O(N²) time complexity. I wouldn't recommend this, although it's still better than the one you have currently.</p>\n</li>\n<li><p>The Mo3 approach. This is where your pivot is the median of the first, middle and last element of your list. Although still possible, it's unlikely that it will approach O(N²) time complexity. Since the median of 3 is still relatively easy to compute, you should definitely consider this.</p>\n</li>\n<li><p>A random element from your list. You can choose a random element from your list by</p>\n<pre><code>import random\nrandom.choice(sequence)\n</code></pre>\n<p>Choosing a random variable will make going to O(N^2) time nearly impossible. However, finding a random variable is slightly time costly (Mo3 is faster to find, but there's a very slight chance it might become incredibly slow).</p>\n</li>\n</ul>\n</li>\n<li><p>Insertion Sorting. For lists of size 10 or less, sort the rest of the list using insertion sort instead. Insertion sort, although an O(N²) time complexity, is faster than quicksort for lists of size 10 or less. You can implement it into your code like this:</p>\n<pre><code>def quick_sort(sequence):\n if len(sequence) <= 10:\n insertionsort(sequence)\n return sequence\n</code></pre>\n<p>Keep in mind that you will have to implement insertion sort. I would recommend <a href=\"https://www.geeksforgeeks.org/insertion-sort/\" rel=\"nofollow noreferrer\">https://www.geeksforgeeks.org/insertion-sort/</a> if you do not already know what insertion sort is.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-22T23:58:36.923",
"Id": "257551",
"ParentId": "244004",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T21:03:55.040",
"Id": "244004",
"Score": "1",
"Tags": [
"python",
"algorithm",
"sorting",
"quick-sort"
],
"Title": "QuickSort Algorithm (Python)"
}
|
244004
|
<p>I want to pass the param from the request on the scope method in the model and serve it as json to be rendered by select2. Which is better?</p>
<h3>1. Pass request from the controller like this</h3>
<p>controller:</p>
<pre><code>public function selectJson(Request $request)
{
$request = Customer::getSelect2($request)
return \Response::json($request);
}
</code></pre>
<p>model:</p>
<pre><code>public function scopeGetSelect2($query, $request)
{
$customers = $query->select('id','name')->orderBy('name','asc')->where("name", "like", "%".$request->q."%");
if($request->city_id)
{
$customers = $query->where("city_id", $request->city_id);
}
$customers = $customers->limit(5)->get();
$formatted_tags = [];
foreach ($customers as $customer) {
$formatted_tags[] = ['id' => $customer->id, 'text' => $customer->name];
}
return $formatted_tags;
}
</code></pre>
<h3>2. Use request() helper in the model</h3>
<p>Controller:</p>
<pre><code>public function selectJson()
{
$request = Customer::getSelect2()
return \Response::json($request);
}
</code></pre>
<p>Model:</p>
<pre><code>public function scopeGetSelect2($query)
{
$customers = $query->select('id','name')->orderBy('name','asc')->where("name", "like", "%".request()->q."%");
if($request->city_id)
{
$customers = $query->where("city_id", request()->city_id);
}
$customers = $customers->limit(5)->get();
$formatted_tags = [];
foreach ($customers as $customer) {
$formatted_tags[] = ['id' => $customer->id, 'text' => $customer->name];
}
return $formatted_tags;
}
</code></pre>
<p>Which is better in performance and best practice? And should I format the return in the model like above codes or in the controller like below:</p>
<pre><code>public function selectJson()
{
$customers = Customer::getSelect2()->limit(5)->get();
$formatted_tags = [];
foreach ($customers as $customer) {
$formatted_tags[] = ['id' => $customer->id, 'text' => $customer->name];
}
return \Response::json($formatted_tags);
}
</code></pre>
<p>Or any other method or concern that I need to know?</p>
<p>Thanks in advance</p>
|
[] |
[
{
"body": "<p>Laravel scopes are not a way to create static methods, they should be used to add parts to a database query. <a href=\"https://laravel.com/docs/7.x/eloquent#local-scopes\" rel=\"nofollow noreferrer\">They should always return a query builder</a>.</p>\n<p>Aim to make your scopes as small as possible so you can then combine them together to make more complex queries.</p>\n<p>It doesn't matter if you use the <code>Request</code> passed in to the controller or the <code>request()</code> helper, use whichever you prefer.</p>\n<p>If you aren't going to reuse the <code>getSelect2()</code> method you don't need to add it to the model, just do the query in the controller. If you do need to repeat the query elsewhere you can make a new class that can build the options (<code>$formatted_tags</code>).</p>\n<pre class=\"lang-php prettyprint-override\"><code>class Customer extends Model\n{\n // ...\n\n public function scopeNameLike($query, $name): void\n {\n $query->orderBy('name','asc')->where("name", "like", "%{$name}%");\n }\n\n // ...\n}\n</code></pre>\n<pre class=\"lang-php prettyprint-override\"><code>class Controller\n{\n public function selectJson(Request $request)\n {\n return Customer::nameLike($request->q)\n ->when($request->city_id, function ($query, $value) {\n $query->where('city_id', $value);\n })\n ->limit(5)\n ->get(['name', 'id'])\n ->map(function ($item) {\n return ['id' => $item->id, 'text' => $item->name];\n });\n }\n}\n</code></pre>\n<hr />\n<blockquote>\n<p>Is return something in scope really bad practice? What about the normal method in the model? I have so many tables/models that I need to format to select2 format. Am I need to format it in every controller? – Muhammad Dyas Yaskur</p>\n</blockquote>\n<p>I was mistaken that scopes shouldn't return a value, as per the Laravel documentation they <a href=\"https://laravel.com/docs/7.x/eloquent#local-scopes\" rel=\"nofollow noreferrer\">should return a query builder instance</a>. It would be bad practice to return any other value from a scope.</p>\n<p>If you need many of these types of queries for different models you can create a helper class that can then be reused.</p>\n<pre class=\"lang-php prettyprint-override\"><code>class Select2\n{\n public static function customer(Request $request)\n {\n // Query moved from controller\n }\n}\n</code></pre>\n<pre class=\"lang-php prettyprint-override\"><code>class Controller\n{\n public function selectJson(Request $request)\n {\n return Select2::customer($request);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T20:58:47.540",
"Id": "479142",
"Score": "0",
"body": "Is return something in scope really bad practice? What about the normal method in the model? I have so many tables/models that I need to format to select2 format. Am I need to format it in every controller?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T21:42:06.480",
"Id": "479145",
"Score": "0",
"body": "okay, thank for your explanation, I have so many models that I need to select2 format, should I declare static method every model? What about using a trait like on my another question?\nhttps://codereview.stackexchange.com/questions/244071/using-method-trait-to-return-something-in-laravel-model"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T13:11:12.150",
"Id": "244042",
"ParentId": "244007",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T21:49:57.337",
"Id": "244007",
"Score": "5",
"Tags": [
"php",
"comparative-review",
"laravel",
"eloquent"
],
"Title": "Laravel Scope get request data/param"
}
|
244007
|
<p>Now ALL of the below works as intended - a poll asks users questions and I store them in a dictionary, finally I print how many times a country was mentioned - boring I know. However, I really want to know if there is <strong>better, cleaner even high level way</strong> to do this (<em>reading comments here people usually mention speed, efficiency always gets me excited and motivated to carry on learning</em>) and if I am falling into any potholes or bad practices. I am not new to programming but new to Python, I would genuinely appreciate the help. Stay safe :)</p>
<pre><code>dream_vacation_poll = {}
question = 'What is your dream holiday? '
while True:
name = input('Name: ').lower()
message = input(question).lower()
dream_vacation_poll[name] = message
message = input('Does anyone else want to answer? (y/n)').lower()
if message == 'n':
break
else:
continue
results = {}
for country in dream_vacation_poll.values():
count = 0
v = country
for value in dream_vacation_poll.values():
if v == value:
count += 1
results[v] = count
print(results)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T22:35:50.757",
"Id": "479031",
"Score": "0",
"body": "The second block (with the two `for` loops) could be refactored to a **list comprehension** in order to produce more compact and Pythonic code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T00:03:44.200",
"Id": "479034",
"Score": "2",
"body": "There is no way that this code can run. Please can you update your question with working code. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T03:41:25.453",
"Id": "479052",
"Score": "3",
"body": "Specifically, the indentation starting at `for value` is broken. This is required to be fixed for Python to be able to interpret it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T03:44:10.763",
"Id": "479054",
"Score": "0",
"body": "Said another way: if you copy the code out of this question and paste it into your IDE, are you _sure_ that this works as intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T08:21:17.290",
"Id": "479083",
"Score": "0",
"body": "`efficiency always gets me excited` there's (computing) machinery resources, and other. Such as *human*, including *user*s and *developer*s."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T22:41:18.680",
"Id": "479151",
"Score": "0",
"body": "@Reinderien apologies for the indentation issue, code does work I just messed up when I copied and pasted here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T22:41:28.240",
"Id": "479152",
"Score": "0",
"body": "@greybeard I’m sorry I don’t follow"
}
] |
[
{
"body": "<p>Well, I found a few issues with this code, which can be easily fixed.</p>\n<p>The first is really small. In your <code>while True</code> loop you read the name of a person and then apply <code>.lower()</code> to it. I'd consider using <code>.title()</code>, because it makes first letter capital. Example:</p>\n<pre><code>>>> 'nIKOlay'.title()\n'Nikolay'\n</code></pre>\n<p>I'm not really sure if you should also use <code>.title()</code> with dream vacation message, because dream vacation is not necessary a country/city.</p>\n<p>You also don't need that <code>else: continue</code> block in 'while True', because it basically does nothing in your program. So it's better to just remove it.</p>\n<p>The third issue is pretty major, as I think. There's a much simpler way to get the <code>results</code> dictionary. You can do this right in your <code>while True</code> loop when you read the <code>message</code>. So the code will be:</p>\n<pre><code>dream_vacation_poll = {}\nresults = {}\nquestion = 'What is your dream holiday? '\n\nwhile True:\n name = input('Name: ').title()\n message = input(question).lower()\n dream_vacation_poll[name] = message\n\n if message in results.keys():\n results[message] += 1\n else:\n results[message] = 1\n\n message = input('Does anyone else want to answer? (y/n)').lower()\n if message == 'n':\n break\n\nprint(results)\n</code></pre>\n<p>But there's an even more elegant solution. Instead of checking if the key is in <code>results.keys()</code> we can use <code>defaultdict</code> from collections module:</p>\n<pre><code>from collections import defaultdict\n\ndream_vacation_poll = {}\n# create defaultdict and set all values equal to 0 by default\n# we use this so we dont have to check if key is in results.keys()\nresults = defaultdict(int)\nquestion = 'What is your dream holiday? '\n\nwhile True:\n name = input('Name: ').lower()\n message = input(question).lower()\n dream_vacation_poll[name] = message\n\n results[message] += 1\n\n message = input('Does anyone else want to answer? (y/n)').lower()\n if message == 'n':\n break\n\n# convert defaultdict to dict\nprint(dict(results))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T22:37:00.860",
"Id": "479149",
"Score": "0",
"body": "thank you so much for this explanation learnt something new today (deafultdict) , always appreciate people like you thanks again. Also realised I need to really narrow down what I want each part of my program to do, that way my logic can improve. Do you have any techniques for this or is it just experience ?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T12:00:38.377",
"Id": "244036",
"ParentId": "244008",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244036",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T22:15:57.383",
"Id": "244008",
"Score": "2",
"Tags": [
"python"
],
"Title": "Dream holiday poll"
}
|
244008
|
<p>This particular snippet is a simple to-do app that allows the user to add new items to the list, mark them as done, delete a single item, or delete all items.</p>
<p>What I would be looking for advice on are my use of a function constructor. It may be overkill for something like this, but it is more of a learning exercise to become familar with the process. Could the building up of each list item be done in a better way?</p>
<p>On the use of an IIFE, my understanding of these is that it can help self-contain code snippets and ensure they keep their scope. Would this be a good practice going forward, or do they have their best use cases?</p>
<p>If there are other areas of improvement I would welcome input regarding those. Thanks.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>(function(){
"use strict"
let form, listArea, formInput, clearList;
// Function constructor
// Will build up each list item
// With associated functions
const Task = function (taskName) {
this.taskName = taskName;
this.buildTask = function () {
let newListItem = document.createElement('li');
newListItem.innerHTML = `<span></span>${this.taskName}<button class="remove-item">Bin It</button>`;
newListItem.querySelector('.remove-item').addEventListener('click', removeItem);
newListItem.querySelector('span').addEventListener('click', markDone);
listArea.appendChild(newListItem);
}
}
function markDone(e) {
e.currentTarget.parentNode.classList.toggle('done');
}
function removeItem(e) {
e.currentTarget.parentNode.remove();
}
function clearAllItems() {
let listAreaItem = listArea.querySelectorAll('li');
listAreaItem.forEach((item) => {
item.remove();
})
}
// On form submit
// Create new instance of Task
function formValidate(e) {
e.preventDefault();
const value = formInput.value
if(!value) {
formInput.dataset.state = 'invalid';
return;
}
// Trim whitespace from the input
const trimValue = formInput.value.trim();
if(trimValue) {
formInput.dataset.state = 'valid';
new Task(trimValue).buildTask();
formInput.value = '';
}
}
function startup() {
form = document.getElementById('form');
listArea = document.getElementById('listArea');
formInput = document.getElementById('addToField');
clearList = document.getElementById('clearList');
// Check for an submit on the form field
form.addEventListener('submit', formValidate);
clearList.addEventListener('click', clearAllItems);
}
window.addEventListener('DOMContentLoaded', startup);
})();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
box-sizing: border-box;
}
body,
button,
form input,
form button {
font-family: 'Space Mono', monospace;
}
button {
color: #fff;
border: none;
background: #7e7e7e;
height: 60px;
padding: 0 25px;
}
button:hover,
ul li span:hover {
cursor: pointer;
}
.input-area {
max-width: 600px;
margin-left: auto;
margin-right: auto;
padding: 50px;
}
#form {
display: flex;
}
form input {
border: none;
border-bottom: 2px solid rgba(0,0,0,0.25);
height: 60px;
flex-grow: 1;
font-size: 20px;
}
form input[data-state="invalid"] {
border-color: red;
}
form input[data-state="valid"] {
border-color: green;
}
form button {
height: 60px;
border: 2px solid rgba(0,0,0,0.25);
flex-basis: 175px;
flex-grow: 0;
flex-shrink: 0;
border: none;
color: #fff;
}
ul {
list-style: none;
padding-left: 0;
}
ul li {
display: flex;
line-height: 60px;
background-color: #e3e3e3;
margin: 5px 0;
}
ul li.done {
background-color: limegreen;
}
ul li span {
display: inline-block;
width: 60px;
height: 60px;
background-color: rgba(0,255,0,0.2);
margin-right: 20px;
}
ul li.done span {
background-color: green;
}
ul li button {
height: 60px;
padding: 0 20px;
margin-left: auto;
background-color: #db4646;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To Do App</title>
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css2?family=Space+Mono&display=swap" rel="stylesheet">
</head>
<body>
<main>
<div class="input-area">
<h1>Do it.</h1>
<form id="form">
<input id="addToField" type="text">
<button id="submitToList" type="submit">Add to List</button>
</form>
<ul id="listArea"></ul>
<button id="clearList">Clear List</button>
</div>
</main>
</body>
<script src="script-2.js"></script>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<blockquote>\n<p>On the use of an IIFE, my understanding of these is that it can help self-contain code snippets and ensure they keep their scope. Would this be a good practice going forward, or do they have their best use cases?</p>\n</blockquote>\n<p>Usually you'd write ES5 modules and use a build tool like Rollup, Webpack or Parcel to compile your code into something understandable by older browsers. <br />\nLearning and keeping up with the whole ecosystem of NodeJS-based development tools can be overwhelming though.</p>\n<blockquote>\n<p>If there are other areas of improvement I would welcome input regarding those.</p>\n</blockquote>\n<p>Modern frameworks like React tend to approach working with DOM differently: instead of changing the existing tree of nodes, they throw away and recreate the whole UI on every change.</p>\n<p>You'd need four things:</p>\n<ol>\n<li>A variable that holds the current state. I believe in your case that would be a list of tasks, e.g. <code>{taskName: "task name", done: true}</code>.</li>\n<li>Event handlers that respond to DOM events.</li>\n<li>A function that takes the current state and returns a new tree of DOM nodes, with event handlers attached.</li>\n<li>(Optional) A convenience function for wrapping event handlers. Each event handler changes state based on the current state and the event, and then replaces the old DOM with the new DOM created by function (3). This way defining an event handler is as simple as writing <code>(state, event) => doSomethingAndReturnNewState(...)</code>.</li>\n</ol>\n<p>This way you can store your whole application state in JS. Having a single source of truth makes it easier to keep track of all the possible states your application can be in.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T13:26:39.580",
"Id": "244108",
"ParentId": "244009",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244108",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T22:17:09.770",
"Id": "244009",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Simple to-do application"
}
|
244009
|
<p>A trie for handling strings for an autocomplete dictionary. This passes my fairly casual tests, though it's always possible that there are broken edge cases, but I'm mainly concerned about design and efficiency: is this a sensible way to implement this data structure? (In particular, is it sensible to do the insert method recursively?). It feels a little gnarly to me.</p>
<pre><code>struct Trie {
var root: Node
init() {
root = Node()
}
func search(_ word: String) -> Bool {
let letters = Array(word)
var curnode = root
for letter in letters {
guard let match = curnode.children.first(where: {(key, _) in
key == letter
})
else {
return false
}
curnode = match.value
}
if curnode.contained {
return true
}
return false
}
func remove(_ word: String) {
let letters = Array(word)
var curnode = root
for letter in letters {
if !curnode.children.contains(where: {(key, _) in
key == letter
}) {
break
} else {
curnode = curnode.children[letter]!
}
}
curnode.contained = false
}
func insert(_ letters: [Character], parent: Node) -> Node {
if letters.count == 1 {
let letter = letters[0]
if parent.children.contains(where: {(key, _) in
key == letter
}) {
let newNode = parent
newNode.children[letter]!.contained = true
return newNode
} else {
let newNode = Node(letter, final: true)
return newNode
}
} else {
let first = letters[0]
let rest = Array(letters.dropFirst())
if let subtree = parent.children.first(where: {(key, _) in
key == first
}) {
let newNode = Node(first, final: subtree.value.contained, kids: subtree.value.children)
newNode.children[rest[0]] = insert(rest, parent: newNode)
return newNode
} else {
let newNode = Node(first, final: false)
newNode.children[rest[0]] = insert(rest, parent: newNode)
return newNode
}
}
}
mutating func insert(_ word: String) {
let new_subtree = insert(Array(word), parent: root)
root.children[new_subtree.char!] = new_subtree
}
}
class Node {
var char: Character?
var children: [Character:Node]
var contained: Bool
init() {
char = nil
children = [:]
contained = false
}
init(_ c: Character, final: Bool) {
children = [:]
contained = final
char = c
}
init(_ c: Character, final: Bool, kids: [Character:Node]) {
children = kids
contained = final
char = c
}
}
</code></pre>
<p>Clarification edit: this isn't meant to be production ready, is only meant to be a concise and straightforward implementation of the data structure. So I intentionally left off checks for problem input; it should only be able to handle sensible inputs right now, where "sensible" means "input that someone using the data structure correctly to add, look for, and remove data would intentionally provide." So, not empty strings, removing stuff that isn't there, inserting the same thing twice, etc. etc.</p>
<p>The casual test cases I used, meant to represent sensible behavior, are:</p>
<pre><code>var testTrie = Trie()
testTrie.insert("cat")
testTrie.search("cat") // T
testTrie.search("car") // F
testTrie.insert("car")
testTrie.search("car") // T
testTrie.search("cat") // T
testTrie.search("ca") // F
testTrie.search("cad") // F
testTrie.search("carburetor") // F
testTrie.insert("carburetor")
testTrie.search("carburetor") // T
testTrie.search("car") // T
testTrie.search("cat") // T
testTrie.search("ca") // F
testTrie.remove("car")
testTrie.search("carburetor") // T
testTrie.search("car") // F
testTrie.search("cat") // T
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T13:05:45.323",
"Id": "479101",
"Score": "0",
"body": "I'm not trying to handle that kind of input yet---intentionally trying to keep it simple and avoid having to put in checks for empty strings, removing things that aren't there, double insertions, etc. etc. I'll edit to make that clear and also to include my test cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T22:44:25.540",
"Id": "479416",
"Score": "0",
"body": "On the Naming point, `contained` is not as familiar, to me, as `isFinal`, `isTerminating` or `isLeaf` for Trie implementations. According to the [API Design Guidelines](https://swift.org/documentation/api-design-guidelines/#naming): \"*Uses of Boolean methods and properties should read as assertions about the receive*\". \nAlternative implementation [here](https://github.com/raywenderlich/swift-algorithm-club/tree/master/Trie)."
}
] |
[
{
"body": "<h3>String traversal</h3>\n<p>At several places in your code you convert a string to an array of its characters in order to iterate over it:</p>\n<pre><code>let letters = Array(word)\nfor letter in letters {\n // ...\n}\n</code></pre>\n<p>These intermediate arrays are not needed. A Swift string is a <em>collection</em> of characters, so that you can iterate over it simply with</p>\n<pre><code>for letter in word {\n // ...\n}\n</code></pre>\n<h3>Dictionary access</h3>\n<p>In the <code>search()</code> method you look up the node for a character with</p>\n<pre><code>guard let match = curnode.children.first(where: {(key, _) in\n key == letter\n})\n else {\n return false\n}\ncurnode = match.value\n</code></pre>\n<p>Similar patterns are also in the other methods. This dictionary lookup can be simplified using a subscript:</p>\n<pre><code>guard let node = curnode.children[letter] else {\n return false\n}\ncurnode = node\n</code></pre>\n<h3>Returning boolean values</h3>\n<p>Code like</p>\n<pre><code>if someCondition {\n return true\n}\nreturn false\n</code></pre>\n<p>can always be simplified to</p>\n<pre><code>return someCondition\n</code></pre>\n<p>which is shorter and clearer. The search method then looks like this:</p>\n<pre><code>func search(_ word: String) -> Bool {\n var curnode = root\n for letter in word {\n guard let node = curnode.children[letter] else {\n return false\n }\n curnode = node\n }\n return curnode.contained\n}\n</code></pre>\n<h3>Removing non-existent strings</h3>\n<p>Removing a string which has never been inserted currently has undesired side effects:</p>\n<pre><code>var trie = Trie()\ntrie.insert("a")\ntrie.remove("ab")\nprint(trie.search("a")) // false\n</code></pre>\n<p>That is easy to fix: As soon as the traversal does not find a node for the next character it should <em>return</em> instead of setting <code>curnode.contained = false</code> on the last node encountered:</p>\n<pre><code>func remove(_ word: String) {\n var curnode = root\n for letter in word {\n guard let node = curnode.children[letter] else {\n return // <--- HERE\n }\n curnode = node\n }\n curnode.contained = false\n}\n</code></pre>\n<h3>Mutating (or not?) methods</h3>\n<p>The <code>mutating</code> keyword in</p>\n<pre><code>mutating func insert(_ word: String)\n</code></pre>\n<p>is not needed: <code>Node</code> is a reference type so that the properties of <code>root</code> can be modified without making the method mutating. For the same reason, the property can be declared as a constant:</p>\n<pre><code>struct Trie {\n let root: Node\n // ...\n}\n</code></pre>\n<h3>Use substrings!</h3>\n<p>The main insert method create a array of all characters:</p>\n<pre><code> let new_subtree = insert(Array(word), parent: root)\n</code></pre>\n<p>and the recursive helper methods repeatedly creates more arrays of the remaining characters:</p>\n<pre><code> let rest = Array(letters.dropFirst())\n</code></pre>\n<p>That is very inefficient. The better approach is that the helper method takes a <code>Substring</code> argument:</p>\n<pre><code>func insert(_ letters: Substring, parent: Node) -> Node\n</code></pre>\n<p>so that it can call itself with</p>\n<pre><code>let rest = letters.dropFirst()\ninsert(rest, parent: newNode)\n</code></pre>\n<p>This is called “slicing” in Swift and very efficient because the substrings share the element storage with the original string and no copies are made.</p>\n<p>The main insert method then calls the helper method with a substring comprising all its characters:</p>\n<pre><code>func insert(_ word: String) {\n let new_subtree = insert(word[...], parent: root)\n // ...\n}\n</code></pre>\n<h3>Simplify the insertion method (and the Node type)</h3>\n<p>I found the insertion code difficult to understand. It also has some problems (which you are already aware of):</p>\n<ul>\n<li>It is not possible to insert an empty string.</li>\n<li>It is not possible to insert the same string twice.</li>\n</ul>\n<p>To be honest: I cannot see which cases are handled correctly and which are not.</p>\n<p>What I also do not like is the <code>var char: Character?</code> property of <code>Node</code>. Apparently this is needed to insert a newly created subtree at the right position of the parent's <code>children</code> dictionary. But</p>\n<ul>\n<li>it introduces some redundancy,</li>\n<li>it is not clear in which cases it can be <code>nil</code> (only in the root node?),</li>\n<li>it requires forced unwrapping.</li>\n</ul>\n<p>Doing the insertion recursively is fine. But if we create new nodes <em>before</em> the recursive call with the rest of the string then everything becomes much simpler:</p>\n<pre><code>func insert(_ word: Substring, node: Node) {\n if let letter = word.first {\n if let nextnode = node.children[letter] {\n insert(word.dropFirst(), node: nextnode)\n } else {\n let newnode = Node()\n node.children[letter] = newnode\n insert(word.dropFirst(), node: newnode)\n }\n } else {\n node.contained = true\n }\n}\n\nfunc insert(_ word: String) {\n insert(word[...], node: root)\n}\n</code></pre>\n<p>The <code>char</code> property is not needed anymore, i.e. that type simplifies to</p>\n<pre><code>class Node {\n var children: [Character: Node] = [:]\n var contained: Bool = false\n}\n</code></pre>\n<p>More advantages:</p>\n<ul>\n<li>The recursion terminates when the string is empty, not when it is a single character. As a consequence, inserting an empty string works now.</li>\n<li>Inserting the same string twice works as well.</li>\n</ul>\n<p>The same can be done with iteration instead of recursion:</p>\n<pre><code>func insert(_ word: String) {\n var curnode = root\n for letter in word {\n if let nextnode = curnode.children[letter] {\n curnode = nextnode\n } else {\n let newnode = Node()\n curnode.children[letter] = newnode\n curnode = newnode\n }\n }\n curnode.contained = true\n}\n</code></pre>\n<p>That is a matter of taste, but it is shorter and makes even the substrings obsolete.</p>\n<h3>Naming</h3>\n<p>You use different naming conventions in your code:</p>\n<pre><code>curnode, newNode, new_subtree\n</code></pre>\n<p>The Swift naming convention is camelcase (upper camelcase for types, and lower camelcase for everything else):</p>\n<pre><code>currentNode, newNode, newSubtree\n</code></pre>\n<p>I would also prefer <code>char</code> or <code>character</code> over <code>letter</code>: A Swift string can contain arbitrary Unicode characters, not only “letters.”</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T14:37:19.730",
"Id": "479112",
"Score": "0",
"body": "This is incredibly helpful; thanks. I confess to that some of the stuff you identified is due to my shakiness on how swift value and reference types work---pretty sure the mutating keyword is in there just to shut up the compiler yelling at me :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T14:30:28.177",
"Id": "244051",
"ParentId": "244010",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244051",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T22:25:11.237",
"Id": "244010",
"Score": "2",
"Tags": [
"algorithm",
"strings",
"graph",
"swift",
"trie"
],
"Title": "Trie implementation for strings in Swift"
}
|
244010
|
<p>I am attempting to make an unbeatable Tic Tac Toe game using a simplified minimax algorithm. The code looks like this:</p>
<pre><code>private static int findBestMove(String[][] board, boolean comp) {
// comp returns true if the computer is the one looking for the best move
// findBestMove is always called by the program as findBestMove(board, true)
// since the computer is the only one that uses it
// If the board in its current state is a win for the
// player, return -1 to indicate a loss
if (playerWon(board)) return -1;
// If the board in its current state is a win for the
// computer, return 1 to indicate a win
if (compWon(board)) return 1;
// If the board in its current state is a tie
// return 0 to indicate a tie
if (tie(board)) return 0;
// Set the default possible outcome as the opposite of what
// the respective player wants
int bestPossibleOutcome = comp ? -1 : 1;
// Loop through the board looking for empty spaces
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
// Once an empty space is found, create a copy of the board
// with that space occupied by the respective player
if (board[i][j].equals(" ")) {
String[][] newBoard = new String[3][3];
for (int a = 0; a < 3; a++) {
System.arraycopy(board[a], 0, newBoard[a], 0, 3);
}
newBoard[i][j] = comp ? "O" : "X";
// Recursively call findBestMove() on this copy
// and see what the outcome is
int outCome = findBestMove(newBoard, !comp);
// If this is the computer's turn, and the outcome
// is higher than the value currently stored as the
// best, replace it
if (comp && outCome > bestPossibleOutcome) {
bestPossibleOutcome = outCome;
// r and c are instance variables that store the row
// and column of what the computer's next move should be
r = i;
c = j;
// If this is the player's turn, and the outcome
// is lower than the value currently stored as the
// best, replace it
} else if (!comp && outCome < bestPossibleOutcome) {
bestPossibleOutcome = outCome;
}
}
}
}
// Return the ultimate value deemed to be the best
return bestPossibleOutcome;
}
</code></pre>
<p>The idea is that after I run this program, the instance variables <code>r</code> and <code>c</code> should contain the row and column, respectively, of the computer's best move. However, the program only successfully prevents a loss about half the time, and I can't tell if the other half is luck, or if the program is actually working.</p>
<p>I am aware that the computer will respond to every scenario exactly the same way each game. That is fine.</p>
<p>In the event anyone would like to run the program, I have included the full class below:</p>
<pre><code>import java.util.Scanner;
public class TicTacToe {
private static int r;
private static int c;
private static void printBoard(String[][] board) {
System.out.println(" 0 1 2");
System.out.println("0 " + board[0][0] + " | " + board[0][1] + " | " + board[0][2] + " ");
System.out.println(" ---+---+---");
System.out.println("1 " + board[1][0] + " | " + board[1][1] + " | " + board[1][2] + " ");
System.out.println(" ---+---+---");
System.out.println("2 " + board[2][0] + " | " + board[2][1] + " | " + board[2][2] + " ");
}
private static boolean playerWon(String[][] board) {
return playerHasThreeInCol(board) || playerHasThreeInDiag(board) || playerHasThreeInRow(board);
}
private static boolean playerHasThreeInRow(String[][] board) {
for (int i = 0; i < 3; i++) {
if (board[i][0].equals(board[i][1]) && board[i][0].equals(board[i][2]) && board[i][0].equals("X")) return true;
}
return false;
}
private static boolean playerHasThreeInCol(String[][] board) {
for (int i = 0; i < 3; i++) {
if (board[0][i].equals(board[1][i]) && board[0][i].equals(board[2][i]) && board[0][i].equals("X")) return true;
}
return false;
}
private static boolean playerHasThreeInDiag(String[][] board) {
if (board[0][0].equals(board[1][1]) && board[0][0].equals(board[2][2]) && board[0][0].equals("X")) return true;
return board[0][2].equals(board[1][1]) && board[0][2].equals(board[2][0]) && board[0][2].equals("X");
}
private static boolean compWon(String[][] board) {
return compHasThreeInCol(board) || compHasThreeInDiag(board) || compHasThreeInRow(board);
}
private static boolean compHasThreeInRow(String[][] board) {
for (int i = 0; i < 3; i++) {
if (board[i][0].equals(board[i][1]) && board[i][0].equals(board[i][2]) && board[i][0].equals("O")) return true;
}
return false;
}
private static boolean compHasThreeInCol(String[][] board) {
for (int i = 0; i < 3; i++) {
if (board[0][i].equals(board[1][i]) && board[0][i].equals(board[2][i]) && board[0][i].equals("O")) return true;
}
return false;
}
private static boolean compHasThreeInDiag(String[][] board) {
if (board[0][0].equals(board[1][1]) && board[0][0].equals(board[2][2]) && board[0][0].equals("O")) return true;
return board[0][2].equals(board[1][1]) && board[0][2].equals(board[2][0]) && board[0][2].equals("O");
}
private static boolean tie(String[][] board) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j].equals(" ")) return false;
}
}
return true;
}
private static int findBestMove(String[][] board, boolean comp) {
if (playerWon(board)) return -1;
if (compWon(board)) return 1;
if (tie(board)) return 0;
int bestPossibleOutcome = comp ? -1 : 1;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j].equals(" ")) {
String[][] newBoard = new String[3][3];
for (int a = 0; a < 3; a++) {
System.arraycopy(board[a], 0, newBoard[a], 0, 3);
}
newBoard[i][j] = comp ? "O" : "X";
int outCome = findBestMove(newBoard, !comp);
if (comp && outCome > bestPossibleOutcome) {
bestPossibleOutcome = outCome;
r = i;
c = j;
} else if (!comp && outCome < bestPossibleOutcome) {
bestPossibleOutcome = outCome;
}
}
}
}
return bestPossibleOutcome;
}
private static void go() {
Scanner input = new Scanner(System.in);
String[][] board = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = " ";
}
}
printBoard(board);
for (int i = 0;; i++) {
if (i % 2 == 0) {
while (true) {
System.out.println("Enter position: ");
String position = input.nextLine();
int row, column;
try {
row = Integer.parseInt(position.substring(0, 1));
column = Integer.parseInt(position.substring(1, 2));
} catch (Exception e) {
System.out.println("Invalid entry. ");
continue;
}
if (row < 0 || row > 2 || column < 0 || column > 2) {
System.out.println("That position is not on the board. ");
continue;
}
if (!board[row][column].equals(" ")) {
System.out.println("That space is already taken. ");
continue;
}
board[row][column] = "X";
break;
}
} else {
System.out.println("\nMy move: ");
findBestMove(board, true);
board[r][c] = "O";
}
printBoard(board);
if (playerWon(board)) {
System.out.println("You win!");
break;
} else if (compWon(board)) {
System.out.println("I win!");
break;
} else if (tie(board)) {
System.out.println("Tie game");
break;
}
}
}
public static void main(String[] args) {
go();
}
}
</code></pre>
<p>I'm not asking for anyone to rewrite the whole thing for me, but if you can point out any obvious mistakes or point me in the right direction, that would be appreciated. I am also open to any suggestions or comments that you may have.</p>
|
[] |
[
{
"body": "<p>Welcome to Code Review. I run your code and the game works well, probably there is something you have to adjust about strategy, because it does not always choose the best move to win the match or at least tie. In your code there are some repetitions about method to check if the player or the computer wins like your code below:</p>\n<pre><code>private static boolean playerWon(String[][] board) {}\nprivate static boolean playerHasThreeInRow(String[][] board) {}\nprivate static boolean playerHasThreeInCol(String[][] board) {}\nprivate static boolean playerHasThreeInDiag(String[][] board) {}\nprivate static boolean compWon(String[][] board) {}\nprivate static boolean compHasThreeInRow(String[][] board) {}\nprivate static boolean compHasThreeInCol(String[][] board) {}\nprivate static boolean compHasThreeInDiag(String[][] board) {}\nprivate static boolean tie(String[][] board) {}\n</code></pre>\n<p>You created separated methods for the player and the computer doing the same thing while computer is also a player and the only difference between human player and computer is that one use <code>X</code> and the other use <code>O</code>. You can rewrite your methods to check if there is a winner in this way:</p>\n<pre><code>private final static String[] THREE_X = {"X", "X", "X"};\nprivate final static String[] THREE_O = {"O", "O", "O"};\n \nprivate static boolean areThreeInRow(String[][] board, String s) {\n String[] threeOfS = s.equals("X") ? THREE_X : THREE_O; \n \n return IntStream.range(0, 3)\n .mapToObj(i -> board[i])\n .anyMatch(row -> Arrays.equals(row, threeOfS));\n}\n \nprivate static boolean areThreeInColumn(String[][] board, String s) {\n String[] threeOfS = s.equals("X") ? THREE_X : THREE_O;\n \n return IntStream.range(0, 3)\n .mapToObj(j -> new String[] {board[0][j], board[1][j], board[2][j]})\n .anyMatch(column -> Arrays.equals(column, threeOfS));\n}\n \nprivate static boolean areThreeInDiagonal(String[][] board, String s) {\n String[] threeOfS = s.equals("X") ? THREE_X : THREE_O;\n String[] main = { board[0][0], board[1][1], board[2][2]}; \n String[] secondary = { board[0][2], board[1][1], board[2][0]};\n \n return Arrays.equals(main, threeOfS) || Arrays.equals(secondary, threeOfS);\n}\n \nprivate static boolean isTie(String[][] board) {\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (board[i][j].equals(" ")) return false;\n }\n }\n return true;\n}\n</code></pre>\n<p>I had created two static arrays <code>THREE_X</code> and <code>THREE_O</code> so if one of them is present on the board the match ends with a winner. I decided to add to the signature of the methods the parameter <code>s</code> representing the symbol (<code>X</code> or <code>O</code>) the player adopted. I decided to use the <code>IntStream</code> class and the function <code>anyMatch</code> to check if someone of the rows or the columns contains three equal symbols independently from the fact you are checking if human player or computer is the winner, passing from 7 different methods to only 4.</p>\n<p>I rewrite the methods <code>playerWon</code> and <code>compWon</code> in this way:</p>\n<pre><code>private static boolean symbolWon(String[][] board, String symbol) {\n return areThreeInColumn(board, symbol) ||\n areThreeInDiagonal(board, symbol) || \n areThreeInRow(board, symbol);\n}\n\nprivate static boolean playerWon(String[][] board) {\n String symbol = "X";\n \n return symbolWon(board, symbol);\n}\n \nprivate static boolean compWon(String[][] board) {\n String symbol = "O";\n \n return symbolWon(board, symbol);\n}\n</code></pre>\n<p>You can choose to modify these methods passing the symbol assigned to human player and computer.</p>\n<p>Minor changes: you have to close the <code>Scanner</code> resource to avoid memory leak : use the <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try with resources</a> statement. The followind code :</p>\n<pre><code>public static void main(String[] args) {\n go();\n}\n</code></pre>\n<p>It is correct and reminds to python, but it would better directly include the Scanner and its code inside the <code>main</code> .</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T13:30:12.370",
"Id": "479106",
"Score": "0",
"body": "Thanks for answering and offering some suggestions. Do you see anything in the ```findBestMove()``` method in particular that can be causing the issue?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T14:58:48.213",
"Id": "479113",
"Score": "1",
"body": "@ap You are welcome. Looking at the code, at a first view it seems me that tie is not considered as the possible best outcome, so it is always excluded in favour of an impossible victory. This site hosts versions of tic tac toe minimax, you could check them to see in which mode their ai version is different from yours."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T18:14:26.570",
"Id": "479129",
"Score": "0",
"body": "I thought that by writing ```if (comp && outCome > bestPossibleOutcome)``` I was acknowledging ties since 0 is greater than -1. What do you mean by impossible victory?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T20:14:14.060",
"Id": "479136",
"Score": "1",
"body": "I mean that it seems me that computer always tries to win as the first priority instead of avoiding not to loose; it should check before if there one position that not checked brings defeat and check it, if there is no such position choose the most advantageous one."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T13:15:39.047",
"Id": "244043",
"ParentId": "244011",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T23:15:51.187",
"Id": "244011",
"Score": "4",
"Tags": [
"java",
"beginner",
"algorithm",
"recursion",
"tic-tac-toe"
],
"Title": "Minimax based Tic Tac Toe"
}
|
244011
|
<p>I have difficulties when sometimes a game client sends a list of packet in the same buffer, where it is split before processing. The biggest problem is when any packets don't come complete. For example; all packets have the same size, of 1000 bytes, and then we receive a list of packets of only 2500 bytes. Say the third packet came incomplete, I have difficulty filling this incomplete packet. I'm not sure if the way I'm doing the split buffer are really correct.</p>
<p>I'm not sure if doing right way below is what I'm using.</p>
<pre><code>public static async void ProcessarAsync(Client client, byte[] buffer) // process recv packets
{
try{
int cc = buffer[0];
int id = BitConverter.ToInt16(buffer, 1);
int length = BitConverter.ToInt32(buffer, 4);
//VERIFY IF THE FIRST PACKET BELONG THE GAME
if (client != null)
{
if (client.PrimeiroPacote)
{
if (id != SecureConfig.PrimeiroPacoteMap)
{
if (client != null) client.Close();
return;
}
}
}
try
{
if (client != null)
{
client.delayCheck = DateTime.Now;
//ANALISA O PACOTE E SEPARA CASO HAJA MAIS DE 1 PACOTE EM UM MESMO PACOTE
//ANALISE THE PACKAGE AND SPLIT IF HAVE MORE THEN 1 PACKETS IN SAME PACKET
if (buffer.Length > length || length > buffer.Length || length <= 0)//180
{
//FAZ A SEPARAÇÃO DOS PACOTES
//MAKE THE PACKET SEPARATION
List<byte[]> datas = await SepararData.Separar(buffer,client);
bool fail = false;
bool sucess = false;
//Faz a junção dos pacotes ou envia para o handler
//Merge packets or send to handler
while (datas.Count > 0)
{
//VERIFICA SE O CLIENT FOI DISPENSADO
//VERIFY IF THE CLIENT WAS DISPOSED
if (client == null || client != null && client.Dispensado) break;
//PACOTE COMPLETO (OU AGUARDANDO PARA SER COMPELTADO)
// PACKET FULL ( OR WAITING TO BE COMPLETED)
byte[] maindata = null;
//PROCESSO DE JUNTAR OS PACOTES CASO NÃO ESTEJA COMPLETO
//PROCESS OF UNITS THE PACKETS IF NOT COMPLET
if (client.packetListEncrypted.Count > 0)
{
//PEGA O PRIMEIRO PACOTE ARMAZENADO PARA SER PROCESSADO
//GET THE FIRST PACKET STORED TO BE PROCESSED
byte[] data = (byte[])client.packetListEncrypted.Dequeue();
if (data == null)
{
continue;
}
//PEGA O TAMANHO DO PACOTE QUANDO EXISTE
//GET THE LENGTH OF THE PACKET WHEN EXIST
length = BitConverter.ToInt32(data, 4);
if (length <= 0)
{
fail = true;
break;
}
//ENQUANTO O TAMANHO DESSE TRECHO DE PACOTE FOR MENOR QUE O TAMANHO TOTAL
//WHILE THE SIZE OF THIS PACKAGE SECTION IS LESS THAN THE TOTAL SIZE
while (data.Length < length)
{
//VERIFICA SE O CLIENT FOI DISPENSADO
//VERIFY IF THE CLIENT WAS DISPOSED
if (client == null || client != null && client.Dispensado) break;
//VERIFICA SE EXISTE PARTES SEPARADAS
//VERIFY IF EXIST PARTS SEPARATE
if (datas.Count > 0)
{
//ADICIONA A DADO AO PACOTE PRINCIPAL
//ADD DATA TO MAIN PACKAGE
byte[] maindata2 = datas[0];
datas.RemoveAt(0);
Array.Resize(ref data, data.Length + maindata2.Length);
Buffer.BlockCopy(maindata2, 0, data, ((data.Length - maindata2.Length)), maindata2.Length);
}
else
{
//DEVOLVE O TRECHO PARA A LISTA
//RETURN THE SECTION TO THE LIST
fail = true;
client.packetListEncrypted.Enqueue(data);
break;
}
}
//CASO O TAMANHO SEJA EQUIVALENTE
// IF SIZE IS EQUIVALENT
if (data.Length == length)
{
//PACOTE "COMPLETO"
//COMPLETE PACKAGE"
sucess = true;
maindata = data;
}
else if(data.Length < length)
{
//VERIFICA SE ESSE TRECHO JÁ SE ENCONTRA NA LISTA
//CASO NÃO ESTIVER, ADICIONAR
// CHECK IF THIS SECTION IS ALREADY IN THE LIST
// IF NOT, ADD
if (!client.packetListEncrypted.Contains(data))
client.packetListEncrypted.Enqueue(data);
fail = true;
}
}
//CASO AINDA TENHA TRECHOS AGUARDANDO (TENTA EXTRAIR OS TRECHOS NOVAMENTE)
// IF STILL HAVE A SECTION WAITING (TRY TO EXTRACT THE SECTIONS AGAIN)
if (datas.Count > 0)
{
//E O PACOTE AINDA NÃO SE ENCONTRA COMPLETO
//AND THE PACKAGE IS NOT YET COMPLETE
if (!sucess)
{
//PEGA O PRIMEIRO PACOTE DA LISTA
//GET THE FIRST PACKAGE FROM THE LIST
maindata = datas[0];
datas.RemoveAt(0);
//PEGA O TAMANHO DO PACOTE QUANDO EXISTE
//GET THE SIZE OF PACKET WHEN EXIST
length = BitConverter.ToInt32(maindata, 4);
//ENQUANTO O TAMANHO DESSE TRECHO DE PACOTE FOR MENOR QUE O TAMANHO TOTAL
//WHILE THE SIZE OF THIS PACKAGE SECTION IS LESS THAN THE TOTAL SIZE
while (maindata.Length < length)
{
//VERIFICA SE O CLIENT FOI DISPENSADO
//VERIFY IF THE CLIENT WAS DISPOSED
if (client == null || client != null && client.Dispensado) break;
//LOOP VERIFICANDO SE HÁ MAIS PARTES SEPARADAS
// LOOP CHECKING IF THERE ARE MORE SEPARATE PARTS
while (datas.Count > 0)
{
//VERIFICA SE O CLIENT FOI DISPENSADO
//VERIFY IF THE CLIENT WAS DISPOSED
if (client == null || client != null && client.Dispensado) break;
//ADICIONA A DADO AO PACOTE PRINCIPAL
//ADD DATA TO MAIN PACKAGE
byte[] maindata2 = datas[0];
datas.RemoveAt(0);
Array.Resize(ref maindata, maindata.Length + maindata2.Length);
Buffer.BlockCopy(maindata2, 0, maindata, ((maindata.Length - maindata2.Length)), maindata2.Length);
}
//DEFINE O TAMANHO DO PACOTE PRINCIPAL
//DEFINE THE SIZE OF MAIN PACKAGE
length = BitConverter.ToInt32(maindata, 4);
//CASO O TAMANHO NÃO SEJA IGUAL AO PACOTE PRINCIPAL
// IF THE SIZE IS NOT EQUAL TO THE MAIN PACKAGE
if (maindata.Length < length || length < 0)
{
//VERIFICA SE ESSE TRECHO JÁ SE ENCONTRA NA LISTA
//CASO NÃO ESTIVER, ADICIONAR
// CHECK IF THIS SECTION IS ALREADY IN THE LIST
// IF NOT, ADD
if (!client.packetListEncrypted.Contains(maindata))
client.packetListEncrypted.Enqueue(maindata);
fail = true;
break;
}
}
//VERIFICA SE ESSE TRECHO HÁ ALGUM DADO PARA RETORNA-LO PARA A LISTA
// CHECK IF THERE IS ANY DATA IN THIS SECTION TO RETURN IT TO THE LIST
if (length <= 0)
{
//VERIFICA SE ESSE TRECHO JÁ SE ENCONTRA NA LISTA
//CASO NÃO ESTIVER, ADICIONAR
// CHECK IF THIS SECTION IS ALREADY IN THE LIST
// IF NOT, ADD
if (!client.packetListEncrypted.Contains(maindata))
client.packetListEncrypted.Enqueue(maindata);
fail = true;
break;
}
}
}
//NÃO FOI POSSÍVEL RECUPERAR O PACOTE
// IT WASN'T POSSIBLE TO RECOVER THE PACKAGE
if (fail)
{
break;
}
//NÃO FOI POSSÍVEL RECUPERAR O PACOTE
// IT WASN'T POSSIBLE TO RECOVER THE PACKAGE
if (maindata == null) break;
//O PACOTE FOI RECEBIDO COM SUCESSO
// THE PACKAGE WAS SUCCESSFULLY RECEIVED
//PARTE DE DECRIPTAR O PACOTE CASO ESTEJA HABILITADO
// PART OF DECRIPTING THE PACKAGE IF IT IS ENABLED
if (Server.AtivarEncriptacao && client.AtivarEncriptacao)
{
Crypto crypto = new Crypto();
Int32 packetSize = BitConverter.ToInt32(maindata, 0x04);
if (packetSize <= 0) packetSize = maindata.Length;
if (maindata.Length < packetSize)
{
Array.Resize(ref maindata, packetSize);
}
else if (maindata.Length > packetSize)
{
Array.Resize(ref maindata, packetSize);
}
byte[] csSucks = new byte[packetSize - 8];
Array.Copy(maindata, 8, csSucks, 0, packetSize - 8);
crypto.crypto(ref csSucks, packetSize - 8, 1);
Array.Copy(csSucks, 0, maindata, 8, packetSize - 8);
//Log.SalvarF(client, "Bugs_Map", "ULTIMO RECEBIDO NaO SEPARADO", "DEPOIS DECRYPT:\n" + Digimon_Battle_Online.Packets.Packet.Visualize(buffer, true), true);
}
//ENVIA PARA A LISTA DE PACOTES PARA SER PROCESSADO
// SEND TO PACKAGE LIST TO BE PROCESSED
client.packetListRecv.Enqueue(maindata);
}
//LIMPA A LISTA DE PACOTES, JÁ FOI ARMAZENADO EM OUTRO OBJETO EM UMA OUTRA LISTA
// CLEAR THE PACKAGE LIST, IT HAS ALREADY BEEN STORED IN ANOTHER OBJECT IN ANOTHER LIST
for (int i = 0; i < datas.Count; i++)
{
datas[i] = null;
}
datas.Clear();
}
//CASO O TAMANHO DO PACOTE SEJA IGUAL E TEM A HEADER DO JOGO
// IF THE PACKAGE SIZE IS EQUAL AND HAS THE GAME HEADER
else if (cc == 0xCC)
{
//PARTE DE DECRIPTAR O PACOTE CASO ESTEJA HABILITADO
// PART OF DECRIPTING THE PACKAGE IF IT IS ENABLED
if (Server.AtivarEncriptacao && client.AtivarEncriptacao)
{
Crypto crypto = new Crypto();
Int32 packetSize = BitConverter.ToInt32(buffer, 0x04);
if (packetSize <= 0) packetSize = buffer.Length;
if (buffer.Length < packetSize)
{
Array.Resize(ref buffer, packetSize);
}
else if (buffer.Length > packetSize)
{
Array.Resize(ref buffer, packetSize);
}
byte[] csSucks = new byte[packetSize - 8];
Array.Copy(buffer, 8, csSucks, 0, packetSize - 8);
crypto.crypto(ref csSucks, packetSize - 8, 1);
Array.Copy(csSucks, 0, buffer, 8, packetSize - 8);
}
//ENVIA PARA A LISTA DE PACOTES PARA SER PROCESSADO
// SEND TO PACKAGE LIST TO BE PROCESSED
client.packetListRecv.Enqueue(buffer);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Erro ao processar pacote Map: {0}", ex);
if (client.Login.Length > 0)
{
Log.Salvar(client, "Map", "Processar Pacote", string.Format("login: {0} erro ao processar pacote! {1}", client.Login, ex), false);
Log.Salvar(client, "Map", "Processar Pacote", Packet.Visualize(buffer, false), false);
}
else
{
Log.Salvar(client, "Map", "Processar Pacote", Packet.Visualize(buffer, false), false);
}
client.Close();
//Handler(client, buffer);
}
}
catch (Exception e)
{
Console.WriteLine("Erro ProcessarAsync " + e.Message);
}
}
</code></pre>
<hr />
<pre><code>using Common.Entity.Clients;
using Common.Network.Packet;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Common.Utils
{
public class SepararData
{
public static Task<List<byte[]>> Separar(byte[] data, Client client)
{
var t = Task.Run(() =>
{
bool encontrado = false;
bool fail = false;
List<byte[]> lista = new List<byte[]>();
//try
//{
int index = data[0];
int header = data[1];
int tamanho = BitConverter.ToInt32(data, 4);
int otamanho = tamanho;
if (tamanho == data.Length)
{
lista.Add(data);
return lista;
}
PacketLog.Write(client, "Recv", data[1].ToString("X2") + "[" + (int)data[1] + "]", Packet.Visualize(data, false), client.Tamer != null && client.Tamer.Nome.Length > 0 ? true : false);
// await Log.SalvarPacoteTamanhoAsync("PACKET-H-" + header + "-L-" + tamanho, Packet.Visualize(data, true));
for (int i = 0; i < data.Length; i += tamanho)
{
encontrado = false;
if (i >= data.Length)
{
//Console.WriteLine("DATA INVALIDA HEADER: {0} LENGHT: {1}", data[0], otamanho);
break;//ativar dps
}
if (i+1 >= data.Length)
{
//Console.WriteLine("DATA INVALIDA HEADER: {0} LENGHT: {1}", data[0], otamanho);
break;//ativar dps
}
if (i + 4 >= data.Length)
{
//Console.WriteLine("DATA INVALIDA HEADER: {0} LENGHT: {1}", data[1], otamanho);
break;//ativar dps
}
if (i + 8 >= data.Length)
{
//Console.WriteLine("DATA INVALIDA HEADER: {0} LENGHT: {1}", data[1], otamanho);
break;//ativar dps
}
index = data[i];
header = data[i + 1];
tamanho = BitConverter.ToInt32(data, i+4);
if (tamanho <= 0)
{
//Console.WriteLine("DATA INVALIDA HEADER T<0: {0} LENGHT: {1}", data[i + 1], tamanho);
tamanho = data.Length - i;
fail = true;
}
if (tamanho >= data.Length)
{
//Console.WriteLine("DATA INVALIDA HEADER T>D: {0} LENGHT: {1}", data[i + 1], tamanho);
tamanho = data.Length - i;
fail = true;
//break;
}
//header = BitConverter.ToInt16(data, 1);
if (i + tamanho > data.Length)
{
//Console.WriteLine("DATA INVALIDA HEADER I>T: {2}: {0} LENGHT: {1}", data[i + 1], tamanho, nome);
tamanho = data.Length - i;
fail = true;
//break;
//continue;
}
if (index > 0)
{
//Console.WriteLine("DATA INVALIDA HEADER INDEX!=0xCC: {2}: {0} LENGHT: {1}", header, tamanho, nome);
}
if (!fail && header <= 255 && header >= 0)
{
encontrado = true;
if (tamanho >= 8)
{
byte[] b = new byte[tamanho];
Buffer.BlockCopy(data, i, b, 0, tamanho);
lista.Add(b);
}
}
//if (!encontrado && fail)
//{
// /*byte[] b = new byte[tamanho];
// Buffer.BlockCopy(data, i, b, 0, tamanho);
// lista.Add(b);*/
// byte[] b = new byte[data.Length];
// Buffer.BlockCopy(data, 0, b, 0, data.Length);
// lista.Add(b);
//}
else if(!encontrado&&fail)
{
List<int> remove = new List<int>();
List<int> zeros = new List<int>();
for(int z=data.Length-1;z>0;z--)
{
if ((z - 3) < 0) break;
if (data[z] == 0x00 &&
data[z - 1] == 0x00 &&
data[z - 2] == 0x00 &&
data[z - 3] == 0x00)
{
z -= 3;
zeros.Add(z);
}
}
if (zeros.Count > 0)
{
}
int lastZero = -1;
int count = 0;
bool retirar = false;
foreach (int b in zeros)
{
if (lastZero == -1) lastZero = b;
else if (lastZero - 4 == b)
{
lastZero = b;
count++;
}
else
{
remove.Add(b);
}
}
foreach (int b in remove)
{
zeros.Remove(b);
}
if (count >= 4) retirar = true;
if (retirar && zeros.Count > 0)
{
Array.Resize(ref data, data.Length - zeros[zeros.Count-1]);
remove.Clear();
zeros.Clear();
remove = null;
zeros = null;
}
lista.Add(data);
break;
}
//}
//catch { break; }
}
//Console.WriteLine("Tamanho Max:{0}", lista.Count);
return lista;
});
return t;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T19:39:34.167",
"Id": "479135",
"Score": "0",
"body": "i hate that's winsock does packets fragmentation"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T00:39:55.500",
"Id": "244014",
"Score": "1",
"Tags": [
"c#",
"programming-challenge",
"game",
"async-await",
"server"
],
"Title": "ReadAsync: Continuously reads stream and spits out Packets and Fill incomplete Packets"
}
|
244014
|
<p>I have these strings:</p>
<pre><code>)hello(
this has ]some text[
flip }any{ brackets
even with )))]multiple[((( brackets
</code></pre>
<p>As you can see, the brackets are all in the wrong direction.</p>
<p>I have a function called <code>flipBracketsDirection()</code> to handle each scenario. Here is an example of input and output of the above strings:</p>
<pre><code>flipBracketsDirection(')hello(');
// should return: (hello)
flipBracketsDirection('this has ]some text[');
// should return: this has [some text]
flipBracketsDirection('flip }any{ brackets');
// should return: flip {any} brackets
flipBracketsDirection('even with )))]multiple[((( brackets');
// should return: even with ((([multiple]))) brackets
</code></pre>
<p><strong>Note</strong>: The direction is flipped at <strong>all</strong> times. So this is fine too:</p>
<pre><code>flipBracketsDirection('flip (it) anyway');
// should return: flip )it( anyway
</code></pre>
<p>Here is my solution.</p>
<pre><code>function flipBracketsDirection(str: string) {
return str
// flip () brackets
.replace(/\(/g, 'tempBracket').replace(/\)/g, '(').replace(/tempBracket/g, ')')
// flip [] brackets
.replace(/\[/g, 'tempBracket').replace(/\]/g, '[').replace(/tempBracket/g, ']')
// flip {} brackets
.replace(/\{/g, 'tempBracket').replace(/\}/g, '{').replace(/tempBracket/g, '}')
;
}
</code></pre>
<p>Is this the best way to create this function?</p>
|
[] |
[
{
"body": "<p>Your function seems to work fine, but you can condense it a bit by search for all bracket types in one regex replace with the following pattern:</p>\n<pre><code>/[\\(\\)\\[\\]\\{\\}]/g\n</code></pre>\n<p>and then use the <code>replace</code> function that takes a replace function as argument:</p>\n<pre><code>const brs = "()({}{[][";\nfunction flipBracketsDirection(str) {\n return str.replace(/[\\(\\)\\[\\]\\{\\}]/g, br => brs[brs.indexOf(br) + 1]);\n}\n</code></pre>\n<p><code>brs</code> holds all the replaceable brackets with the opening brackets twice, so <code>brs[brs.indexOf(')') + 1]</code> finds <code>'('</code> as the next char in <code>brs</code>;</p>\n<p>You could also let <code>brs</code> be an object like:</p>\n<pre><code>const brs =\n{\n "(": ')',\n ")": '(',\n "{": '}',\n "}": '{',\n "[": ']',\n "]": '[',\n};\n</code></pre>\n<p>and then cquery it as:</p>\n<pre><code>function flipBracketsDirection(str) {\n return str.replace(/[\\(\\)\\[\\]\\{\\}]/g, br => brs[br]);\n}\n</code></pre>\n<p>Your version actually query the string nine times, where the above only iterates it once.</p>\n<p>As an alternative to the 'sophisticated' <code>brs</code> dictionary-solution, you could just create a function with a switch statement:</p>\n<pre><code>function swapBracket(br) {\n switch (br) {\n case '(': return ')';\n case ')': return '(';\n case '{': return '}';\n case '}': return '{';\n case '[': return ']';\n case ']': return '[';\n }\n}\n</code></pre>\n<p>And call that instead, this way:</p>\n<pre><code>function flipBracketsDirection(str: string) {\n return str.replace(/[\\(\\)\\[\\]\\{\\}]/g, swapBracket);\n}\n\nflipBracketsDirection('}hello{');\n// will return {hello}\n</code></pre>\n<hr />\n<p>Your tests cases could also be simplified, so it is easier to maintain - for instance like:</p>\n<pre><code> let strs = [\n ')hello(',\n 'this has ]some text[',\n 'flip }any{ brackets',\n 'even with )))]multiple[((( brackets'\n ];\n\n for (let s of strs) {\n let t = flipBracketsDirection(s);\n console.log(t);\n console.log(flipBracketsDirection(t));\n console.log("");\n }\n</code></pre>\n<hr />\n<p>Both the above suggestions should conform to the DRY principle.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T13:16:38.000",
"Id": "479102",
"Score": "3",
"body": "What's you're opinion on `brs = '(){}[]'`, `brs[brs.indexOf(br) ^ 1]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T13:20:51.067",
"Id": "479103",
"Score": "3",
"body": "Too clever for me @Peilonrayz. Sure, it works, but coming back to that in a month..?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T13:23:24.553",
"Id": "479104",
"Score": "3",
"body": "@Gerrit0 I've never heard anyone say xor is 'too clever' before."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T13:26:14.290",
"Id": "479105",
"Score": "0",
"body": "@Peilonrayz: That's indeed clever, I din't think in that direction - I thought my solution was clever. +1 from me :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T21:55:07.033",
"Id": "479146",
"Score": "0",
"body": "What wonderful ways to solve this! I think all of you are clever. What does ^ do? I couldn't find anything on google"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T23:22:36.590",
"Id": "479154",
"Score": "1",
"body": "@Elron [bitwise XOR](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T18:28:56.550",
"Id": "479266",
"Score": "1",
"body": "@Peilonrayz: For what it's worth, I find your version much clearer, and less error-prone. The next dev might not notice that the brackets need to be written 3 times otherwise, and would simply add `brs = \"<>()({}{[][\"`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T22:56:35.240",
"Id": "479290",
"Score": "1",
"body": "@EricDuminil I was really confused by the `+ 1` at first. But meh you can't win them all ;)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T05:04:13.617",
"Id": "244021",
"ParentId": "244018",
"Score": "18"
}
},
{
"body": "<p>It may seem unlikely but it is not impossible for an input string to contain <code>tempBracket</code> so a solution that doesn't involve adding and replacing that string would be ideal.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function flipBracketsDirection(str) {\n return str\n // flip () brackets\n .replace(/\\(/g, 'tempBracket').replace(/\\)/g, '(').replace(/tempBracket/g, ')')\n\n // flip [] brackets\n .replace(/\\[/g, 'tempBracket').replace(/\\]/g, '[').replace(/tempBracket/g, ']')\n\n // flip {} brackets\n .replace(/\\{/g, 'tempBracket').replace(/\\}/g, '{').replace(/tempBracket/g, '}')\n ;\n}\nconsole.log(flipBracketsDirection(')will tempBracket get replaced?('))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The answer by <a href=\"https://codereview.stackexchange.com/users/73941/henrik-hansen\">@Henrik</a> already suggests using a single regular expression to replace any characters in the group of brackets.</p>\n<p>A mapping of characters seems an ideal solution in terms of performance. The mapping can be frozen using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\" rel=\"nofollow noreferrer\"><code>Object.freeze()</code></a> to avoid alteration.</p>\n<pre><code>const BRACKET_MAPPING = Object.freeze({\n "(": ')',\n ")": '(',\n "{": '}',\n "}": '{',\n "[": ']',\n "]": '[',\n});\nconst mapBracket = (bracket: string) => BRACKET_MAPPING[bracket];\nconst flipBracketsDirection = (str: string) => str.replace(/[\\(\\)\\[\\]\\{\\}]/g, mapBracket);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T18:27:19.453",
"Id": "479265",
"Score": "0",
"body": "This looks clear and concise. Would it be possible to generate the regex from the keys of `BRACKET_MAPPING`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T18:32:09.127",
"Id": "479267",
"Score": "0",
"body": "yes- likely with the [Regexp constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Constructor)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T14:28:26.600",
"Id": "244050",
"ParentId": "244018",
"Score": "8"
}
},
{
"body": "<p>This is an <a href=\"https://stackoverflow.com/a/62426116/15472\">answer that I posted</a> to the original question on StackOverflow. It does away with regular expressions entirely, and uses a similar case-statement to the one suggested in <a href=\"https://codereview.stackexchange.com/a/244021/140466\">@Henrik's answer</a></p>\n<p>The original code performs 6 regular expression substitutions (which require 1 pass each), and fails on strings that contain the text <code>tempBracket</code> (as noted by @Kaiido in comments to the StackOverflow question).</p>\n<p>This should be quicker because it makes a single pass, and requires no regular expressions at all. If all characters are ASCII, the <code>flip</code> function could be rewritten to use a look-up table, which would make it branch-free and potentially even faster.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function flipBracketsDirection(str) {\n function flip(c) {\n switch (c) {\n case '(': return ')';\n case ')': return '(';\n case '[': return ']';\n case ']': return '[';\n case '{': return '}';\n case '}': return '{';\n default: return c;\n }\n }\n return Array.from(str).map(c => flip(c)).join('');\n} \n\n// testcases\nlet test = (x) => console.log(flipBracketsDirection(x));\ntest('flip (it) anyway');\ntest(')hello(');\ntest('this has ]some text[');\ntest('flip }any{ brackets');\ntest('even with )))]multiple[((( brackets');</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T13:56:09.790",
"Id": "479210",
"Score": "0",
"body": "Can you also post this in [a new post](https://codereview.stackexchange.com/questions/ask), with the tag [tag:rags-to-riches]? I have some thoughts ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T14:20:50.283",
"Id": "479215",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ you hereby have my permission to post my answer as a question to then answer it with your answer :-). I'll be happy to look at it (answer the comment so that I know to look)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T14:28:05.330",
"Id": "479217",
"Score": "0",
"body": "I wouldn't really be able to (morally) post your code in a question because I wouldn't be able to answer \"yes\" to all the questions in the [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic) page... (hint/protip: we can both gain more rep that way)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T14:58:45.283",
"Id": "479224",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ Then post the good code to get feedback for it! Regarding posting my code, the licensing is there (it is already on the site, and thus CC); and the moral aspect is also there (explicit permission in writing!). If you frame it as a performance competition, with regex vs split-join vs what-have-you, it would be actually quite interesting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T00:40:02.320",
"Id": "479300",
"Score": "2",
"body": "How bad is the performance hit of converting from string to array and back again, compared to regular expression replacement? I may be mistaken, but it seems like this would be more expensive than a simple regex"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T00:59:17.340",
"Id": "479304",
"Score": "3",
"body": "It seems like the regex wins out by 5-10% (https://jsperf.com/reverse-brackets)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T09:08:16.847",
"Id": "244098",
"ParentId": "244018",
"Score": "6"
}
},
{
"body": "<p>One for the fun of it</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const flipBrackets = BracketFlipper();\n[ ')hello(', \n'this has ]some text[',\n'flip }any{ brackets',\n'even with )))]multiple[((( brackets',\n'flip (it) anyway',\n'>Pointy stuff<', \n'/slashed\\\\'].forEach(s => console.log(flipBrackets(s)));;\n\nfunction BracketFlipper() {\n const bracks = \"(),{},[],<>,\\\\\\/\".split(\",\");\n const brackets = [\n ...bracks, \n ...bracks.reverse()\n .map(v => [...v].reverse().join(\"\")) ]\n .reduce( (a, v) => ({...a, [v[0]]: v[1] }), {} );\n const re = new RegExp( `[${Object.keys(brackets).map(v => `\\\\${v}`).join(\"\")}]`, \"g\" );\n return str => str.replace(re, a => brackets[a]);\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console-wrapper { top: 0; max-height: 100% !important; }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T08:23:49.277",
"Id": "244154",
"ParentId": "244018",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244021",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T03:26:33.157",
"Id": "244018",
"Score": "8",
"Tags": [
"javascript",
"strings",
"regex",
"typescript"
],
"Title": "JavaScript function that flips brackets direction"
}
|
244018
|
<p>I'm doing some toy problems <a href="https://github.com/togakangaroo/daily-programmer/tree/master/missing-ranges#more-idomatic-racket" rel="nofollow noreferrer">in a variety of languages</a> and wanted to do the following in Racket Lisp.</p>
<hr />
<p>Given a sorted integer array <code>nums</code>, where the range of elements are in the inclusive range <code>[lower, upper]</code>, return its missing ranges.</p>
<pre><code>0, 1, 3, 50, 75
</code></pre>
<p>Lower: <code>0</code></p>
<p>Upper: <code>99</code></p>
<p>Expected Output:</p>
<pre><code>["2", "4->49", "51->74", "76->99"]
</code></pre>
<hr />
<p>As you can see on the linked page I had to take two whacks at it but eventually came up with the following. How does it look? Is it idiomatic? Could I have done certain things far better?</p>
<pre><code>(define (missing-ranges nums lower upper)
(in-generator
(define (yield-missing-range current num)
(yield (if (eq? num (add1 current))
(~a current)
(~a current "->" (sub1 num)))))
(let recur ([remaining-nums nums]
[current lower])
(match remaining-nums
[(cons num rest-nums) (if (< current num)
(begin
(yield-missing-range current num)
(recur rest-nums num))
(recur rest-nums (add1 current)))]
['() (cond [(<= current upper)
(yield-missing-range current (add1 upper))])]))))
</code></pre>
|
[] |
[
{
"body": "<p>Your solution seems to me quite complex, with iterations, recursions, and the use of <code>match</code>.</p>\n<p>Here is an alternative version with a simple linear recursion, where the result is given with lists and not with strings.</p>\n<pre><code>(define (missing-ranges nums lower upper)\n (cond ((> lower upper) '())\n ((null? nums) (list (list lower upper)))\n ((= lower (car nums)) (missing-ranges (cdr nums) (+ lower 1) upper))\n ((= (car nums) (+ 1 lower)) (cons (list lower) (missing-ranges nums (+ lower 1) upper)))\n (else (cons (list lower (- (car nums) 1)) (missing-ranges (cdr nums) (+ (car nums) 1) upper)))))\n\n(missing-ranges '(0 1 3 50 75) 0 99)\n'((2) (4 49) (51 74) (76 99))\n\n(missing-ranges '(8) 0 99)\n'((0 7) (9 99))\n\n(missing-ranges '() 0 99)\n'((0 99))\n\n(missing-ranges '(3 9 88 99) 0 99)\n'((0 2) (4 8) (10 87) (89 98))\n\n(missing-ranges '(0 99) 0 99)\n'((1 98))\n\n(missing-ranges '(1 2 3) 1 3)\n'()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T13:40:11.187",
"Id": "479108",
"Score": "0",
"body": "Yeah, the string thing was an original requirement (though I control the requirements). I suppose taking those output lists and stringifying could just be a separate step. I also wanted to use generators specifically, though I think that should still be possible with your version"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T07:51:35.803",
"Id": "244024",
"ParentId": "244020",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244024",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T04:49:05.907",
"Id": "244020",
"Score": "1",
"Tags": [
"lisp",
"racket"
],
"Title": "Racket code to find missing ranges"
}
|
244020
|
<p>Here is my code that check and upload an image to my website.</p>
<p>Is this code really secure against uploading of malicious codes?</p>
<p>Anything I have to add to this code to make it more secure?</p>
<p>I have also blocked execution of PHP in images folder using <code>php_flag engine off</code> in .htaccess of images folder, I can also move images folder out of the public_html (root) folder.</p>
<pre><code> <?php
if(isset($_POST['submit'])){
// permenant variabes for upload
$target_dir = "./images/";
$allowed = array('jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif');
$maximumsize=5000000000;
//variables form file
$filetempname=$_FILES["image"]["tmp_name"];
$fileinfo = new finfo(FILEINFO_MIME_TYPE);
$filemime = $fileinfo->file($_FILES['image']['tmp_name']);
//check if error is set
if(!isset($_FILES['image']['error']) ){
echo 'Invalid upload.';
die();
}
// check formultiple uploads and block
elseif(is_array($_FILES['image']['error'])){
echo 'Only one file allowed.';
die();
}
//check for any upload error
elseif($_FILES['image']['error']===0){
// check image size
if($_FILES["image"]["size"] > $maximumsize){
echo 'File size exceed maximum size.';
die();
}
$ext = array_search($filemime, $allowed, true);
if(false !== $ext){
//upload file by giving new name
$newfilename = md5(uniqid('', true));
$newfilename= $newfilename.'.'.array_search($filemime, $allowed);
$target_file = $target_dir .$newfilename;
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
echo "uploaded.";
}
//upload failed message
else{
echo "upload failed";
die();
}
}
// if file format is wrong
else{
echo "invalid file format";
die();
}
}
// if there is any upload error
else{
echo "error in upload";
die();
}
}
else{
echo "not submited form properly";
}
?>
</code></pre>
<p>Do you have any suggestions to make this more secure or can you spot any flaws in this script that could be exploited by hackers to upload shell or PHP scripts?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T08:06:30.957",
"Id": "479074",
"Score": "0",
"body": "\"Is this code really secure?\" Secure against what?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T08:08:31.833",
"Id": "479076",
"Score": "0",
"body": "I want to know is there anyway someone can still use this upload feature to upload some php like scripts"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T08:09:56.383",
"Id": "479077",
"Score": "0",
"body": "Like [this](https://security.stackexchange.com/q/81677/55196)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T08:11:22.177",
"Id": "479078",
"Score": "0",
"body": "I want to prevent uploading of shell scripts or something like that to my server."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T09:32:56.373",
"Id": "507310",
"Score": "0",
"body": "This code is basically secure because it **renames** the file with a predefined set of extensions, thus making it impossible to upload a file with `.php` or any other harmful extension. You have to watch out for the other code though that may be tricked into including a file of the users choice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T20:35:13.447",
"Id": "510697",
"Score": "0",
"body": "For me is missing `chmod` for files and check file is image or not, may have a `php` code."
}
] |
[
{
"body": "<h1>Questions</h1>\n<blockquote>\n<p>Is this code really secure against uploading of malicious codes ? Anything i have to add to this code to make it more secure?</p>\n</blockquote>\n<p>My initial thought is to ensure that the uploaded file is not an executable file or a file that may be run as a separate script- e.g. PHP or some other language the server may handle. The Mime type checking from <code>finfo::file()</code> should handle that.</p>\n<p>You could also :</p>\n<ul>\n<li>check that a GD function like <a href=\"https://www.php.net/manual/en/function.imagecreatefromgif.php\" rel=\"nofollow noreferrer\"><code>imagecreatefromgif()</code></a>, <a href=\"https://www.php.net/manual/en/function.imagecreatefromjpeg.php\" rel=\"nofollow noreferrer\"><code>imagecreatefromjpeg()</code></a>, etc. does not return <code>FALSE</code></li>\n<li>check the permissions on the file after it is uploaded to ensure anything that shouldn’t be executed cannot be executed - perhaps use <a href=\"https://www.php.net/manual/en/function.is-executable.php\" rel=\"nofollow noreferrer\"><code>is_executable()</code></a>, <a href=\"https://php.net/fileperms\" rel=\"nofollow noreferrer\"><code>fileperms</code></a> and <a href=\"https://php.net/chmod\" rel=\"nofollow noreferrer\"><code>chmod</code></a></li>\n<li>like you say: “<em>move images folder out of public_html (root) folder.</em>”- Ensure that any uploaded files are not stored in a web accessible directory unless that is your desire. This may lead to needing a (PHP/other) script or web server module to read files.</li>\n</ul>\n<h1>Suggestions</h1>\n<h3>avoid excess <code>else</code></h3>\n<p>Whenever a conditional block contains a <code>die</code> statement then subsequent code does not need to be prefixed with <code>else</code> e.g.</p>\n<blockquote>\n<pre><code>//check if error is set\nif(!isset($_FILES['image']['error']) ){\n echo 'Invalid upload.';\n die();\n}\n// check formultiple uploads and block\nelseif(is_array($_FILES['image']['error'])){\n echo 'Only one file allowed.';\n die();\n} \n</code></pre>\n</blockquote>\n<p>When <code>else</code> is used it adds more complexity to the decision tree.</p>\n<h3>Returning early</h3>\n<p>Going along with the previous point, in some parts of the code when a precondition is not met then an error message is printed to the screen before <code>die()</code> is called. However this is not true in all cases - e.g. the first conditional:</p>\n<blockquote>\n<pre><code>if(isset($_POST['submit'])){\n</code></pre>\n</blockquote>\n<p>Flipping the logic on that so the error message that is displayed when that condition is false and adding a call to <code>die</code> would allow the indentation levels to be decreased dramatically, which would likely make the code more readable. Further improvement would come from moving some logic to functions - e.g. a function to determine if the file can be uploaded - if not then return early.</p>\n<p>With such changes the decision tree of the logic could go from something like this:</p>\n<p><a href=\"https://i.stack.imgur.com/znsHk.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/znsHk.jpg\" alt=\"screenshot of wider decision tree\" /></a>\n<sub>screenshot captured from source: <a href=\"https://www.youtube.com/watch?v=GtB5DAfOWMQ&t=917\" rel=\"nofollow noreferrer\"><em>Your code sucks, let's fix it - By Rafael Dohms</em> at 15:17</a></sub></p>\n<p>To this:</p>\n<p><a href=\"https://i.stack.imgur.com/1GFJN.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1GFJN.jpg\" alt=\"enter image description here\" /></a>\n<sub>screenshot captured from source: <a href=\"https://youtu.be/GtB5DAfOWMQ?t=928\" rel=\"nofollow noreferrer\"><em>Your code sucks, let's fix it - By Rafael Dohms</em> at 15:28</a></sub></p>\n<h3>storing max size</h3>\n<blockquote>\n<pre><code> $maximumsize=5000000000;\n</code></pre>\n</blockquote>\n<p>Since that value shouldn’t be reassigned during the runtime it is advisable to use a <a href=\"https://php.net/const\" rel=\"nofollow noreferrer\">constant</a> instead, and a common convention in many programming languages is to use all caps, which is in-line with the <a href=\"https://www.php-fig.org/psr/psr-1/#41-constants\" rel=\"nofollow noreferrer\">PHP Standards recommendation PSR-1</a> - e.g.</p>\n<pre><code>const MAXIMUM_SIZE = 5000000000;\n</code></pre>\n<p>And define those near the top of the code or in a configuration file to allow quick access should you ever need to change the value - that way you won’t need to go hunting through the code to find it.</p>\n<h3>Array syntax</h3>\n<p>There isn't anything wrong with using <code>array()</code> but as of the time of writing, <a href=\"https://www.php.net/supported-versions.php\" rel=\"nofollow noreferrer\">PHP has Active support for versions 8.0 and 7.4</a>, and since PHP 5.4 arrays can be declared with <a href=\"https://www.php.net/manual/en/migration54.new-features.php\" rel=\"nofollow noreferrer\">short array syntax (PHP 5.4)</a>.</p>\n<blockquote>\n<pre><code>$allowed = array('jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif');\n</code></pre>\n</blockquote>\n<p>Can be shortened slightly to</p>\n<pre><code>$allowed = ['jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif'];\n</code></pre>\n<h3>checking mimetype</h3>\n<p><code>$filemime</code> could either be string or Boolean - check for Boolean, then if it isn’t then <code>in_array()</code> could be used to determine if it exists in the array instead of using <code>array_search()</code></p>\n<h3>Appending to <code>$newfilename</code></h3>\n<p>The extension is appended to the file name:</p>\n<blockquote>\n<pre><code> $newfilename= $newfilename.'.'.array_search($filemime, $allowed);\n</code></pre>\n</blockquote>\n<p>The dot equals operator can be used to append to the variable:</p>\n<pre><code> $newfilename .= '.' . array_search($filemime, $allowed);\n</code></pre>\n<p>Spaces added for readability.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T08:20:36.207",
"Id": "507296",
"Score": "0",
"body": "It is not a mime-type checking that makes this code secure, but the mime-type based **renaming**. the checking is not enough, as a php file can simply bypass the checking. but renaming a .php file to .jpg will make it at least directly harmless."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T09:00:34.783",
"Id": "507305",
"Score": "0",
"body": "the mime type checking literally \"scans the first couple of bytes\", so it's already done. From the security standpoint, we don't care whether uploaded file is an image or not. We only care whether a file can be executed as a PHP script."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T07:13:25.930",
"Id": "256911",
"ParentId": "244025",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T08:03:46.683",
"Id": "244025",
"Score": "3",
"Tags": [
"php",
"security",
"validation",
"image"
],
"Title": "Secure/Bulletproof Image Upload Using PHP"
}
|
244025
|
<p>Good day! I would like to know if this is possible to be refactored into a cleaner code.
The reason I'm doing it like this is to catch the column that the error appeared on and then potentially output the column name and value for the client to view later on.</p>
<pre><code>// Make the name act as the key and the value equates to ID
// $towers['tower1'] = 1;
$towers = Tower::pluck('id', 'name')->toArray();
$departments = Department::pluck('id', 'name')->toArray();
foreach($data as $key => $row) {
try {
// $row['tower'] = 'Hello World Tower'
// Try to see if $row['tower'] is present in the $towers data source
$data[$key]['tower'] = $towers[$row['tower']];
} catch (\Exception $e) {
// Exception occurs because index is not available
$error_holder[$key]['tower_error'] = $e->getMessage();
}
// Same logic as above
try {
$data[$key]['department'] = $departments[$row['department']];
} catch (\Exception $e) {
$error_holder[$key]['department_error'] = $e->getMessage();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T12:49:26.190",
"Id": "479093",
"Score": "1",
"body": "The catch blocks will never be executed. Voting to close as not working as intended."
}
] |
[
{
"body": "<p>You need anything here but a try catch.</p>\n<pre><code>foreach($data as $key => $row) {\n // $row['tower'] = 'Hello World Tower'\n // Try to see if $row['tower'] is present in the $towers data source\n if (isset($towers[$row['tower']])) {\n $data[$key]['tower'] = $towers[$row['tower']];\n } else {\n $error_holder[$key]['tower_error'] = "Tower not found for $key";\n }\n\n if (isset($departments[$row['department']])) {\n $data[$key]['department'] = $departments[$row['department']];\n } else {\n $error_holder[$key]['tower_error'] = "Department not found for $key";\n }\n}\n</code></pre>\n<p>Although you can reduce the duplication by storing sources into array and looping over it but honestly it makes the code so muddled that I don't see the benefit.</p>\n<pre><code>foreach (compact('tower','department') as $name => $column)\n foreach($data as $key => $row) {\n if (isset($column[$row[$name]])) {\n $data[$key][$name] = $column[$row[$name]];\n } else {\n $error_holder[$key][$name.'_error'] = "$name not found for $key";\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T12:18:47.707",
"Id": "244038",
"ParentId": "244029",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244038",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T08:49:57.553",
"Id": "244029",
"Score": "1",
"Tags": [
"php",
"error-handling",
"laravel",
"exception"
],
"Title": "Handling multiple try-catches in a for loop"
}
|
244029
|
<p>I need to have a range selector that accepts string values instead of integer value.
This is not possible with standard HTML, so I needed to simulate one by using (hidden) radio buttons that are coupled with the range selector and change the label of the range selector accordingly.</p>
<p>My code is a bit of a mess, though. Could you help me clean it up?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
"use strict";
console.clear()
const selector = 'input[type="radio"][data-range-selector]'
let radios = Array.from(document.querySelectorAll(selector)).reduce((acc, el) => {
acc[el.name] = acc[el.name] || {form: el.form, elements: []}
acc[el.name].elements.push({
'element': el,
'value': el.dataset.rangeValue,
'selector': el.dataset.rangeSelector,
})
el.dataset.rangeValue = acc[el.name].elements.length - 1
return acc
}, {})
const getRadio = el => {
return el.form.querySelector(`input[type="radio"][data-range-value="${el.value}"]`)
}
const getLabelForInput = el => {
return el.form.querySelector(`label[for="${el.id}"]`)
}
const getRangeSelector = el => {
return el.form.querySelector(el.dataset.rangeSelector)
}
Object.keys(radios).forEach(key => {
var rangeSelector = getRangeSelector(radios[key].elements[0].element)
rangeSelector.setAttribute('max', radios[key].elements.length - 1);
rangeSelector.dataset.key = key
radios[key].form.addEventListener('input', function(e) {
if (e.target.matches('input[type="range"][data-key]')) {
getLabelForInput(e.target).innerHTML = getLabelForInput(getRadio(e.target)).innerHTML
getRadio(e.target).checked = true
// getRangeSelector(e.target).value = e.target.dataset.rangeValue
}
})
})
// document.addEventListener('change', e => console.log(e.target.form))
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>[data-range-selector], [data-range-selector] + label {
display: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Simulate a sliding range selector with string values</h1>
<form>
<input type="radio" name="evil" value="" id="evil" data-range-selector="#evil-range" /><label for="evil">Choose</label>
<input type="radio" name="evil" value="one" id="evil-one" data-range-selector="#evil-range" /><label for="evil-one">One</label>
<input type="radio" name="evil" value="twin" id="evil-twin" / data-range-selector="#evil-range" ><label for="evil-twin">Twin</label>
<input type="radio" name="evil" value="six" id="evil-six" data-range-selector="#evil-range" /><label for="evil-six">Six</label>
<input type="radio" name="evil" value="666" id="evil-666" data-range-selector="#evil-range" /><label for="evil-666">666</label>
<input type="range" id="evil-range" min="0" value="0"><label for="evil-range">Choose</label>
</form>
<hr>
<form>
<input type="radio" name="good" value="" id="good" data-range-selector="#good-range" data-range-value="0" /><label for="good">Choose</label>
<input type="radio" name="good" value="one" id="good-one" data-range-selector="#good-range" data-range-value="1" /><label for="good-one">One</label>
<input type="radio" name="good" value="twin" id="good-twin" / data-range-selector="#good-range" data-range-value="2" ><label for="good-twin">Twin</label>
<input type="radio" name="good" value="six" id="good-three" data-range-selector="#good-range" data-range-value="3" /><label for="good-three">Tree</label>
<input type="range" id="good-range" min="0" value="0"><label for="good-range">Choose</label>
</form></code></pre>
</div>
</div>
</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T09:49:45.303",
"Id": "244030",
"Score": "2",
"Tags": [
"javascript",
"html",
"html5"
],
"Title": "Simulate sliding range selector with string values"
}
|
244030
|
<p>I am hoping that someone can take a look at my implementation of a lock-free ring buffer and critique the implementation. I'm hoping that the focus can be of the correctness of the atomic operations and thread safety.</p>
<p>The buffer is implemented as a single producer/single consumer ring buffer, and owes a lot of boost's SPSC queue (unfortunately simply using <code>boost::spsc_queue</code> is not an option for my use case. Therefore I rolled my own.</p>
<p>Usage details are as follows:</p>
<ul>
<li>Only 1 thread (producer) may call Push()</li>
<li>Only 1 thread (consumer) may call Pop()</li>
<li><em>Either</em> the producer and consumer thread may call Read/WriteAvailable()</li>
</ul>
<p>The main concern is that the atomic operations in ReadAvailable and WriteAvailable are correct for this use case. Secondary concerns would be any performance gains that I can achieve to make operations on the buffer faster, as well as code style critique in general.</p>
<p>Many Thanks.</p>
<pre> * LockfreeBuffer.h
*
* Defines a lock free, single producer/single consumer queue
* based around a ring buffer. Only a single thread may call
* Push, and likewise a single thread may call Pop. Push/Pop
* will fail with a false return value if the queue is full (push)
* or empty (pop).
* ReadAvailable and WriteAvailable may be called from either the
* producer or consumer thread.
*/
#ifndef LOCKFREE_BUFFER_H
#define LOCKFREE_BUFFER_H
#include <atomic>
#include <memory>
template<class T>
class LockfreeBuffer
{
private:
typedef std::size_t size_t;
const size_t m_size;
std::atomic<size_t> m_readIdx;
// For Intel/AMD64, force m_readIdx and m_writeIdx onto
// different cache lines with 64 bytes of padding
// https://news.ycombinator.com/item?id=13186232
unsigned char padding[64];
std::atomic<size_t> m_writeIdx;
std::unique_ptr<T[]> m_storage;
static size_t ReadAvailable(
size_t readIdx, size_t writeIdx, size_t size)
{
if(writeIdx >= readIdx)
return writeIdx - readIdx;
return writeIdx + size - readIdx;
}
static size_t WriteAvailable(
size_t readIdx, size_t writeIdx, size_t size)
{
size_t ret = readIdx - writeIdx -1;
if(writeIdx >= readIdx)
ret += size;
return ret;
}
public:
LockfreeBuffer() = delete;
LockfreeBuffer(const LockfreeBuffer&) = delete;
LockfreeBuffer& operator=(const LockfreeBuffer&) = delete;
LockfreeBuffer(size_t size)
: m_readIdx(0)
, m_writeIdx(0)
, m_size(size)
, m_storage(std::unique_ptr<T[]>(new T[size]))
{ }
bool Push(const T& obj)
{
const size_t nextWriteIdx =
(m_writeIdx.load(std::memory_order_relaxed) + 1) % m_size;
if(nextWriteIdx == m_readIdx.load(std::memory_order_acquire))
return false; // Buffer is full
m_storage[nextWriteIdx] = obj;
m_writeIdx.store(nextWriteIdx, std::memory_order_release);
return true;
}
bool Pop(T& obj)
{
const size_t writeIdx = m_writeIdx.load(std::memory_order_acquire);
const size_t readIdx = m_readIdx.load(std::memory_order_relaxed);
if(ReadAvailable(readIdx, writeIdx, m_size) == 0)
// Buffer is empty
return false;
obj = m_storage[readIdx];
m_readIdx.store((readIdx + 1) % m_size, std::memory_order_release);
return true;
}
size_t Size()
{
// Const, no need to acquire
return m_size;
}
size_t ReadAvailable()
{
const size_t readIdx = m_readIdx.load(std::memory_order_acquire);
const size_t writeIdx = m_writeIdx.load(std::memory_order_acquire);
return ReadAvailable(readIdx, writeIdx, m_size);
}
size_t WriteAvailable()
{
const size_t readIdx = m_readIdx.load(std::memory_order_acquire);
const size_t writeIdx = m_writeIdx.load(std::memory_order_acquire);
return WriteAvailable(readIdx, writeIdx, m_size);
}
};
#endif
</pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T12:28:23.837",
"Id": "479091",
"Score": "0",
"body": "If you have a test case that uses this code, it would help the question if you posted that test code in the question as well, otherwise this is a well asked question. The more code you post the better review you will get."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T11:25:46.680",
"Id": "244033",
"Score": "1",
"Tags": [
"c++",
"performance",
"multithreading",
"lock-free"
],
"Title": "Lock free ring buffer"
}
|
244033
|
<p>Stack Exchange provides access to query their MS SQL databases. They have a table <code>Posts</code> where each post is either a question or an answer (see the schema on right hand side <a href="https://data.stackexchange.com/unix/query/new" rel="nofollow noreferrer">here</a>).</p>
<p>I saw a <a href="https://data.stackexchange.com/unix/revision/1252021/1540600/questions-answered-by-more-than-3-top-n-users" rel="nofollow noreferrer">query for questions answered by more than three 50k users</a>:</p>
<pre><code>SELECT DISTINCT Q.Id AS [Post Link], Q.AnswerCount
FROM Posts Q
JOIN Posts A1 on A1.ParentId = Q.Id
AND A1.OwnerUserId IN (SELECT TOP ##TopN## Id FROM Users ORDER BY Reputation DESC)
JOIN Posts A2 on A2.ParentId = Q.Id
AND A2.OwnerUserId IN (SELECT TOP ##TopN## Id FROM Users ORDER BY Reputation DESC)
AND A1.Id != A2.Id
JOIN Posts A3 on A3.ParentId = Q.Id
AND A3.OwnerUserId IN (SELECT TOP ##TopN## Id FROM Users ORDER BY Reputation DESC)
AND A3.Id != A1.Id AND A3.Id != A2.Id
WHERE Q.AnswerCount = 3
</code></pre>
<p>I was wondering how to improve the query (balance between efficiency and readability)? For example:</p>
<ul>
<li><p>Is it possible to avoid repeating the subquery <code>SELECT TOP ##TopN## Id FROM Users ORDER BY Reputation DESC</code> three times, and instead just have it once?</p>
</li>
<li><p>Will it be more efficient if switching the order of filtering out questions with less than three answers and checking if a question is answered by more than three 50k users?</p>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T22:32:52.043",
"Id": "479414",
"Score": "0",
"body": "Your title should state what your code does. Please read https://codereview.stackexchange.com/help/how-to-ask ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T12:55:07.887",
"Id": "479761",
"Score": "0",
"body": "As the author of the SEDE query, (1) I'm happy that the (extensive!) version history of that query seems to be gone, and (2) because SQL class was 20 years ago, I started off with a simpler goal (static 50k) and eventually figured out how to incorporate the variable \"top N\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T12:57:28.610",
"Id": "479762",
"Score": "0",
"body": "Re-viewing my own query, it's also apparent that I intended to find Q's with *at least 3* answers by top-rated users, but have managed to restrict it to Q's with *exactly 3* such answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T13:04:16.630",
"Id": "479763",
"Score": "0",
"body": "Hrmph; after incorporating [Gert's improvements](https://codereview.stackexchange.com/a/244191/103675), the link to the SEDE query has also changed. https://data.stackexchange.com/unix/revision/1252021/1540600/questions-answered-by-more-than-3-top-n-users is the one for this question."
}
] |
[
{
"body": "<p>The query title is</p>\n<blockquote>\n<p>Questions answered by more than 3 50k users</p>\n</blockquote>\n<p>But that doesn't describe what the query actually does. The query selects questions with three answers given by three <em>distinct</em> top <code>n</code> rated users. They happen to have more than 50k rep on that site, but that's a mere coincidence.</p>\n<p>That can also be done by this query, containing only 1 subquery to get the top rated users:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT Q.Id AS [Post Link], Q.AnswerCount\nFROM Posts Q\nWHERE Q.AnswerCount = 3\nAND\n(\n SELECT COUNT( DISTINCT A.OwnerUserId)\n FROM Posts A\n WHERE A.ParentId = Q.Id\n AND A.OwnerUserId IN\n (\n SELECT TOP ##TopN## Id\n FROM Users\n ORDER BY Reputation DESC\n )\n) = 3\n</code></pre>\n<p>For the record, the query doing what the title says would be</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT Q.Id AS [Post Link], Q.AnswerCount\nFROM Posts Q\nWHERE Q.AnswerCount >= 3\nAND\n(\n SELECT COUNT(DISTINCT A.OwnerUserId)\n FROM Posts A\n JOIN Users U ON A.OwnerUserId = U.Id\n WHERE A.ParentId = Q.Id\n AND U.Reputation >= 50000\n) = Q.AnswerCount\n</code></pre>\n<p>Assuming that the intention was to get questions with answers from 50k users <em>exclusively</em>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T19:49:16.217",
"Id": "244191",
"ParentId": "244034",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T11:36:49.117",
"Id": "244034",
"Score": "2",
"Tags": [
"sql",
"sql-server",
"stackexchange"
],
"Title": "How to make this query better (e.g. avoid repeating subquery in a query)?"
}
|
244034
|
<p>So this is a post as per request in a different post on stack overflow: <a href="https://stackoverflow.com/questions/62412713/why-does-my-c-sharp-xml-code-only-work-when-i-enumerate-variable-enumerable">https://stackoverflow.com/questions/62412713/why-does-my-c-sharp-xml-code-only-work-when-i-enumerate-variable-enumerable</a>. The goal of this code is to re-format an XML-file containing a treeview of a sort of folder structure. The XML is of the following format where every folder (Main or sub) is contained as a direct child of the root:</p>
<pre><code><Processen>
<process-group id="12345" name="Main1">
<members>
<process id="23456" />
</members>
</process-group>
<process-group id="34567" name="Main1/Subfolder1">
<members>
<process id="45678" />
</members>
</process-group>
</Processen>
// Etcetera
</code></pre>
<p>It needs to be:</p>
<pre><code><Processen>
<process-group id="12345" name="Main1">
<members>
<process id="23456" />
<process-group id="34567" name="Subfolder1">
<members>
<process id="45678" />
</members>
</process-group>
</members>
</process-group>
</Processen>
</code></pre>
<p>The code I created to accomplish this is real messy, I had to figure a lot out as I am an absolute beginner at coding. The code checks to see if a node is in fact a folder (process-group in the XML), then whether that folder has a name containing a slash (indicating it is a subfolder) and if so; Check if parent folder exists -> Yes: move item to that node, No: Create xml root to folder path and then move item to that node. Don't get confused by the node name and the node attribute called name. This is something I cannot influence.</p>
<p>The code for this:</p>
<pre><code>// Load XML tree
string sFile = @"FilePath";
XmlDocument doc = new XmlDocument();
doc.Load(sFile);
// Read nodes into nodelist
var n = doc.DocumentElement.SelectNodes("//*").OfType<XmlNode>().ToList();
// Build actual tree (dus childfolders in parentfolders zetten)
foreach (XmlNode x in n) // For each node
{
XmlElement xParentEle = x as XmlElement; // Convert to XmlElement to be able to check if attribute exists
if((xParentEle != null) && xParentEle.HasAttribute("name")) // If attribute (name) exists
{
if(x.Name == "process-group") // If name (= node type) process-group, these are the folders.
{
if (x.Attributes["name"].Value.ToString().Contains("/")) // If attribute name contains a '/' and is therefore a nested folder (I.e.: name="Mainfolder/subfolder")
{
string[] folders = x.Attributes["name"].Value.ToString().Split('/'); // Split into individual folder names
for(int i = folders.Length-2; i >= 0; i--) // Go through each name, starting at deepest level and work towards root. Check if folder that should be parent exists. If yes, Move node and delete original. If no, make node with that name and path.
{
if(x.ParentNode != null) // This is to prevent errors if current node has no parent as next step assumes parent exists.
{
if (x.ParentNode.SelectSingleNode("//process-group[@name='" + folders[i] + "']") != null) // If parent node of deepest folder has currently examined name. This is separate from nodes which contain multiple splits/levels as single split nodes only have to be moved. Multiple level splits have to have their paths created first which neccesitates a different approach.
{
XmlNode tempNode = x.Clone(); // Temporary clone of node that is to be moved
tempNode.Attributes["name"].Value = folders[folders.Length - 1]; // Change attribute name to only folder name (no more mainfolder/subfolder, just subfolder)
XmlNode removeNode = doc.SelectSingleNode("//process-group[@name='" + x.Attributes["name"].Value.ToString() + "']"); // Create reference to original node, it must be deleted and there should only be 1 with a particular name
doc.SelectSingleNode("/Processen").RemoveChild(removeNode); // Select parentnode and delete childnode
doc.SelectSingleNode("//process-group[@name='" + folders[i] + "']").AppendChild(tempNode); // Add the temporary node to appropriate parent folder
}
else // If the appropriate parent node does NOT exist. In this case the path and structure has to be created until the first separation. This is done by creating dummy nodes with the appropriate name and add them into the path
{
string tempXPath = "/Processen"; // Set temporary xPath to root node. This string is added onto as path grows.
foreach (string folder in folders) // For each folder contained in the necessary path, Starting at the highest level (directly underneath root)
{
if (doc.SelectSingleNode(tempXPath + "/process-group[@name='" + folder + "']") == null) // If requested node at requested location does not exist.
{
if (folder != folders[folders.Length - 1]) // If requested node is not the deepest level (Deepest level has to be copied/moved, until then they're empty/new nodes)
{
XmlNode newNode = x.Clone(); // Make new node
newNode.RemoveAll(); // Empty new node
XmlAttribute nameAttr = doc.CreateAttribute("name"); // Make node attribute "name"
nameAttr.Value = folder; // Make attribute value into name of requested folder (this is the name of a folder in the path, ex. mainfolder/ SUBFOLDERNAME / subfolder, then SUBFOLDERNAAM)
newNode.Attributes.Append(nameAttr); // Add attribute to new node
doc.SelectSingleNode(tempXPath).AppendChild(newNode); // Add new folder node to appropriate location in original document
tempXPath += "/process-group[@name='" + folder + "']"; // Go 1 level deeper with the xPath
}
else
{
XmlNode tempNode = x.Clone(); // Temporary clone of node that is to be moved
tempNode.Attributes["name"].Value = folders[folders.Length - 1]; // Change attribute name to only folder name (no more mainfolder/subfolder, just subfolder)
XmlNode removeNode = doc.SelectSingleNode("//process-group[@name='" + x.Attributes["name"].Value.ToString() + "']"); // Create reference to original node, it must be deleted and there should only be 1 with a particular name
string parentXPath = tempXPath.Substring(0, tempXPath.LastIndexOf('/')); // Remove last node from xPath to arrive at parent node. This is different from the 1 split nodes as in that case parent node is always root
doc.SelectSingleNode(parentXPath).RemoveChild(removeNode); // Select parentnode and delete childnode
doc.SelectSingleNode("//process-group[@name='" + folders[i] + "']").AppendChild(tempNode); // Add temporary node to appropriate folder
}
}
}
}
}
}
}
}
}
}
</code></pre>
<p>I am absolutely certain that this is not the best way of approaching this problem but this is the best I could think of. Apparently I've learned by now you can have a "live" node list where changes are reflected in the original document, but this lead to other difficulties as you can read in the original post linked above. I am curious if you guys can come up with better ideas!</p>
|
[] |
[
{
"body": "<p>I'm not sure if it's in the spirit of this site to suggest an entirely new approach, but here is how I would go about this:</p>\n<p>Select all of the <code>process-group</code> elements:</p>\n<pre><code>var processGroups = doc.SelectNodes("/*/process-group");\n</code></pre>\n<p>Create a dictionary of them, indexed by name (this assumes the names are all unique):</p>\n<pre><code>var processGroupDictionary = processGroups\n .OfType<XmlElement>()\n .ToDictionary(e => e.GetAttribute("name"), e => e);\n</code></pre>\n<p>Find all of the process groups that have a slash in their name:</p>\n<pre><code>var childProcessGroups = processGroupDictionary\n .Where(kv => kv.Key.Contains("/"));\n</code></pre>\n<p>For each of those:</p>\n<ul>\n<li>Change their name attribute to just the final segment</li>\n<li>Find their parent</li>\n<li>Insert them into that parent</li>\n</ul>\n\n<pre><code>foreach (var kv in childProcessGroups)\n{\n var fullName = kv.Key;\n var child = kv.Value;\n\n var lastSlash = fullName.LastIndexOf("/");\n var name = fullName.Substring(lastSlash + 1);\n var parentName = fullName.Substring(0, lastSlash);\n\n child.SetAttribute("name", name);\n\n var parent = processGroupDictionary[parentName];\n\n parent.SelectSingleNode("members").AppendChild(child);\n}\n</code></pre>\n<p>That's it!</p>\n<p>This is the full code:</p>\n<pre><code>var processGroups = doc.SelectNodes("/*/process-group");\n\nvar processGroupDictionary = processGroups\n .OfType<XmlElement>()\n .ToDictionary(e => e.GetAttribute("name"), e => e);\n\nvar childProcessGroups = processGroupDictionary\n .Where(kv => kv.Key.Contains("/"));\n\nforeach (var kv in childProcessGroups)\n{\n var fullName = kv.Key;\n var child = kv.Value;\n\n var lastSlash = fullName.LastIndexOf("/");\n var name = fullName.Substring(lastSlash + 1);\n var parentName = fullName.Substring(0, lastSlash);\n\n child.SetAttribute("name", name);\n\n var parent = processGroupDictionary[parentName];\n\n parent.SelectSingleNode("members").AppendChild(child);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T14:34:25.773",
"Id": "479111",
"Score": "0",
"body": "An entirely different way to solve a problem is always welcome, especially if it is well explained like yours. +1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T16:50:46.107",
"Id": "479124",
"Score": "0",
"body": "@JLRishe Thank you again! I am truly grateful and impressed by your generosity in answering! Your approach is definitely way cleaner and it seems more robust as well I think. It has also already given me some interesting ideas to adapt the steps following this part! I only wonder what happens when the xPath to the final node has multiple layers, i.e. more than one '/' in its name. The problem in that case is that the parentfolder (or path) does not exist yet and has to be created first. I tried your code and it does seem to produce an error because of this. I'll definitely build on this!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T17:02:12.140",
"Id": "479254",
"Score": "0",
"body": "@ThomasW Could you provide that more elaborate test case in the text of your question (preferably with the expected output)? I tried this on an example where one of the items had multiple slashes in the name and it seemed to work fine."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T13:29:18.193",
"Id": "244044",
"ParentId": "244039",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T12:31:38.497",
"Id": "244039",
"Score": "3",
"Tags": [
"c#",
"tree",
"formatting",
"xml"
],
"Title": "XML Tree Reformatter requested code. C#"
}
|
244039
|
<p>Project structure without code:<br />
<a href="https://i.stack.imgur.com/YS4rk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YS4rk.png" alt="project structure without code" /></a></p>
<p>Packages:</p>
<p><a href="https://i.stack.imgur.com/RrGBU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RrGBU.png" alt="packages" /></a></p>
<p>Classes in packages:</p>
<p><a href="https://i.stack.imgur.com/4oiiT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4oiiT.png" alt="first part" /></a><br />
<a href="https://i.stack.imgur.com/MilWT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MilWT.png" alt="second part" /></a></p>
<p>In <code>ConfigConstants</code> I store path to folder, where I save pictures. Also in <code>WebConstants</code> I store URL of Servlet.<br />
Here is mySQL script for creating db:</p>
<pre><code>drop database meme_exchanger;
CREATE SCHEMA `meme_exchanger` DEFAULT CHARACTER SET utf8 ;
use meme_exchanger;
create table users(
id int auto_increment primary key,
name varchar(30) not null unique,
password varchar(20) not null,
access_level_id int references access_levels.id,
creation_date date not null
);
create table users_banned(
id int auto_increment primary key,
user_id int references users.id,
_from date not null,
_to date not null,
removed boolean default false,
removed_date date default null
);
create table access_levels(
id int auto_increment primary key,
name varchar(20) not null
);
create table posts(
id int auto_increment primary key,
title varchar(100),
user_id int references users.id,
publish_date date not null,
picture_name varchar(50) not null
);
create table posts_banned(
id int auto_increment primary key,
post_id int references posts.id,
_from date not null,
_to date not null,
removed boolean default false,
removed_date date default null
);
create table post_likes(
id int auto_increment primary key,
post_id int references posts.id,
user_id int references users.id,
date date not null
);
create table post_comments(
id int auto_increment primary key,
post_id int references posts.id,
user_id int references users.id,
text varchar(500) not null,
date date not null
);
create table post_comments_banned(
id int auto_increment primary key,
comment_id int references post_comments.id,
_from date not null,
_to date not null,
removed boolean default false,
removed_date date default null
);
create table user_ip_adresses(
id int auto_increment primary key,
user_id int references users.id,
name varchar(15)
);
create table user_id_adresses_banned(
id int auto_increment primary key,
ip_adress_id int references user_ip_addresses.id,
_from date not null,
_to date not null,
removed boolean default false,
removed_date date default null
);
</code></pre>
<p>and creating admin account:</p>
<pre><code>insert into access_levels
(name)
VALUES
('CommonUser'),
('Admin');
insert into users
(name, password, access_level_id, creation_date)
VALUES
('root', '123321a', 2, curdate());
</code></pre>
<p><a href="https://github.com/Daam10/MemeExchanger" rel="nofollow noreferrer">To see code on GitHub</a>.</p>
<p>It is my first project on Spring MVC(used <code>Tomcat 7.0</code>) and I think I did many design and coding mistakes. Help me to find them, please.</p>
<p>I'll leave here some important files from my project:</p>
<p>AdminToolsController:</p>
<pre><code>@Controller
public class AdminToolsController {
@SuppressWarnings("deprecation")
Date toForeverDate = new Date(3000, 1, 1);
@Autowired
WebUtils webUtils;
@Autowired
IUserDAO userDAO;
@Autowired
IPostDAO postDAO;
@Autowired
MessageSource messageSource;
@RequestMapping(value = {
"/" + adminToolsMenuURL + "/" + adminToolsMenuUsersBanURL,
"/" + adminToolsMenuURL + "/" + adminToolsMenuPostsBanURL,
"/" + adminToolsMenuURL + "/" + adminToolsMenuPostCommentsBanURL,
"/" + adminToolsMenuURL + "/" + adminToolsMenuIPAddressesBanURL},
method = RequestMethod.GET)
public Object entitiesBanManagement(
HttpServletRequest request,
Locale locale) {
RedirectView redirectTo;
if((redirectTo = webUtils.loggedCheck(request)) != null ||
(redirectTo = webUtils.adminCheck(request, messageSource, locale)) != null ||
(redirectTo = webUtils.userBanCheck(request, messageSource, locale)) != null ||
(redirectTo = webUtils.ipAddressBanCheck(request, messageSource, locale)) != null) {
return redirectTo;
}
if(request.getServletPath().endsWith(adminToolsMenuUsersBanURL)) {
request.setAttribute(entitiesBanManagementPageTypeOfEntityParam, TypesOfEntity.USERS);
request.setAttribute(typeOfIdentificatorParamName, TypesOfIdentificator.LOGIN);
request.setAttribute(entitiesBanManagementPageTitleAttrName, messageSource.getMessage("UsersBanManagement", null, locale));
request.setAttribute(entitiesBanManagementPageIdentificatorNameAttrName, messageSource.getMessage("Login", null, locale));
} else if(request.getServletPath().endsWith(adminToolsMenuPostsBanURL)) {
request.setAttribute(entitiesBanManagementPageTypeOfEntityParam, TypesOfEntity.POSTS);
request.setAttribute(typeOfIdentificatorParamName, TypesOfIdentificator.ID);
request.setAttribute(entitiesBanManagementPageTitleAttrName, messageSource.getMessage("PostsBanManagement", null, locale));
request.setAttribute(entitiesBanManagementPageIdentificatorNameAttrName, messageSource.getMessage("PostID", null, locale));
} else if(request.getServletPath().endsWith(adminToolsMenuPostCommentsBanURL)) {
request.setAttribute(entitiesBanManagementPageTypeOfEntityParam, TypesOfEntity.POST_COMMENTS);
request.setAttribute(typeOfIdentificatorParamName, TypesOfIdentificator.ID);
request.setAttribute(entitiesBanManagementPageTitleAttrName, messageSource.getMessage("PostCommentsBanManagement", null, locale));
request.setAttribute(entitiesBanManagementPageIdentificatorNameAttrName, messageSource.getMessage("CommentID", null, locale));
} else if(request.getServletPath().endsWith(adminToolsMenuIPAddressesBanURL)){
request.setAttribute(entitiesBanManagementPageTypeOfEntityParam, TypesOfEntity.IP_ADDRESSES);
request.setAttribute(typeOfIdentificatorParamName, TypesOfIdentificator.ID);
request.setAttribute(entitiesBanManagementPageTitleAttrName, messageSource.getMessage("IPAddressesBanManagement", null, locale));
request.setAttribute(entitiesBanManagementPageIdentificatorNameAttrName, messageSource.getMessage("IPAddrID", null, locale)); // TODO: show user ip addresses before
} else {
throw new IllegalStateException("Wrong URL");
}
return entitiesBanManagementPageName;
}
@RequestMapping(value = "/" + adminToolsMenuURL + "/" + banURL, method = RequestMethod.POST)
public Object ban(
HttpServletRequest request,
Locale locale,
@RequestParam(identificatorParamName) String identificator,
@RequestParam(typeOfIdentificatorParamName) String typeOfIdentificator,
@RequestParam(entitiesBanManagementPageToDateParam) String toDateString,
@RequestParam(value = entitiesBanManagementPageForeverCheckboxParam, required = false) String foreverCheckbox,
@RequestParam(entitiesBanManagementPageTypeOfEntityParam) String typeOfEntity) throws ParseException {
RedirectView redirectTo;
if((redirectTo = webUtils.loggedCheck(request)) != null ||
(redirectTo = webUtils.adminCheck(request, messageSource, locale)) != null ||
(redirectTo = webUtils.userBanCheck(request, messageSource, locale)) != null ||
(redirectTo = webUtils.ipAddressBanCheck(request, messageSource, locale)) != null) {
return redirectTo;
}
String banMenuURL = null;
IBanner banner = null;
IExistanceChecker existanceChecker = null;
TypesOfEntity enumTypeOfEnity = null;
TypesOfIdentificator enumTypeOfIdentificator = null;
if(TypesOfEntity.contains(typeOfEntity)) {
enumTypeOfEnity = TypesOfEntity.getByString(typeOfEntity);
banner = chooseBanner(enumTypeOfEnity);
banMenuURL = chooseBanMenuURL(enumTypeOfEnity);
} else {
return illegalEntityTypeRedirect(typeOfEntity, request, locale);
}
if(TypesOfIdentificator.contains(typeOfIdentificator)) {
enumTypeOfIdentificator = TypesOfIdentificator.getByString(typeOfIdentificator);
existanceChecker = chooseEntityExistanceChecker(enumTypeOfEnity, enumTypeOfIdentificator);
} else {
return illegalIdentificatorTypeRedirect(typeOfIdentificator, request, locale);
}
try {
if(!existanceChecker.exists(identificator)) {
return entityDoesntExistRedirect(banMenuURL, identificator, request, locale);
}
Date now = new Date();
boolean forever = webUtils.getHTMLCheckboxValue(foreverCheckbox);
if(forever) {
banner.ban(now, toForeverDate, identificator);
} else {
try {
Date toDate = htmlDateFormater.parse(toDateString);
if(now.after(toDate)) {
return wrongToDateRedirect(banMenuURL, now, toDate, request, locale); // TODO: not generic message?
}
banner.ban(now, toDate, identificator);
} catch(ParseException ex) {
return maybeDidntSetDateRedirect(banMenuURL, identificator, request, locale);
}
}
return new RedirectView("/" + adminToolsMenuURL + "/" + banMenuURL, true);
} catch(IllegalArgumentException ex) {
return illegalIdentificatorRedirect(banMenuURL, identificator, request, locale);
}
}
@RequestMapping(value = "/" + adminToolsMenuURL + "/" + getBansURL, method = RequestMethod.GET)
public Object getBansUsingJSGet(
HttpServletRequest request,
Locale locale,
@RequestParam(countFromParamName) int from,
@RequestParam(countToParamName) int to,
@RequestParam(bansFirstIDFromFirstSetParamName) Integer idOfFirstBan,
@RequestParam(identificatorParamName) String identificator,
@RequestParam(typeOfIdentificatorParamName) String typeOfIdentificator,
@RequestParam(entitiesBanManagementPageTypeOfEntityParam) String typeOfEntity) {
String loginFromCookies = webUtils.getLoginFromCookies(request);
if(webUtils.isLoggedUsingCookies(request) != LoginStatus.LOGGED) {
request.getSession().setAttribute(failedPageErrorMessageAttrName, messageSource.getMessage("NotLogonMsg", new Object[] {loginFromCookies}, locale));
return failedPageName;
}
if(!userDAO.isAdmin(loginFromCookies)) {
request.getSession().setAttribute(failedPageErrorMessageAttrName, messageSource.getMessage("YouAreNotAdmin", null, locale));
return failedPageName;
}
if(userDAO.isBannedUser(loginFromCookies)) {
DateInterval banDateInterval = userDAO.getLastUserBanDateInterval(loginFromCookies);
Date fromDate = null, toDate = null;
if(banDateInterval != null) {
fromDate = banDateInterval.getFromDate();
toDate = banDateInterval.getToDate();
}
request.getSession().setAttribute(failedPageErrorMessageAttrName, messageSource.getMessage("UserWithLoginBannedMsg", new Object[] {loginFromCookies, fromDate, toDate}, locale));
return failedPageName;
}
if(userDAO.isBannedUserIPAddressByLogin(webUtils.getLoginFromCookies(request))) {
DateInterval banDateInterval = userDAO.getLastUserIPAddressBanDateInterval(loginFromCookies);
IPAddress ipAddress = userDAO.getIPAddressByLogin(loginFromCookies);
Date fromDate = null, toDate = null;
if(banDateInterval != null) {
fromDate = banDateInterval.getFromDate();
toDate = banDateInterval.getToDate();
}
request.getSession().setAttribute(failedPageErrorMessageAttrName, messageSource.getMessage("IPAddressBannedMsg", new Object[] {ipAddress == null ? null : ipAddress.getName(), fromDate, toDate}, locale));
return failedPageName;
}
IBansGetter bansGetter = null;
IExistanceChecker banExistanceChecker = null;
TypesOfEntity enumTypeOfEnity = null;
TypesOfIdentificator enumTypeOfIdentificator = null;
if(TypesOfEntity.contains(typeOfEntity)) {
enumTypeOfEnity = TypesOfEntity.getByString(typeOfEntity);
bansGetter = chooseBansGetter(enumTypeOfEnity);
} else {
return illegalEntityTypeRedirect(typeOfEntity, request, locale);
}
if(TypesOfIdentificator.contains(typeOfIdentificator)) {
enumTypeOfIdentificator = TypesOfIdentificator.getByString(typeOfIdentificator);
banExistanceChecker = chooseEntityExistanceChecker(enumTypeOfEnity, enumTypeOfIdentificator);
} else {
return illegalIdentificatorTypeRedirect(typeOfIdentificator, request, locale);
}
try {
if(!banExistanceChecker.exists(identificator)) {
request.getSession().setAttribute(
failedPageErrorMessageAttrName,
messageSource.getMessage("EntityDoesntExistsMsg", new Object[] {identificator}, locale));
return failedPageName;
}
boolean isFirstSet = idOfFirstBan == null;
int countOfNewBeforeFirst = 0;
if(!isFirstSet) {
countOfNewBeforeFirst = bansGetter.getBansCountBefore(idOfFirstBan);
}
System.out.println(identificator + " " + from + " " + to + " " + countOfNewBeforeFirst);
List<Ban> bans = bansGetter.getBans(identificator, from + countOfNewBeforeFirst, to + countOfNewBeforeFirst);
request.setAttribute(getBansPageBansAttrName, bans);
request.setAttribute(getBansPageWhenSwitchedURLAttrName, changeBanStateURL);
request.setAttribute(entitiesBanManagementPageTypeOfEntityParam, enumTypeOfEnity);
request.setAttribute(isFirstSetAttrName, isFirstSet);
return getBansPage;
} catch(IllegalArgumentException ex) {
request.getSession().setAttribute(
failedPageErrorMessageAttrName,
messageSource.getMessage(
"IllegalIdentificatorMsg",
new Object[] {identificator},
locale));
return failedPageName;
}
}
@RequestMapping(value = "/" + changeBanStateURL, method=RequestMethod.POST)
public Object changeBanState(
HttpServletRequest request,
Locale locale,
@RequestParam(value=getBansPageDoActiveParamName,required=false) String doActive,
@RequestParam(identificatorParamName) String banIdentificator,
@RequestParam(entitiesBanManagementPageTypeOfEntityParam) String typeOfEntity) {
System.out.println(banIdentificator);
RedirectView redirectTo;
if((redirectTo = webUtils.loggedCheck(request)) != null ||
(redirectTo = webUtils.adminCheck(request, messageSource, locale)) != null ||
(redirectTo = webUtils.userBanCheck(request, messageSource, locale)) != null ||
(redirectTo = webUtils.ipAddressBanCheck(request, messageSource, locale)) != null) {
return redirectTo;
}
String banMenuURL = null;
IBanStateChanger banStateChanger = null;
IExistanceChecker banExistanceChecker = null;
if(TypesOfEntity.contains(typeOfEntity)) {
TypesOfEntity enumTypeOfEnity = TypesOfEntity.getByString(typeOfEntity);
banMenuURL = chooseBanMenuURL(enumTypeOfEnity);
banExistanceChecker = chooseEntityBanExistanceChecker(enumTypeOfEnity, TypesOfIdentificator.ID);
banStateChanger = chooseBanStateChanger(enumTypeOfEnity, TypesOfIdentificator.ID);
} else {
return illegalEntityTypeRedirect(typeOfEntity, request, locale);
}
try {
if(!banExistanceChecker.exists(banIdentificator)) {
return entityDoesntExistRedirect(banMenuURL, banIdentificator, request, locale);
}
boolean isActive = doActive == null ? true : false;
int changedCount = banStateChanger.changeBanState(isActive, banIdentificator);
if(changedCount != 1) {
System.out.println("Changed " + changedCount + " bans instead of 1");
}
return new RedirectView("/" + adminToolsMenuURL + "/" + banMenuURL, true);
} catch(IllegalArgumentException ex) {
return illegalIdentificatorRedirect(banMenuURL, banIdentificator, request, locale);
}
}
@RequestMapping(value = "/" + adminToolsMenuURL + "/" + getIPAddressByUserURL, method=RequestMethod.POST)
public Object getIPAddress(
HttpServletRequest request,
Locale locale,
@RequestParam(typeOfIdentificatorParamName) String typeOfIdentificator,
@RequestParam(identificatorParamName) String identificator) {
String loginFromCookies = webUtils.getLoginFromCookies(request);
if(webUtils.isLoggedUsingCookies(request) != LoginStatus.LOGGED) {
request.getSession().setAttribute(failedPageErrorMessageAttrName, messageSource.getMessage("NotLogonMsg", new Object[] {loginFromCookies}, locale));
return failedPageName;
}
if(!userDAO.isAdmin(loginFromCookies)) {
request.getSession().setAttribute(failedPageErrorMessageAttrName, messageSource.getMessage("YouAreNotAdmin", null, locale));
return failedPageName;
}
if(userDAO.isBannedUser(loginFromCookies)) {
DateInterval banDateInterval = userDAO.getLastUserBanDateInterval(loginFromCookies);
Date from = null, to = null;
if(banDateInterval != null) {
from = banDateInterval.getFromDate();
to = banDateInterval.getToDate();
}
request.getSession().setAttribute(failedPageErrorMessageAttrName, messageSource.getMessage("UserWithLoginBannedMsg", new Object[] {loginFromCookies, from, to}, locale));
return failedPageName;
}
if(userDAO.isBannedUserIPAddressByLogin(webUtils.getLoginFromCookies(request))) {
DateInterval banDateInterval = userDAO.getLastUserIPAddressBanDateInterval(loginFromCookies);
IPAddress ipAddress = userDAO.getIPAddressByLogin(loginFromCookies);
Date from = null, to = null;
if(banDateInterval != null) {
from = banDateInterval.getFromDate();
to = banDateInterval.getToDate();
}
request.getSession().setAttribute(failedPageErrorMessageAttrName, messageSource.getMessage("IPAddressBannedMsg", new Object[] {ipAddress == null ? null : ipAddress.getName(), from, to}, locale));
return failedPageName;
}
TypesOfIdentificator enumTypeOfIdentificator = null;
IIPAddressGetter ipAddressGetter = null;
if(TypesOfIdentificator.contains(typeOfIdentificator)) {
enumTypeOfIdentificator = TypesOfIdentificator.getByString(typeOfIdentificator);
ipAddressGetter = chooseByUserIPAddressGetter(enumTypeOfIdentificator);
} else {
request.getSession().setAttribute(
failedPageErrorMessageAttrName,
messageSource.getMessage(
"IllegalIdentificatorTypeMsg",
new Object[] {
typeOfIdentificator,
CommonUtils.getEnumeration(TypesOfIdentificator.getTypesOfIdentificatorList(), ", ")},
locale));
return failedPageName;
}
try {
request.setAttribute(getIPAddressPageIPAddressAttrName, ipAddressGetter.get(identificator));
return getIPAddressPageName;
} catch(IllegalArgumentException ex) {
request.getSession().setAttribute(
failedPageErrorMessageAttrName,
messageSource.getMessage(
"IllegalIdentificatorMsg",
new Object[] {identificator},
locale));
return failedPageName;
}
}
private IIPAddressGetter chooseByUserIPAddressGetter(TypesOfIdentificator enumTypeOfIdentificator) {
switch(enumTypeOfIdentificator) {
case LOGIN:
return userDAO::getIPAddressByLogin;
default:
throw new IllegalStateException();
}
}
private IExistanceChecker chooseEntityExistanceChecker(TypesOfEntity typeOfEntity, TypesOfIdentificator typeOfIdentificator) {
switch(typeOfEntity) {
case USERS:
switch(typeOfIdentificator) {
case LOGIN:
return userDAO::existsUserByLogin;
case ID:
return (String identificator) -> userDAO.existsUserById(Integer.parseInt(identificator));
default:
throw new IllegalStateException("Illegal type of entity to ban");
}
case POSTS:
return (String identificator) -> postDAO.existsPost(Integer.parseInt(identificator));
case POST_COMMENTS:
return (String identificator) -> postDAO.existsComment(Integer.parseInt(identificator));
case IP_ADDRESSES:
return (String identificator) -> userDAO.existsIPAddressById(Integer.parseInt(identificator));
default:
throw new IllegalStateException("illegal type of entity to ban");
}
}
private String chooseBanMenuURL(TypesOfEntity typeOfEntity) {
switch(typeOfEntity) {
case USERS:
return adminToolsMenuUsersBanURL;
case POSTS:
return adminToolsMenuPostsBanURL;
case POST_COMMENTS:
return adminToolsMenuPostCommentsBanURL;
case IP_ADDRESSES:
return adminToolsMenuIPAddressesBanURL;
default:
throw new IllegalStateException("illegal type of entity to ban");
}
}
private IBansGetter chooseBansGetter(TypesOfEntity typeOfEntity) {
switch(typeOfEntity) {
case USERS:
return new IBansGetter() {
@Override
public List<Ban> getBans(String identificator, int from, int to) {
return userDAO.getUserBans(identificator, from, to);
}
@Override
public int getBansCountBefore(int id) throws DataAccessException {
return userDAO.getUserBansCountBefore(id);
}
};
case POSTS:
return new IBansGetter() {
@Override
public List<Ban> getBans(String identificator, int from, int to) {
return postDAO.getPostBans(Integer.parseInt(identificator), from, to);
}
@Override
public int getBansCountBefore(int id) throws DataAccessException {
return postDAO.getPostBansCountBefore(id);
}
};
case POST_COMMENTS:
return new IBansGetter() {
@Override
public List<Ban> getBans(String identificator, int from, int to) {
return postDAO.getCommentBans(Integer.parseInt(identificator), from, to);
}
@Override
public int getBansCountBefore(int id) throws DataAccessException {
return postDAO.getCommentBansCountBefore(id);
}
};
case IP_ADDRESSES:
return new IBansGetter() {
@Override
public List<Ban> getBans(String identificator, int from, int to) {
return userDAO.getIPAddressBans(Integer.parseInt(identificator), from, to);
}
@Override
public int getBansCountBefore(int id) throws DataAccessException {
return userDAO.getIPAddressBansCountBefore(id);
}
};
default:
throw new IllegalStateException("Illegal type of entity to ban");
}
}
private IBanner chooseBanner(TypesOfEntity typeOfEntity) throws ParseException {
switch(typeOfEntity) {
case USERS:
return userDAO::banUser;
case POSTS:
return (Date from, Date to, String identificator) -> postDAO.banPost(from, to, Integer.parseInt(identificator));
case POST_COMMENTS:
return (Date from, Date to, String identificator) -> postDAO.banComment(from, to, Integer.parseInt(identificator));
case IP_ADDRESSES:
return (Date from, Date to, String identificator) -> userDAO.banIPAddress(from, to, Integer.parseInt(identificator));
default:
throw new IllegalStateException("illegal type of entity to ban");
}
}
private IExistanceChecker chooseEntityBanExistanceChecker(TypesOfEntity typeOfEntity, TypesOfIdentificator typeOfIdentificator) {
switch(typeOfEntity) {
case USERS:
return (String identificator) -> userDAO.existsUserBanById(Integer.parseInt(identificator));
case POSTS:
return (String identificator) -> postDAO.hasPostBan(Integer.parseInt(identificator));
case POST_COMMENTS:
return (String identificator) -> postDAO.hasCommentBan(Integer.parseInt(identificator));
case IP_ADDRESSES:
return (String identificator) -> userDAO.existsIPAddressBanById(Integer.parseInt(identificator));
default:
throw new IllegalStateException("illegal type of entity to ban");
}
}
private IBanStateChanger chooseBanStateChanger(TypesOfEntity typeOfEntity, TypesOfIdentificator typeOfIdentificator) {
switch(typeOfEntity) {
case USERS:
return (boolean isActive, String identificator) -> userDAO.changeUserBanStateById(isActive, Integer.parseInt(identificator));
case POSTS:
return (boolean isActive, String identificator) -> postDAO.changePostBanState(isActive, Integer.parseInt(identificator));
case POST_COMMENTS:
return (boolean isActive, String identificator) -> postDAO.changeCommentBanState(isActive, Integer.parseInt(identificator));
case IP_ADDRESSES:
return (boolean isActive, String identificator) -> userDAO.changeIPAddressBanStateById(isActive, Integer.parseInt(identificator));
default:
throw new IllegalStateException("illegal type of entity to ban");
}
}
private RedirectView maybeDidntSetDateRedirect(
String adminToolURL,
String login,
HttpServletRequest request,
Locale locale) {
request.getSession().setAttribute(entitiesBanManagementPageMaybeDidntSetDateMsgAttrName, messageSource.getMessage("MaybeDidntSetDateMsg", null, locale));
return new RedirectView("/" + adminToolsMenuURL + "/" + adminToolURL, true);
}
private RedirectView wrongToDateRedirect(
String adminToolURL,
Date now,
Date toDate,
HttpServletRequest request,
Locale locale) {
request.getSession().setAttribute(entitiesBanManagementPageWrongToDateErrorMsgAttrName, messageSource.getMessage("WrongToDateErrorMsg", new Object[] {now, dbDateFormater.format(toDate)}, locale));
return new RedirectView("/" + adminToolsMenuURL + "/" + adminToolURL, true);
}
private RedirectView entityDoesntExistRedirect(
String toolURL,
String identificator,
HttpServletRequest request,
Locale locale) {
request.getSession().setAttribute(entitiesBanManagementPageEntityDoesntExistMsgAttrName, messageSource.getMessage("EntityDoesntExistsMsg", new Object[] {identificator}, locale));
return new RedirectView("/" + adminToolsMenuURL + "/" + toolURL, true);
}
private RedirectView illegalIdentificatorRedirect(
String toolURL,
String identificator,
HttpServletRequest request,
Locale locale) {
request.getSession().setAttribute(
adminToolsMenuPageIllegalEntityTypeMsgAttrName, // TODO: think about creating name-spaces - EntitiesBanManagement.* class f.e.
messageSource.getMessage(
"IllegalIdentificatorMsg",
new Object[] {identificator},
locale));
return new RedirectView("/" + adminToolsMenuURL + "/" + toolURL, true);
}
private RedirectView illegalIdentificatorTypeRedirect(
String typeOfIdentificator,
HttpServletRequest request,
Locale locale) {
request.getSession().setAttribute(
adminToolsMenuPageIllegalIdentificatorTypeMsgAttrName,
messageSource.getMessage(
"IllegalIdentificatorTypeMsg",
new Object[] {
typeOfIdentificator,
CommonUtils.getEnumeration(TypesOfIdentificator.getTypesOfIdentificatorList(), ", ")},
locale));
return new RedirectView("/" + adminToolsMenuURL, true);
}
private RedirectView illegalEntityTypeRedirect(
String typeOfEntity,
HttpServletRequest request,
Locale locale) {
request.getSession().setAttribute(
adminToolsMenuPageIllegalEntityTypeMsgAttrName,
messageSource.getMessage(
"IllegalEntityTypeMsg",
new Object[] {
typeOfEntity,
CommonUtils.getEnumeration(TypesOfEntity.getTypesOfEntityList(), ", ")},
locale));
return new RedirectView("/" + adminToolsMenuURL, true);
}
}
</code></pre>
<p>DefaultController:</p>
<pre><code>@Controller
public class DefaultController {
@Autowired
WebUtils webUtils;
@Autowired
IUserDAO userDAO;
@Autowired
IPostDAO postDAO;
@Autowired
IFileChecker fileChecker;
@Autowired
IPostTitleChecker postTitleChecker;
@Autowired
MessageSource messageSource;
@RequestMapping(value="/" + mainURL, method = RequestMethod.GET)
public Object main(HttpServletRequest request, Locale locale) {
RedirectView redirectTo;
if((redirectTo = webUtils.loggedCheck(request)) != null ||
(redirectTo = webUtils.userBanCheck(request, messageSource, locale)) != null ||
(redirectTo = webUtils.ipAddressBanCheck(request, messageSource, locale)) != null) {
return redirectTo;
}
request.setAttribute(isAdminAttrName, userDAO.isAdmin(webUtils.getLoginFromCookies(request)));
return mainPageName;
}
@RequestMapping(value="/" + createPostURL, method = RequestMethod.GET)
public Object createPost(HttpServletRequest request, Locale locale) {
RedirectView redirectTo;
if((redirectTo = webUtils.loggedCheck(request)) != null ||
(redirectTo = webUtils.userBanCheck(request, messageSource, locale)) != null ||
(redirectTo = webUtils.ipAddressBanCheck(request, messageSource, locale)) != null) {
return redirectTo;
}
int countOfPostsToday = postDAO.countOfPostsToday(webUtils.getLoginFromCookies(request));
if(countOfPostsToday >= MAX_POSTS_COUNT_PER_DAY) {
if(request.getSession().getAttribute(createPostPageTooManyPostsPerDayMsgAttrName) == null) { // if didn't redirected from createPost_postForm with this error
request.getSession().setAttribute(
createPostPageTooManyPostsPerDayMsgAttrName,
messageSource.getMessage(
"TooManyPostsPerDayMsg",
new Object[] {webUtils.getLoginFromCookies(request), MAX_POSTS_COUNT_PER_DAY},
locale));
}
}
return createPostPageName;
}
@RequestMapping(value="/" + createPostURL, method = RequestMethod.POST)
public Object createPost_postForm(
HttpServletRequest request,
@RequestParam(createPostPageTitleParamName) String title,
@RequestParam(createPostPageFileParamName) CommonsMultipartFile file,
Locale locale) throws IOException {
HttpSession session = request.getSession();
RedirectView redirectTo;
if((redirectTo = webUtils.loggedCheck(request)) != null ||
(redirectTo = webUtils.userBanCheck(request, messageSource, locale)) != null ||
(redirectTo = webUtils.ipAddressBanCheck(request, messageSource, locale)) != null) {
return redirectTo;
}
List<String> errors;
boolean hasErrors = false;
if(!(errors = fileChecker.getErrorsBeforeGetting(file, locale)).isEmpty()) {
hasErrors = true;
errors.forEach(System.out::println);
session.setAttribute(createPostPageFileBeforeInsertErrorsAttrName, errors);
}
if(!(errors = postTitleChecker.getErrors(title, locale)).isEmpty()) {
hasErrors = true;
errors.forEach(System.out::println);
session.setAttribute(createPostPageTitleErrorsAttrName, errors);
}
int countOfPostsToday = postDAO.countOfPostsToday(webUtils.getLoginFromCookies(request));
if(countOfPostsToday >= MAX_POSTS_COUNT_PER_DAY) {
hasErrors = true;
session.setAttribute(
createPostPageTooManyPostsPerDayMsgAttrName,
messageSource.getMessage(
"TooManyPostsPerDayMsg",
new Object[] {webUtils.getLoginFromCookies(request), MAX_POSTS_COUNT_PER_DAY},
locale));
}
if(hasErrors) {
return new RedirectView("/" + createPostURL, true);
}
String insertedFileName = postDAO.insertFile(file, locale);
if(!(errors = fileChecker.getErrorsAfterGetting(insertedFileName, locale)).isEmpty()) {
errors.forEach(System.out::println);
session.setAttribute(createPostPageFileAfterInsertErrorsAttrName, errors);
return new RedirectView("/" + createPostURL, true);
}
System.out.println(insertedFileName);
postDAO.insertRecord(webUtils.getLoginFromCookies(request), title, insertedFileName);
return new RedirectView("/" + createPostURL, true);
}
@RequestMapping(value="/" + feedURL, method = RequestMethod.GET)
public Object feed(HttpServletRequest request) {
RedirectView redirectTo;
if((redirectTo = webUtils.loggedCheck(request)) != null) {
return redirectTo;
}
return feedPageName;
}
@RequestMapping(value="/" + getFeedURL, method = RequestMethod.GET)
public Object getFeed(HttpServletRequest request,
@RequestParam(countFromParamName) int from,
@RequestParam(countToParamName) int to,
@RequestParam(postsFirstIDFromFirstSetParamName) Integer idOfFirst) throws IOException {
if(webUtils.loggedCheck(request) != null) {
return null; // TODO: write smth in answer?
}
boolean isFirstSet = idOfFirst == null;
int countOfNewBeforeFirst = 0;
if(!isFirstSet) {
countOfNewBeforeFirst = postDAO.getCountPostsBefore(idOfFirst);
}
List<FeedPostWithBanInfo> feedPostsWithBanInfo = postDAO.getFreshPostsWithBiggestBanInfo(from + countOfNewBeforeFirst, to + countOfNewBeforeFirst);
feedPostsWithBanInfo.forEach(System.out::println);
request.setAttribute(feedPostsWithBanInfoAttrName, feedPostsWithBanInfo);
request.setAttribute(isFirstSetAttrName, isFirstSet);
String loginFromCookies = webUtils.getLoginFromCookies(request);
request.setAttribute(getFeedPageCanLeaveCommentsAttrName, canLeaveComments(loginFromCookies));
request.setAttribute(loginAttrName, loginFromCookies);
return getFeedPageName;
}
@RequestMapping(value="/" + createCommentURL, method = RequestMethod.POST)
@ResponseBody
public Object createComment(
HttpServletRequest request,
@RequestParam(getFeedTextOfCommentParamName) String text,
@RequestParam(postIDParamName) int postID) {
String loginFromCookies = webUtils.getLoginFromCookies(request);
if(webUtils.isLoggedUsingCookies(request) != LoginStatus.LOGGED ||
userDAO.isBannedUser(loginFromCookies) ||
userDAO.isBannedUserIPAddressByLogin(loginFromCookies)) {
return "error - banned or not logged"; // TODO: to return smth?
}
if(text.length() > MAX_COMMENT_LENGTH || text.length() < MIN_COMMENT_LENGTH) {
return "error - comment has illegal length - > " + MAX_COMMENT_LENGTH + " or < " + MIN_COMMENT_LENGTH;
}
if(!postDAO.existsPost(postID) || postDAO.isPostBanned(postID)) {
return "error - post doesn't exist or banned";
}
if(postDAO.getCommentsCountPerDay(loginFromCookies) > MAX_COMMENTS_COUNT_PER_DAY) {
return "too many comments per day";
}
int countCreated = postDAO.createComment(postID, loginFromCookies, text);
if(countCreated == 0) {
return "not created";
}
return "ok";
}
@RequestMapping(value="/" + imgsURL, method = RequestMethod.GET)
public void getImg(@RequestParam(imgNameParamName) String name, HttpServletResponse response, HttpServletRequest request, Locale locale) throws IOException {
if(webUtils.loggedCheck(request) != null ||
webUtils.userBanCheck(request, messageSource, locale) != null) {
return; // TODO: to return smth?
}
File file = new File(picturesDirectiory + File.separatorChar + name);
if(!file.exists()) {
System.out.println(name);
response.sendError(404, messageSource.getMessage("ImgNotFoundMsg", new Object[] {name}, locale));
return;
}
String postfix = name.split("\\.")[1];
if(!PossibleIMGsSuffixes.contains(postfix.toLowerCase())) {
response.sendError(500, messageSource.getMessage("InvalidFileTypeOnServerMsg", new Object[] {name}, locale));
}
response.setContentType("image/" + postfix);
InputStream in = new FileInputStream(file);
IOUtils.copy(in, response.getOutputStream());
}
@RequestMapping(value = "/" + getCommentsURL, method = RequestMethod.GET)
public Object getComments(HttpServletRequest request,
Locale locale,
@RequestParam(countFromParamName) int from,
@RequestParam(countToParamName) int to,
@RequestParam(commentsFirstIDFromFirstSetParamName) Integer idOfFirstComment,
@RequestParam(postIDParamName) int postID) {
String loginFromCookies = webUtils.getLoginFromCookies(request);
if(webUtils.isLoggedUsingCookies(request) != LoginStatus.LOGGED) {
request.getSession().setAttribute(failedPageErrorMessageAttrName, messageSource.getMessage("NotLogonMsg", new Object[] {loginFromCookies}, locale));
return failedPageName;
}
boolean isFirstSet = idOfFirstComment == null;
int countOfNewBeforeFirst = 0;
if(!isFirstSet) {
countOfNewBeforeFirst = postDAO.getCommentsCountUnderPostBefore(idOfFirstComment);
}
List<PostCommentWithBanInfo> comments = postDAO.getFreshCommentsWithBiggestBanInfo(postID, from + countOfNewBeforeFirst, to + countOfNewBeforeFirst);
request.setAttribute(getCommentsPageCommentsAttrName, comments);
request.setAttribute(isFirstSetAttrName, isFirstSet);
request.setAttribute(postIDAttrName, postID);
System.out.println(from + " " + to + " " + countOfNewBeforeFirst);
return getCommentsPageName;
}
@RequestMapping(value="/" + adminToolsMenuURL, method = RequestMethod.GET)
public Object adminToolsMenu(HttpServletRequest request, Locale locale) {
RedirectView redirectTo;
if((redirectTo = webUtils.loggedCheck(request)) != null ||
(redirectTo = webUtils.adminCheck(request, messageSource, locale)) != null ||
(redirectTo = webUtils.userBanCheck(request, messageSource, locale)) != null ||
(redirectTo = webUtils.ipAddressBanCheck(request, messageSource, locale)) != null) {
return redirectTo;
}
return adminToolsMenuPageName;
}
@RequestMapping(value = "/" + failedURL)
public Object failed(HttpServletRequest request) {
return failedPageName;
}
boolean canLeaveComments(String login) {
return !userDAO.isBannedUser(login) && !userDAO.isBannedUserIPAddressByLogin(login);
}
}
</code></pre>
<p>EnterController:</p>
<pre><code>@Controller
@EnableTransactionManagement
public class EnterController {
@Autowired
WebUtils webUtils;
@Autowired
IUserDAO userDAO;
@Autowired
IUserChecker userChecker;
@Autowired
MessageSource messageSource;
@RequestMapping(value="/" + rootURL, method = RequestMethod.GET)
public Object root(HttpServletRequest request) {
if(webUtils.isLoggedUsingCookies(request) != LoginStatus.LOGGED) { // to do ban checks
return rootPageName;
}
return new RedirectView(mainURL, true);
}
@RequestMapping(value="/" + loginURL, method = RequestMethod.GET)
public Object login(HttpServletRequest request) {
return loginPageName;
}
@RequestMapping(value="/" + loginURL, method = RequestMethod.POST)
public Object login_loginForm(
HttpServletRequest request,
HttpSession model,
@RequestParam(loginPageLoginParamName) String login,
@RequestParam(loginPagePasswordParamName) String password,
HttpServletResponse response,
Locale locale) {
if(userDAO.isWrong(login, password)) {
model.setAttribute(
loginPageWrongLoginOrPasswordMsgAttrName,
messageSource.getMessage("WrongLoginOrPasswordMsg", null, locale));
return loginPageName;
}
RedirectView redirectTo;
if((redirectTo = webUtils.userBanCheck(login, request, messageSource, locale)) != null ||
(redirectTo = webUtils.ipAddressBanCheck(login, request, messageSource, locale)) != null) {
return redirectTo;
}
webUtils.putUserIntoCookies(response, login, password, secondsToSaveCookie);
return new RedirectView(mainURL, true);
}
@RequestMapping(value="/" + registrationURL, method = RequestMethod.GET)
public Object registration(HttpServletRequest request) {
return registrationPageName;
}
@Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.SERIALIZABLE)
@RequestMapping(value="/" + registrationURL, method = RequestMethod.POST)
public Object registration_registationForm(
@RequestParam(registrationPageLoginParamName) String login,
@RequestParam(registrationPagePasswordParamName) String password,
HttpServletResponse response,
HttpServletRequest request,
Locale locale) {
if(userDAO.existsUserByLogin(login)) {
request.setAttribute(
registrationPageLoginAlreadyExistsMsgAttrName,
messageSource.getMessage("LoginAlreadyExistsMsg", null, locale));
return registrationPageName;
}
List<String> errors;
if(!(errors = userChecker.getLoginErrors(login, locale)).isEmpty()) {
errors.forEach(System.out::println);
request.setAttribute(registrationPageLoginErrorsAttrName, errors);
return registrationPageName;
}
if(!(errors = userChecker.getPasswordErrors(password, locale)).isEmpty()) {
errors.forEach(System.out::println);
request.setAttribute(registrationPagePasswordErrorsAttrName, errors);
return registrationPageName;
}
String ipAddress = request.getRemoteAddr();
if(userDAO.getCountOfAccountsOfAddr(ipAddress) > MAX_ACCOUNT_COUNT_PER_ADDR) {
request.setAttribute(
registrationPageTooManyAccountsMsgAttrName,
messageSource.getMessage("TooManyAccountsMsg", new Object[] {MAX_ACCOUNT_COUNT_PER_ADDR}, locale));
return registrationPageName;
}
webUtils.putUserIntoCookies(response, login, password, secondsToSaveCookie);
userDAO.insertUser(login, password);
userDAO.insertIPAddress(login, ipAddress);
return new RedirectView(mainURL, true);
}
@RequestMapping(value="/" + logoutURL, method = RequestMethod.GET)
public RedirectView logout(HttpServletResponse response) {
webUtils.deleteCookies(new String[] {loginCookieName, passwordCookieName}, response);
return new RedirectView(rootURL, true);
}
}
</code></pre>
<p>MySQLPostDAO:</p>
<pre><code>@Component
public class MySQLPostDAO implements IPostDAO {
JdbcTemplate jdbcTemplate;
@Autowired
MessageSource messageSource;
@Autowired
public MySQLPostDAO(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public String insertFile(CommonsMultipartFile file, Locale locale) throws IOException, IllegalStateException, EmptyFileException { // TODO: think about it. It doesn't have any relation to MySQL(!)PostDAO
if(!file.isEmpty()) {
File fileToUpload = null;
String[] splittedByDots = file.getOriginalFilename().split("\\.");
String fileName = CommonUtils.connectTo(splittedByDots, splittedByDots.length - 1);
String fileExtension = "." + splittedByDots[splittedByDots.length - 1].toLowerCase(); // SHOULD BE SAVED IN LOWER CASE!
boolean foundPlace = false;
for(int i = 0; i < 100; i++) {
if(!(fileToUpload = new File(picturesDirectiory + File.separatorChar + fileName + Integer.toString(i) + fileExtension)).exists()) {
foundPlace = true;
break;
}
}
if(!foundPlace) {
throw new IllegalStateException(messageSource.getMessage("TooManyFilesWithNameMsg", new Object[] {MAX_FILES_WITH_SAME_NAME_COUNT}, locale));
}
fileToUpload.createNewFile();
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileToUpload));
out.write(file.getBytes());
out.close();
return fileToUpload.getName();
}
throw new EmptyFileException(messageSource.getMessage("EmptyFileMsg", new Object[] {file.getOriginalFilename()}, locale));
}
@Override
public void insertRecord(String login, String title, String filePath) throws DataAccessException {
String query = MessageFormat.format(
"INSERT INTO {0} ({1}, {2}, {3}, {4}) VALUES (?, (SELECT {5} FROM {6} WHERE {7} = ?), curdate(), ?);",
postsTableName,
postsTableTitleFieldName,
postsTableUserIDFieldName,
postsTablePublishDateFieldName,
postsTablePictureNameFieldName,
usersTableIDFieldName,
usersTableName,
usersTableLoginFieldName); // TODO: to remember method with names, not numbers
jdbcTemplate.update(query.toString(), new Object[] {title, login, filePath});
}
@Override
public List<FeedPost> getFreshPosts(int countGot, int countToGet) throws DataAccessException{
String query = MessageFormat.format(
"SELECT {1}, {2}, (SELECT {3} FROM {4} WHERE {5} = {0}.{6}), {7}, {8} FROM {0} ORDER BY {7} DESC, {1} DESC LIMIT ?, ?",
postsTableName,
postsTableIDFieldName,
postsTableTitleFieldName,
usersTableLoginFieldName,
usersTableName,
usersTableIDFieldName,
postsTableUserIDFieldName,
postsTablePublishDateFieldName,
postsTablePictureNameFieldName);
try {
return jdbcTemplate.query(query, new Object[] {countGot, countToGet}, new PostMapper());
} catch(EmptyResultDataAccessException ex) {
return new ArrayList<FeedPost>();
}
}
@Override
public List<FeedPostWithBanInfo> getFreshPostsWithBiggestBanInfo(int countGot, int countToGet) throws DataAccessException {
String query = MessageFormat.format(
//TODO: bad getting
"SELECT {0}.{3}, {0}.{9}, (SELECT {11} FROM {12} WHERE {13} = {0}.{10}) as {11}, {0}.{1}, {14}, ifnull({2}.{5}, true) as {5}, {2}.{6}, {2}.{7} "
+ "FROM (SELECT * FROM {0} ORDER BY {1} DESC, {3} DESC LIMIT ?, ?) as {0} "
+ "LEFT JOIN (SELECT {5}, {6}, {7}, {4} FROM {2} as pb1 WHERE {8} = "
+ "(SELECT {8} FROM {2} as pb2 WHERE {6} <= curdate() AND {7} >= curdate() AND pb1.{4} = pb2.{4} AND {7} = "
+ "(SELECT MAX({7}) FROM {2} as pb3 WHERE {6} <= curdate() AND {7} >= curdate() AND pb3.{4} = pb2.{4}) LIMIT 1)) as {2} "
+ "ON {2}.{4} = {0}.{3} ORDER BY {0}.{1} DESC, {0}.{3} DESC",
postsTableName,
postsTablePublishDateFieldName,
postsBannedTableName,
postsTableIDFieldName,
postsBannedTablePostIDFieldName,
postsBannedTableRemovedFieldName,
postsBannedTableFromDateFieldName,
postsBannedTableToDateFieldName,
postsBannedTableIDFieldName,
postsTableTitleFieldName,
postsTableUserIDFieldName,
usersTableLoginFieldName,
usersTableName,
usersTableIDFieldName,
postsTablePictureNameFieldName);
try {
return jdbcTemplate.query(query, new Object[] {countGot, countToGet}, new PostWithBanInfoMapper());
} catch(EmptyResultDataAccessException ex) {
return new ArrayList<FeedPostWithBanInfo>();
}
}
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public int changePostBanState(boolean isActive, int id) throws DataAccessException {
String query = MessageFormat.format(
"UPDATE {0} SET {1} = " + (isActive ? "true" : "false") + ", {2} = " + (isActive ? "curdate()" : "null") + " WHERE {3} = ?",
postsBannedTableName,
postsBannedTableRemovedFieldName,
postsBannedTableRemovedDateFieldName,
postsBannedTableIDFieldName);
return jdbcTemplate.update(query, new Object[] {id});
}
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public int changeCommentBanState(boolean isActive, int id) throws DataAccessException {
String query = MessageFormat.format(
"UPDATE {0} SET {1} = " + (isActive ? "true" : "false") + ", {2} = " + (isActive ? "curdate()" : "null") + " WHERE {3} = ?",
postCommentsBannedTableName,
postCommentsBannedTableRemovedFieldName,
postCommentsBannedTableRemovedDateFieldName,
postCommentsBannedTableIDFieldName);
return jdbcTemplate.update(query, new Object[] {id});
}
@Override
public boolean existsPost(int id) throws DataAccessException, IllegalStateException {
String query = MessageFormat.format(
"SELECT COUNT(*) FROM {0} WHERE {1} = ?",
postsTableName,
postsTableIDFieldName);
int accountsCount = jdbcTemplate.queryForObject(query, new Object[] {id}, Integer.class);
if(accountsCount == 1) {
return true;
}
if(accountsCount == 0) {
return false;
}
throw new IllegalStateException("DB unique id error"); // don't need to be localized
}
@Override
public boolean existsComment(int id) throws DataAccessException, IllegalStateException {
String query = MessageFormat.format(
"SELECT COUNT(*) FROM {0} WHERE {1} = ?",
postCommentsTableName,
postCommentsTableIDFieldName);
int accountsCount = jdbcTemplate.queryForObject(query, new Object[] {id}, Integer.class);
if(accountsCount == 1) {
return true;
}
if(accountsCount == 0) {
return false;
}
throw new IllegalStateException("DB unique id error"); // don't need to be localized
}
@Override
public List<Ban> getPostBans(int id, int from, int to) throws DataAccessException {
String query = MessageFormat.format(
"SELECT {0}, {1}, {2}, {3}, {4} FROM {5} WHERE {6} = ? ORDER BY {1} DESC, {0} DESC LIMIT ?, ?",
postsBannedTableIDFieldName,
postsBannedTableFromDateFieldName,
postsBannedTableToDateFieldName,
postsBannedTableRemovedFieldName,
postsBannedTableRemovedDateFieldName,
postsBannedTableName,
postsBannedTablePostIDFieldName);
try {
return jdbcTemplate.query(query, new Object[] {id, from, to} , new BanMapperForPost());
} catch(EmptyResultDataAccessException ex) {
return new ArrayList<Ban>();
}
}
@Override
public List<Ban> getCommentBans(int id, int from, int to) throws DataAccessException {
String query = MessageFormat.format(
"SELECT {0}, {1}, {2}, {3}, {4} FROM {5} WHERE {6} = ? ORDER BY {1} DESC, {0} DESC LIMIT ?, ?",
postCommentsBannedTableIDFieldName,
postCommentsBannedTableFromDateFieldName,
postCommentsBannedTableToDateFieldName,
postCommentsBannedTableRemovedFieldName,
postCommentsBannedTableRemovedDateFieldName,
postCommentsBannedTableName,
postCommentsBannedTableCommentIDFieldName);
try {
return jdbcTemplate.query(query, new Object[] {id, from, to} , new BanMapperForPost());
} catch(EmptyResultDataAccessException ex) {
return new ArrayList<Ban>();
}
}
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public int banPost(Date from, Date to, int id) throws DataAccessException {
String query = MessageFormat.format(
"INSERT INTO {0} ({1}, {2}, {3}) VALUES (?, ?, ?)",
postsBannedTableName,
postsBannedTablePostIDFieldName,
postsBannedTableFromDateFieldName,
postsBannedTableToDateFieldName);
int countBanned = jdbcTemplate.update(query, new Object[] {id, dbDateFormater.format(from), dbDateFormater.format(to)});
return countBanned;
}
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public int banComment(Date from, Date to, int id) throws DataAccessException {
String query = MessageFormat.format(
"INSERT INTO {0} ({1}, {2}, {3}) VALUES (?, ?, ?)",
postCommentsBannedTableName,
postCommentsBannedTableCommentIDFieldName,
postCommentsBannedTableFromDateFieldName,
postCommentsBannedTableToDateFieldName);
int countBanned = jdbcTemplate.update(query, new Object[] {id, dbDateFormater.format(from), dbDateFormater.format(to)});
return countBanned;
}
@Override
public boolean hasPostBan(int id) throws DataAccessException{
String query = MessageFormat.format(
"SELECT COUNT(*) FROM {0} WHERE {1} = ?",
postsBannedTableName,
postsBannedTableIDFieldName);
int bansCount = jdbcTemplate.queryForObject(query, new Object[] {id}, Integer.class);
if(bansCount > 0) {
return true;
}
return false;
}
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public boolean hasCommentBan(int id) throws DataAccessException {
String query = MessageFormat.format(
"SELECT COUNT(*) FROM {0} WHERE {1} = ?",
postCommentsBannedTableName,
postCommentsBannedTableIDFieldName);
int bansCount = jdbcTemplate.queryForObject(query, new Object[] {id}, Integer.class);
if(bansCount > 0) {
return true;
}
return false;
}
@Override
public boolean isPostBanned(int id) throws DataAccessException {
String query = MessageFormat.format(
"SELECT COUNT(*) FROM {0} WHERE {1} = ? AND {2} = false",
postsBannedTableName,
postsBannedTablePostIDFieldName,
postsBannedTableRemovedFieldName);
return 0 < jdbcTemplate.queryForObject(query, new Object[] {id}, Integer.class) ;
}
@Override
public int countOfPostsToday(String login) throws DataAccessException {
String query = MessageFormat.format(
"SELECT COUNT(*) FROM {0} WHERE {1} = curdate() AND {2} = (SELECT {3} FROM {4} WHERE {5} = ?)",
postsTableName,
postsTablePublishDateFieldName,
postsTableUserIDFieldName,
usersTableIDFieldName,
usersTableName,
usersTableLoginFieldName);
return jdbcTemplate.queryForObject(query, new Object[] {login}, Integer.class);
}
@Override
public int getCountPostsBefore(int id) throws DataAccessException {
String query = MessageFormat.format(
"SELECT COUNT(*) FROM {0} WHERE {1} > ?", // id should indicate order of publish!
postsTableName,
postsBannedTableIDFieldName);
return jdbcTemplate.queryForObject(query, new Object[] {id}, Integer.class);
}
@Override
public int getPostBansCountBefore(int banId) throws DataAccessException {
String query = MessageFormat.format(
"SELECT COUNT(*) FROM {0} WHERE {1} > ?",
postsBannedTableName,
postsBannedTableIDFieldName);
return jdbcTemplate.queryForObject(query, new Object[] {banId}, Integer.class);
}
@Override
public int getCommentBansCountBefore(int banId) throws DataAccessException {
String query = MessageFormat.format(
"SELECT COUNT(*) FROM {0} WHERE {1} > ?",
postCommentsBannedTableName,
postCommentsBannedTableIDFieldName);
return jdbcTemplate.queryForObject(query, new Object[] {banId}, Integer.class);
}
@Override
public int getCommentsCountUnderPostBefore(int idOfComment) throws DataAccessException {
String query = MessageFormat.format(
"SELECT COUNT(*) FROM {0} WHERE {1} = (SELECT {1} FROM {0} WHERE {2} = ?) AND {1} > ?",
postCommentsTableName,
postCommentsTablePostIDFieldName,
postCommentsTableIDFieldName);
return jdbcTemplate.queryForObject(query, new Object[] {idOfComment, idOfComment}, Integer.class);
}
@Override
public int getPostIDByCommentID(int id) throws DataAccessException {
String query = MessageFormat.format(
"SELECT {0} FROM {1} WHERE {2} = ?",
postCommentsTablePostIDFieldName,
postCommentsTableName,
postCommentsTableIDFieldName);
return jdbcTemplate.queryForObject(query, new Object[] {id}, Integer.class);
}
@Override
public List<PostCommentWithBanInfo> getFreshCommentsWithBiggestBanInfo(int postID, int countGot, int countToGet) throws DataAccessException {
String query = MessageFormat.format(
//TODO: bad getting
"SELECT pc1.{1}, pc1.{2}, (SELECT {8} FROM {6} WHERE {7} = pc1.{3}) as {8}, pc1.{4}, "
+ "ifnull(cb1.{10}, true) as {10}, cb1.{11}, cb1.{12} "
+ "FROM (SELECT {1}, {2}, {3}, {4} FROM {0} WHERE {5} = ? ORDER BY {4}, {1} LIMIT ?, ?) as pc1 "
+ "LEFT JOIN (SELECT {10}, {11}, {12}, {13} FROM {9} as cb1 WHERE {11} <= curdate() AND {12} >= curdate() "
+ "AND {12} = (SELECT MAX({12}) FROM {9} as cb2 WHERE {11} <= curdate() AND {12} >= curdate() AND cb1.{13} = cb2.{13}) LIMIT 1) as cb1 "
+ "ON pc1.{1} = cb1.{13} ORDER BY pc1.{4}, pc1.{1}",
postCommentsTableName, // 0
postCommentsTableIDFieldName, // 1
postCommentsTableTextFieldName, // 2
postCommentsTableUserIDFieldName, // 3
postCommentsTableDateFieldName, // 4
postCommentsTablePostIDFieldName, // 5
usersTableName, // 6
usersTableIDFieldName, // 7
usersTableLoginFieldName, // 8
postCommentsBannedTableName, // 9
postCommentsBannedTableRemovedFieldName, // 10
postCommentsBannedTableFromDateFieldName, // 11
postCommentsBannedTableToDateFieldName, // 12
postCommentsBannedTableCommentIDFieldName // 13
);
try {
return jdbcTemplate.query(query, new Object[] {postID, countGot, countToGet}, new PostCommentWithBanInfoMapper());
} catch(EmptyResultDataAccessException ex) {
return new ArrayList<PostCommentWithBanInfo>();
}
}
@Override
public int createComment(int postID, String login, String text) throws DataAccessException {
String query = MessageFormat.format(
"INSERT INTO {0} ({1}, {2}, {3}, {4}) VALUES (?, (SELECT {5} FROM {6} WHERE {7} = ?), ?, curdate())",
postCommentsTableName,
postCommentsTablePostIDFieldName,
postCommentsTableUserIDFieldName,
postCommentsTableTextFieldName,
postCommentsTableDateFieldName,
usersTableIDFieldName,
usersTableName,
usersTableLoginFieldName);
return jdbcTemplate.update(query, new Object[] {postID, login, text});
}
@Override
public int getCommentsCountPerDay(String login) throws DataAccessException {
String query = MessageFormat.format(
"SELECT COUNT(*) FROM {0} WHERE {1} = curdate() AND {2} = (SELECT {3} FROM {4} WHERE {5} = ?)",
postCommentsTableName,
postCommentsTableDateFieldName,
postCommentsTableUserIDFieldName,
usersTableIDFieldName,
usersTableName,
usersTableLoginFieldName);
return jdbcTemplate.queryForObject(query, new Object[] {login}, Integer.class);
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>A comment on the DDL</h2>\n<p>Despite this using MySQL (which would never be my first choice), the schema seems pretty sane; good job. This surprised me:</p>\n<pre><code>removed_date date default null\n</code></pre>\n<p>but then, reading the <a href=\"https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html\" rel=\"nofollow noreferrer\">documentation</a>, MySQL does a nonsensical thing by default and uses the "zero" value for a date as its default; so what you've done is correct.</p>\n<p>For these two columns:</p>\n<pre><code>_from date not null,\n_to date not null,\n</code></pre>\n<p>If you didn't want an underscore, you can instead use <a href=\"https://stackoverflow.com/questions/2889871/how-do-i-escape-reserved-words-used-as-column-names-mysql-create-table\">quote escaping</a>.</p>\n<p>For columns like these:</p>\n<pre><code>removed boolean default false,\n</code></pre>\n<p>you should consider making them <code>not null</code>.</p>\n<h2>User table</h2>\n<pre><code>insert into users\n(name, password, access_level_id, creation_date)\nVALUES\n ('root', '123321a', 2, curdate());\n</code></pre>\n<p>First of all, you should be able to make the current date the default for <code>creation_date</code> so that you don't actually need to specify it in the <code>insert</code>. Second and certainly the most concerning thing I see in all of this code is what appears to be a plain-text password. Never, ever, ever, ever put a plaintext password in a database. I implore to you have a careful read through <a href=\"https://stackoverflow.com/questions/7270526/how-do-you-securely-store-a-users-password-and-salt-in-mysql\">https://stackoverflow.com/questions/7270526/how-do-you-securely-store-a-users-password-and-salt-in-mysql</a> , or similar articles, noting that some suggest MD5 which should be avoided due to cryptographic weakness. It is crucial to hash and salt passwords.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T11:14:54.957",
"Id": "479638",
"Score": "0",
"body": "Do you have any remarks about queries(`MySQLPostDAO`, `MySQLUserDAO`)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T14:16:58.567",
"Id": "479655",
"Score": "1",
"body": "No, because they aren't included in the body of the question. If you want them to be reviewed they should be included in-line rather than linked to a repository."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T05:38:49.257",
"Id": "479724",
"Score": "0",
"body": "I cannot include all my code in question, because my code has too many symbols. I tried. But I noticed a limitation when I finished including `DAOs` package. I cannot include all code physically."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T05:49:36.787",
"Id": "479726",
"Score": "0",
"body": "I ll try to include only important files, but i think, that it will be bad without others"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T07:20:05.297",
"Id": "479732",
"Score": "0",
"body": "Files have been added to the question on request."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T19:05:06.607",
"Id": "479787",
"Score": "0",
"body": "What about making the [Wikipedia article](https://en.wikipedia.org/wiki/Key_derivation_function) barely readable for laymen and then linking to it? ;)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T15:14:16.507",
"Id": "244268",
"ParentId": "244045",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T13:30:50.763",
"Id": "244045",
"Score": "3",
"Tags": [
"java",
"mvc",
"database",
"spring"
],
"Title": "Meme (title with picture) exchanger"
}
|
244045
|
<p>I want to abstract some code which does a bunch of checks and returns a boolean - since I am using the business logic in several places. But I also want to get back the reason why, if it was returned FALSE. I have this in mind...</p>
<pre><code>class ContactCanBeContactedCheck
{
public $not_contactable_reason;
const REASON_DECEASED = 0;
const REASON_OPTED_OUT = 1;
public function __invoke(Contact $contact)
{
// Deceased
if ($contact->is_deceased) {
$this->not_contactable_reason = static::REASON_DECEASED;
return FALSE;
}
// Opted out
if ($contact->opt_out) {
$this->not_contactable_reason = static::REASON_OPTED_OUT;
return FALSE;
}
return TRUE;
}
}
</code></pre>
<p>I would then call the code like so...</p>
<pre><code>$contact_can_be_contacted_check = new ContactCanBeContactedCheck;
$contact_can_be_contacted_check($contact);
$reason = $contact_can_be_contacted_check->not_contactable_reason;
</code></pre>
<p>I think this must be a well-trodden path: needing a decision, plus a reason for said decision. Is this a suitable approach or is there another more widely accepted?</p>
|
[] |
[
{
"body": "<p>In this case, quite often, the answer is to create some type of "enumeration" where one value means "success" and the rest are reasons for failure.</p>\n<p>In your example, just a minor change:</p>\n<pre><code>class ContactCanBeContactedCheck\n{\n const SUCCESS = 0;\n const FAILURE_REASON_DECEASED = 1;\n const FAILURE_REASON_OPTED_OUT = 2;\n\n public function __invoke(Contact $contact)\n {\n // Deceased\n if ($contact->is_deceased) {\n return static::FAILURE_REASON_DECEASED;\n }\n\n // Opted out\n if ($contact->opt_out) {\n return static::FAILURE_REASON_OPTED_OUT;\n }\n\n return static::SUCCESS;\n }\n}\n</code></pre>\n<p>Of course, now, you can make <code>__invoke</code> a <code>static</code> function, because all of the decision logic is within.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T17:16:21.910",
"Id": "479257",
"Score": "0",
"body": "Great - thanks. This is a much better approach and removes the slightly accident-prone $not_contactable_reason state variable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T16:29:38.880",
"Id": "244058",
"ParentId": "244047",
"Score": "3"
}
},
{
"body": "<blockquote>\n<p>I want to abstract some code...</p>\n</blockquote>\n<p>What is it that you actually want to abstract?</p>\n<p>Unless you are going to pass an instance of <code>ContactCanBeContactedCheck</code> class to someone who expects a <code>callable</code>, you shouldn't implement it through <code>__invoke</code> method.</p>\n<p>My first though was, why not make it a method of the <code>Contact</code> class?</p>\n<pre><code>class Contact\n{\n public const NOT_CONTACTABLE_REASON_DECEASED = 1;\n public const NOT_CONTACTABLE_REASON_OPTED_OUT = 2;\n\n // ...\n\n public function getNotContactableReason(): ?int\n {\n if ($this->is_deceased) {\n return static::NOT_CONTACTABLE_REASON_DECEASED;\n }\n\n if ($this->opt_out) {\n return static::NOT_CONTACTABLE_REASON_OPTED_OUT;\n }\n\n return null;\n }\n}\n</code></pre>\n<p>Now it is contained in the class that actualy has the data to tell the reason. Encapsulation is one of the fundamental principles of OOP.</p>\n<p>Still, if you need a callable, you can now do just</p>\n<pre><code>$callback = fn (Contact $contact): ?int => $contact->getNotContactableReason();\n</code></pre>\n<p>Also your method is trying to do 2 things</p>\n<ul>\n<li>tell if the contact is contactable</li>\n<li>tell the reason why it is not contactable</li>\n</ul>\n<p>My method only tells the reason why it is not contactable, and null if there is no reason, because the contact <strong>is</strong> contactable. Using this approach you are actually able to tell both those things using just this one method as well. But it is not intent to do two things like in your method. It's just a side effect. And that makes a big difference.</p>\n<p>You could add another method that would just tell whether it is contactable regardless of reason, but it is now easy enough to tell from the first method as well, so the second method would be just sugar for <code>$this->getNotContactableReason() === null</code>.</p>\n<p>Notice I started the constants at 1, not 0. Zero is falsey, just like null.\nAnd using zero could then easily lead to mistakes if you use weak comparision.</p>\n<pre><code>if ($reason) {...}\n</code></pre>\n<p>vs.</p>\n<pre><code>if ($reason !== null) {...}\n</code></pre>\n<p>I am wondering though, what you are actually doing with the class and the resulting reason. If the reason ends up in a switch or an if, then the entire method is useless and you should branch your code based directly on the <code>$is_deceased</code> and <code>$opt_out</code> properties.</p>\n<p>Those 3 lines of usage are far from enough to tell what you really need. If I had more, I could target my review much better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T17:13:32.353",
"Id": "479256",
"Score": "0",
"body": "Yeah, nice - thanks. The abstraction is simply due to the fact that two independant parts of the app need to know if a Contact is 'contactable' - so all the logic within this new class I've thought up, are taking inline logic to a single place.\n\nI did want to keep this on the main Contact model, and now we've dropped the need for that $not_contactable_reason state variable, this now works better. Although, I was partly taking it out of the Contact model due to it being such a big thing in itself. But agree with you on the idea of it being part of the main Contact model. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T17:18:05.943",
"Id": "244062",
"ParentId": "244047",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "244062",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T13:50:09.353",
"Id": "244047",
"Score": "3",
"Tags": [
"php",
"design-patterns"
],
"Title": "PHP Status class : pattern or anti-pattern"
}
|
244047
|
<p>I have built a COVID model using UVA data. Currently that data is unavailable so I'm using another source. The new source is, of course, a different format. So rather than refactor all of my model macros, I'm formatting the new data in the old format on import.</p>
<p>The new data looks like this:</p>
<p><a href="https://i.stack.imgur.com/L6TgR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L6TgR.png" alt="enter image description here" /></a></p>
<p>The xlsx files go out to column EH with a new column added daily. There are 267 rows in these files. The import function ends up with a file that looks like this:</p>
<p><a href="https://i.stack.imgur.com/mM93h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mM93h.png" alt="enter image description here" /></a></p>
<p>In this file I don't import all the Confirmed = 0 and I wind up deleting a bunch of the countries using the population column (population = 0 gets deleted). So the file end up with about 6800 rows. This will grow daily also.</p>
<p>I have a file for confirmed, another for deaths, and a third for recovered. Importing the Confirmed and deleting what I don't want takes about a minute. When I try to add in the Deaths file, I can see the column being filled in with the correct numbers from the new data but it's taking so long I can't imagine waiting for it to end. I've waited over 30 minutes before hitting <kbd>Esc</kbd> and Deaths still won't be finished.</p>
<p>I realize I'm going through a lot of cells a lot of times. So, is there a way to optimize my nested For loops in the Deaths and Recovered file imports to still be in the desired format yet not take over half an hour?</p>
<pre><code>Option Explicit
Sub ImportCSSEConfirmed()
Dim i As Variant
Dim j As Variant
Dim lastrow As Long
Dim clastrow As Long
Dim lastcol As Long
Dim currentData As Range
Dim filePath As String
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim cws As Excel.Worksheet
Set cws = ThisWorkbook.Sheets("Raw_Data")
lastrow = cws.Cells(Rows.count, "a").End(xlUp).Row
If lastrow < 2 Then lastrow = 2
Set currentData = cws.Range("a2:l" & lastrow)
currentData.ClearContents
filePath = "C:\Users\chris.h\Desktop\COVID\Other_Data\CSSE\CSSE_Confirmed.xlsx"
Set wb = Excel.Workbooks.Open(filePath)
Set ws = wb.Worksheets(1)
lastrow = ws.Cells(Rows.count, "b").End(xlUp).Row
lastcol = ws.Cells(1, Columns.count).End(xlToLeft).Column
clastrow = cws.Cells(Rows.count, "a").End(xlUp).Row + 1
'takes the csse data files and combines and reformats them into the raw_data sheet in the combined file
'col a = province/state, col b = country, col c = date, col d = confirmed
For i = 2 To lastrow
For j = 3 To lastcol
If ws.Cells(i, j).Value <> 0 Then
cws.Cells(clastrow, "a").Value = ws.Cells(i, 1).Value
cws.Cells(clastrow, "b").Value = ws.Cells(i, 2).Value
cws.Cells(clastrow, "c").Value = ws.Cells(1, j).Value
cws.Cells(clastrow, "d").Value = ws.Cells(i, j).Value
cws.Cells(clastrow, "d").NumberFormat = "#,##0"
clastrow = clastrow + 1
End If
Next j
Next i
wb.Close False
Call PopulationColumn
Call DeleteExtras
predictDone = False
End Sub
Sub ImportCSSEDeaths()
Dim i As Variant
Dim j As Variant
Dim k As Variant
Dim lastrow As Long
Dim clastrow As Long
Dim lastcol As Long
Dim dte As Date
Dim filePath As String
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim cws As Excel.Worksheet
Dim t As Double
Dim tt As String
t = Timer
Set cws = ThisWorkbook.Sheets("Raw_Data")
lastrow = cws.Cells(Rows.count, "a").End(xlUp).Row
filePath = "C:\Users\chris.h\Desktop\COVID\Other_Data\CSSE\CSSE_Deaths.xlsx"
Set wb = Excel.Workbooks.Open(filePath)
Set ws = wb.Worksheets(1)
clastrow = cws.Cells(Rows.count, "b").End(xlUp).Row
lastrow = ws.Cells(Rows.count, "b").End(xlUp).Row
lastcol = ws.Cells(1, Columns.count).End(xlToLeft).Column
For i = 2 To clastrow
For j = 2 To lastrow
For k = 3 To lastcol
If cws.Cells(i, "a").Value = ws.Cells(j, "a").Value And _
cws.Cells(i, "b").Value = ws.Cells(j, "b").Value And _
cws.Cells(i, "c").Value = ws.Cells(1, k).Value Then
cws.Cells(i, "e").Value = ws.Cells(j, k).Value
cws.Cells(i, "e").NumberFormat = "#,##0"
End If
Next k
Next j
Next i
wb.Close False
tt = Format((Timer - t) / 86400, "hh:mm:ss")
predictDone = False
End Sub
Sub ImportCSSERecovered()
Dim i As Variant
Dim j As Variant
Dim k As Variant
Dim lastrow As Long
Dim clastrow As Long
Dim lastcol As Long
Dim dte As Date
Dim filePath As String
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim cws As Excel.Worksheet
Set cws = ThisWorkbook.Sheets("Raw_Data")
lastrow = cws.Cells(Rows.count, "a").End(xlUp).Row
filePath = "C:\Users\chris.h\Desktop\COVID\Other_Data\CSSE\CSSE_Deaths.xlsx"
Set wb = Excel.Workbooks.Open(filePath & fileName)
Set ws = wb.Worksheets(1)
clastrow = cws.Cells(Rows.count, "b").End(xlUp).Row
lastrow = ws.Cells(Rows.count, "b").End(xlUp).Row
lastcol = ws.Cells(1, Columns.count).End(xlToLeft).Column
For i = 2 To clastrow
For j = 2 To lastrow
For k = 3 To lastcol
If cws.Cells(i, "a").Value = ws.Cells(j, "a").Value And _
cws.Cells(i, "b").Value = ws.Cells(j, "b").Value And _
cws.Cells(i, "c").Value = ws.Cells(1, k).Value Then
cws.Cells(i, "f").Value = ws.Cells(j, k).Value
cws.Cells(i, "f").NumberFormat = "#,##0"
End If
Next k
Next j
Next i
wb.Close False
predictDone = False
End Sub
Sub PopulationColumn()
Dim i As Variant
Dim country As String
Dim state As String
Dim rng As Range
Dim lastrow As Long
Dim population As Long
Dim landarea As Double
Dim popdensity As Double
Dim cws As Worksheet
Set cws = ThisWorkbook.Worksheets("Raw_Data")
lastrow = cws.Cells(Rows.count, "b").End(xlUp).Row
Set rng = cws.Range("b2:b" & lastrow)
For Each i In rng
country = i
state = cws.Cells(i.Row, "a").Value
If country = "United Arab Emirates" Then
population = 9890402
landarea = 32278
popdensity = population / landarea
ElseIf country = "Iran" Then
population = 83992949
landarea = 628786
popdensity = population / landarea
ElseIf country = "Oman" Then
population = 5080712
landarea = 119499
popdensity = population / landarea
ElseIf country = "Kuwait" Then
population = 4270571
landarea = 6880
popdensity = population / landarea
ElseIf country = "Bahrain" Then
population = 1701575
landarea = 293
popdensity = population / landarea
ElseIf country = "Iraq" Then
population = 40222493
landarea = 167692
popdensity = population / landarea
ElseIf country = "Pakistan" Then
population = 220892340
landarea = 297638
popdensity = population / landarea
ElseIf country = "Qatar" Then
population = 2881053
landarea = 4483
popdensity = population / landarea
ElseIf country = "Jordan" Then
population = 10203134
landarea = 34278
popdensity = population / landarea
ElseIf country = "Saudi Arabia" Then
population = 34810000
landarea = 830000
popdensity = population / landarea
ElseIf country = "Kazakhstan" Then
population = 18776707
landarea = 1042360
popdensity = population / landarea
ElseIf country = "Syria" Then
population = 17500658
landarea = 70900
popdensity = population / landarea
ElseIf country = "Yemen" Then
population = 29825964
landarea = 203850
popdensity = population / landarea
ElseIf country = "Afghanistan" Then
population = 38928346
landarea = 252071
popdensity = population / landarea
ElseIf country = "Italy" Then
population = 60478457
landarea = 113568
popdensity = population / landarea
ElseIf country = "France" Then
population = 65273511
landarea = 211413
popdensity = population / landarea
ElseIf country = "South Korea" Then
population = 51269185
landarea = 37541
popdensity = population / landarea
ElseIf country = "Spain" Then
population = 46754778
landarea = 192588
popdensity = population / landarea
ElseIf state = "South Carolina" Then
population = 5210095
landarea = 30111
popdensity = population / landarea
ElseIf state = "Texas" Then
population = 29472295
landarea = 261914
popdensity = population / landarea
ElseIf state = "Georgia" Then
population = 10736059
landarea = 57919
popdensity = population / landarea
ElseIf state = "Kentucky" Then
population = 4499692
landarea = 39732
popdensity = population / landarea
ElseIf state = "North Carolina" Then
population = 10611862
landarea = 48718
popdensity = population / landarea
ElseIf country = "United Kingdom" Then
population = 67886011
landarea = 93410
popdensity = population / landarea
ElseIf country = "Switzerland" Then
population = 8654281
landarea = 15257
popdensity = population / landarea
ElseIf country = "Hungary" Then
population = 9660351
landarea = 34954
popdensity = population / landarea
ElseIf country = "Turkey" Then
population = 84339067
landarea = 297156
popdensity = population / landarea
ElseIf country = "Portugal" Then
population = 10196709
landarea = 35363
popdensity = population / landarea
ElseIf country = "Austria" Then
population = 9010000
landarea = 31818
popdensity = population / landarea
ElseIf country = "Poland" Then
population = 37846611
landarea = 118236
popdensity = population / landarea
ElseIf country = "Germany" Then
population = 83783942
landarea = 134580
popdensity = population / landarea
ElseIf country = "Egypt" Then
population = 102334404
landarea = 384345
popdensity = population / landarea
ElseIf state = "Kansas" Then
population = 2910357
landarea = 81823
popdensity = population / landarea
ElseIf country = "Argentina" Then
population = 45516865
landarea = 1056641
popdensity = population / landarea
ElseIf country = "Belize" Then
population = 397628
landarea = 8807
popdensity = population / landarea
ElseIf country = "Norway" Then
population = 5413094
landarea = 141031
popdensity = population / landarea
ElseIf country = "Finland" Then
population = 5540720
landarea = 117333
popdensity = population / landarea
ElseIf country = "Japan" Then
population = 126476461
landarea = 140755
popdensity = population / landarea
ElseIf country = "Australia" Then
population = 25701300
landarea = 2969907
popdensity = population / landarea
ElseIf state = "Colorado" Then
population = 5845526
landarea = 103730
popdensity = population / landarea
ElseIf state = "Oregon" Then
population = 4301089
landarea = 96105
popdensity = population / landarea
ElseIf country = "Sweden" Then
population = 10087218
landarea = 173860
popdensity = population / landarea
Else
population = 0
popdensity = 0
End If
cws.Cells(i.Row, "h").Value = population
cws.Cells(i.Row, "i").Value = popdensity
Next i
cws.Range("h2:h" & lastrow).NumberFormat = "#,##0"
cws.Range("i2:i" & lastrow).NumberFormat = "#,##0"
End Sub
Sub DeleteExtras()
Dim lastrow As Long
Dim rng As Range
Dim i As Variant
Dim count As Integer
Dim cws As Worksheet
Set cws = ThisWorkbook.Worksheets("Raw_Data")
lastrow = cws.Cells(Rows.count, "b").End(xlUp).Row
Set rng = cws.Range("h2:h" & lastrow)
count = 0
Do While count <= 10
For Each i In rng
If i = 0 Then
i.EntireRow.Delete
End If
Next i
count = count + 1
Loop
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T17:46:36.467",
"Id": "479128",
"Score": "0",
"body": "Can you post the code for `PopulationColumn()` and `DeleteExtras()`? As is, this doesn't compile and those could likely be optimized as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T18:42:51.417",
"Id": "479131",
"Score": "0",
"body": "The Population and Pop Density columns are just a list of interested countries. The states that are still in the list are from the UVA data. My new data set is only outside the US.I left them in the Sub becuase I just haven't gotten around to deleting them yet. The DeleteExtra Sub is looped because for some reason it doesn't catch all the 0 values the first time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T14:19:37.470",
"Id": "479214",
"Score": "0",
"body": "The question may be OBE. I've broken up the three loops into seperate macros and changed the order of the nesting. I did this so I could manage the new data files easier. I've also put a timer on the Deaths and Recovered macros. I will edit the above to reflect the new code and the actual time it takes to run."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:10:00.667",
"Id": "479227",
"Score": "0",
"body": "In the second and the third loop you are looping on rows twice (clastrow and lastrow also). So, if the both rows are say 500 then it will loop 500*500=250000 times. It will take huge time. In the first loop, you are incrementing clastrow by 1 in every loop. Do the same in second and third loop. Before `For i = 2 To clastrow` mention `lastrow = 2` and before i loop ends increment lastrow by 1. So you can remove For j loop."
}
] |
[
{
"body": "<p>I have analyzed your code and suggest the following changes:</p>\n<ul>\n<li><p>the second loop over <code>j</code> to find the <code>startdate</code> is superfluous and can be included in the search loop by using a simple <code>if</code>.</p>\n</li>\n<li><p>avoid using <code>Redim Preserve</code> in a loop, it's time consuming as each time the array has to be copied completely; <code>Dim</code> the array once to a set maximum and shorten it once after the loop.</p>\n</li>\n<li><p>from your code I am deducting that the array <code>deaths()</code> is filled from scratch for each loop over <code>i</code>. Therefore, <code>k</code> should be set to zero within the <code>i</code>-loop.</p>\n</li>\n<li><p>in the end, the whole array <code>deaths()</code> is copied cell-by-cell to a target range. This can be done in one statement, which is multiple times faster than touching each element.</p>\n<pre><code> Sub ImportCSSEDeaths()\n\n Dim i As Long, j As Long, k As Long\n Dim lastrow As Long, clastrow As Long, lastcol As Long\n Dim deaths() As Long\n Dim startDate As Date\n Dim filePath As String\n Dim wb As Excel.Workbook, ws As Excel.Worksheet, cws As Excel.Worksheet\n\n Set cws = ThisWorkbook.Sheets("Raw_Data")\n clastrow = cws.Cells(Rows.count, "b").End(xlUp).row\n\n filePath = "C:\\Users\\chris.h\\Desktop\\COVID\\Other_Data\\CSSE\\CSSE_Deaths.xlsx"\n Set wb = Excel.Workbooks.Open(filePath)\n Set ws = wb.Worksheets(1)\n lastrow = ws.Cells(Rows.count, "b").End(xlUp).row\n lastcol = ws.Cells(1, Columns.count).End(xlToLeft).Column\n\n For i = 2 To lastrow\n 'puts country row deaths into array\n With ws\n k = 0 ' deaths() is zero-based! Option Base 0\n ReDim deaths(lastcol) ' cannot get larger than this\n For j = 3 To lastcol\n If .Cells(i, j).Value <> 0 Then\n deaths(k) = .Cells(i, j).Value\n If k = 0 Then\n startDate = .Cells(1, j).Value\n End If\n k = k + 1\n End If\n Next j\n End With\n ReDim Preserve deaths(k - 1) ' shrink once to actual size\n\n 'finds startdate in compiled data and enters array values down column E\n With cws\n For j = 2 To clastrow\n If .Cells(j, "a").Value = ws.Cells(i, "a").Value And _\n .Cells(j, "b").Value = ws.Cells(i, "b") And _\n .Cells(j, "c").Value = startDate Then\n ' copy deaths(0..ub) to .cells(j..ub+j,"e") in one step\n Dim dest As Range\n Set dest = .Cells(j, "e") ' first cell in destination\n Set dest = dest.Resize(UBound(deaths) + 1, 1)\n dest.Value = Application.Transpose(deaths)\n End If\n Next j\n End With\n Next i\n\n wb.Close False\n End Sub ' ImportCSSEDeaths()\n</code></pre>\n</li>\n</ul>\n<p><strong>Edit: delete rows with a null value</strong></p>\n<p>Following your comment, your routine <code>Delete_Extras()</code> not only searches row-by-row but does so for 11 times. You will probably have noticed that not all matching lines got deleted on the first pass.<br />\nOne way to fix this is to loop from the end to the beginning of the range, so that deleting a row does not affect rows yet unprocessed.<br />\nInstead, I suggest the following: filter the range for a "0" in column H and delete all visible rows in one command, like this</p>\n<pre><code> Sub Delete_Extra_Rows_Based_On_Value()\n ' autofilter a range and delete visible rows\n ' 2020-07-01\n \n Dim cws As Worksheet\n Dim lastrow As Long\n Dim result As Range\n \n Set cws = ThisWorkbook.Worksheets("H:\\Raw_Data")\n lastrow = cws.Cells(Rows.count, "B").End(xlUp).row\n \n With Application\n .ScreenUpdating = False\n .EnableEvents = False\n .Calculation = xlCalculationManual\n .DisplayAlerts = False\n End With\n \n ' clear any existing filters\n If cws.AutoFilterMode Then cws.ShowAllData\n ' apply filter\n With cws.Range("A1:H" & lastrow)\n .AutoFilter Field:=8, Criteria1:=0\n ' delete matching rows\n .Offset(1, 0).SpecialCells(xlCellTypeVisible).Delete\n .AutoFilter\n End With\n \n With Application\n .ScreenUpdating = True\n .EnableEvents = True\n .Calculation = xlCalculationAutomatic\n .DisplayAlerts = True\n End With\n End Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T12:42:04.277",
"Id": "480418",
"Score": "0",
"body": "This is awesome! Thank you so much! I caught the ```k=0``` should be inside the first loop after posting but the rest is all new. This teaches me a lot actually."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T13:59:32.100",
"Id": "480423",
"Score": "0",
"body": "I was getting an out of bounds error at ```ReDim Preserve deaths(k - 1)``` so I changed it to ```ReDim Preserve deaths(k)``` and it removed the error. Honestly I'm not sure why this removed the error but it did. Now the biggest time suck on this process is removing the countries I don't track (```population = 0```). Which takes anywhere from 3 minutes to 20 depending on what else is happening on the computer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T13:12:53.950",
"Id": "480593",
"Score": "0",
"body": "Yes I wasn't sure if `ReDim` takes the length or the highest index as parameter. For the other sub, have you already posted it here, as a new post?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T14:21:23.200",
"Id": "480682",
"Score": "0",
"body": "I actually cut off screen updateing on each sub and it really sped things up. Delete extras takes about a minute, now. The whole model takes around 2 minutes to run, which is totally exceptable. If that changes, I'll definitely post another question. Thank you so much!!!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T15:23:16.173",
"Id": "480686",
"Score": "0",
"body": "please see the sub I added - we missed each other while I was writing it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T20:57:47.993",
"Id": "480726",
"Score": "0",
"body": "That cut down the DeleteExtras to about 1 sec! Wow! I would have never thought to filter and delete visible rows! Thank you so much. That will be a handy tool."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T14:52:58.143",
"Id": "244574",
"ParentId": "244053",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244574",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T14:59:16.740",
"Id": "244053",
"Score": "3",
"Tags": [
"vba",
"excel",
"macros",
"covid-19"
],
"Title": "COVID model using UVA data"
}
|
244053
|
<p>Our C++ professor told us to practise the use of std::function, lambda and pointers to functions.
He asked us to:</p>
<blockquote>
<p>Write the function
<code> std::function<bool(float)> interval(float low, float high)</code>. The function should accept two values <code>low</code> and <code>high</code> and should return a function.
The function returned will check if it's parameter is inside or outside the interval (low,high) and will return <code>true</code> or <code>false</code> accordingly.</p>
</blockquote>
<p>I tackled the problem with this code.</p>
<p>The function declaration:</p>
<pre><code>std::function<bool(float)> interval (float low,float high){
return [low,high](float f){ return (f > low) && (f < high); };
}
</code></pre>
<p>How is it used in the main:</p>
<pre><code>std::function<bool(float)> interval (float low,float high);
bool res = interval(10, 20)(150);
std::cout << res;
</code></pre>
<p>And it works.
But I am not sure how the solution is elegant, or "best practise".</p>
<p>In particular, this call <code>bool res = interval(10, 20)(150);</code> is what scares me.
It is really awful to call it like this.
How would you have done the excersize? Do you find my solution clear?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T17:04:44.403",
"Id": "479125",
"Score": "2",
"body": "\"Is it best practice\" isn't really a useful question for homework problems. The task is to use the technique. If you had something that you called like `interval(10, 20, 150)` that would be wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T17:13:13.560",
"Id": "479126",
"Score": "3",
"body": "On the other hand, it may help you to understand the value of this if you split up the call. For example, you could have `auto isLegalSpeed = interval(0, 60);` and on another line `if isLegalSpeed(currentSpeed)` which would be a lot more readable than `if interval(0, 60, currentSpeed)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T17:16:34.150",
"Id": "479127",
"Score": "2",
"body": "Even better, because these lambdas are objects, you can put them in data structures like maps and arrays. For example, you might have something like `speedCheck[highway] = interval(50, 70);` and `speedCheck[city] = interval(10, 30);` That allows for very powerful constructions indeed: if you had a list of speed camera readings from a list of roads, you could then test `speedCheck[roadType](speed)` for each reading instead of the much more verbose `if roadType == city {...`"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T15:42:39.090",
"Id": "244054",
"Score": "2",
"Tags": [
"c++",
"pointers",
"lambda"
],
"Title": "Using std::function to write a function that returns a function"
}
|
244054
|
<p>I came up with a way to get a dict of distinct elements in a list pointing to the location of each element; it works, but I feel pretty awful about this code, it's very ugly. Is there a more natural/pythonic way to do this?</p>
<pre><code>from itertools import groupby
sample_data = [1,2,3,3,1,0,5]
give_groups = lambda dta: {item: list(map(lambda z: z[0], list(item_group))) for item, item_group in itertools.groupby(list(enumerate(dta)), lambda x:x[1])}
print(give_groups(sample_data))
</code></pre>
<pre><code>{1: [4], 2: [1], 3: [2, 3], 0: [5], 5: [6]}
</code></pre>
<p>The performance is also bad.</p>
<p>Created this alternate that does work, but is kinda slow:</p>
<pre><code>def alt_grouping(dta):
retdict = defaultdict(list)
for position, item in enumerate(dta):
retdict[item].append(position)
return retdict
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T16:11:31.187",
"Id": "479120",
"Score": "1",
"body": "shouldn't be `1: [0,4] `?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T16:14:39.017",
"Id": "479121",
"Score": "0",
"body": "AND IT DOESN'T EVEN WORK!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T01:23:36.073",
"Id": "479158",
"Score": "2",
"body": "How did you check the runtime, what were your results, and what would you consider a reasonable result? (It's possible the Python startup time is responsible for any perceived slowness.) Do you know the range of the sample data in advance, so you could pre-fill the result data structure?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T07:58:51.657",
"Id": "479177",
"Score": "1",
"body": "@Carbon What doesn't work, your code? Your question states it does. Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T07:59:16.340",
"Id": "479178",
"Score": "0",
"body": "Can you tell us more about what your input looks like?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T12:15:30.147",
"Id": "479447",
"Score": "1",
"body": "`itertools.groupby` only works correctly if the data is already sorted, as written in the [documentation of the function](https://docs.python.org/3/library/itertools.html#itertools.groupby). As such, your code cannot work (and does not, as noted by @Alucard)."
}
] |
[
{
"body": "<p>The first try :</p>\n<pre><code>from itertools import groupby\nsample_data = [1,2,3,3,1,0,5]\ngive_groups = lambda dta: {item: list(map(lambda z: z[0], list(item_group))) for item, item_group in itertools.groupby(list(enumerate(dta)), lambda x:x[1])}\nprint(give_groups(sample_data))\n</code></pre>\n<p>Have to be corrected to:</p>\n<pre><code>from itertools import groupby # --> you don't have to call itertools.groupby just groupby\nsample_data = [1,2,3,3,1,0,5]\ngive_groups = lambda dta: {item: list(map(lambda z: z[0], list(item_group))) for item, item_group in groupby(list(enumerate(dta)), lambda x:x[1])}\nprint(give_groups(sample_data))\n</code></pre>\n<p>But seems to be replacing items and not appending them, don't see why.</p>\n<hr />\n<p>In the alt_grouping function, defaultdict doesn't exists:</p>\n<pre><code>def alt_grouping(dta):\n retdict = defaultdict(list) # don't know what is defaultdict\n for position, item in enumerate(dta):\n retdict[item].append(position)\n return retdict\n</code></pre>\n<p>Then I found a solution that works, it's based on your function alt_grouping:</p>\n<pre><code>sample_data = [1,2,3,3,1,0,5]\n\nretdict = {}\nfor position, item in enumerate(sample_data):\n if item in retdict.keys():\n retdict[item].append(position)\n else:\n retdict[item] = [position]\n\nprint(retdict)\n</code></pre>\n<p>I take some execution & times testing in the first try and my alternative with a bigger sample a list of two range(100).</p>\n<pre><code>Sample Data:\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, \n77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]\n\nFirst Function:\n{0: [100], 1: [101], 2: [102], 3: [103], 4: [104], 5: [105], 6: [106], 7: [107], 8: [108], 9: [109], 10: [110], 11: [111], 12: [112], 13: [113], 14: [114], 15: [115], 16: [116], 17: [117], 18: [118], 19: [119], 20: [120], 21: [121], 22: [122], 23: [123], 24: [124], 25: [125], 26: [126], 27: [127], 28: [128], 29: [129], 30: [130], 31: [131], 32: [132], 33: [133], 34: [134], 35: [135], 36: [136], 37: [137], 38: [138], 39: [139], 40: [140], 41: [141], 42: [142], 43: [143], 44: [144], 45: [145], 46: [146], 47: [147], 48: [148], 49: [149], 50: [150], 51: [151], 52: [152], 53: [153], 54: [154], 55: [155], 56: [156], 57: [157], 58: [158], 59: [159], 60: [160], 61: [161], 62: [162], 63: [163], 64: [164], 65: [165], 66: [166], 67: [167], 68: [168], 69: [169], 70: [170], 71: [171], 72: [172], 73: [173], 74: [174], 75: [175], 76: [176], 77: [177], 78: [178], 79: [179], 80: [180], 81: [181], 82: [182], 83: [183], 84: [184], 85: [185], 86: [186], 87: [187], 88: [188], 89: [189], 90: [190], 91: [191], 92: [192], 93: [193], 94: [194], 95: [195], 96: [196], 97: [197], 98: [198], 99: [199]}\n--- 0.001995563507080078 seconds ---\nMy Function:\n{0: [0, 100], 1: [1, 101], 2: [2, 102], 3: [3, 103], 4: [4, 104], 5: [5, 105], 6: [6, 106], 7: [7, 107], 8: [8, 108], 9: [9, 109], 10: [10, 110], 11: [11, 111], 12: [12, 112], 13: [13, 113], 14: [14, 114], 15: [15, 115], 16: [16, \n116], 17: [17, 117], 18: [18, 118], 19: [19, 119], 20: [20, 120], 21: [21, 121], 22: [22, 122], 23: [23, 123], 24: [24, 124], 25: [25, 125], 26: [26, 126], 27: [27, 127], 28: [28, 128], 29: [29, 129], 30: [30, 130], 31: [31, 131], 32: [32, 132], 33: [33, 133], 34: [34, 134], 35: [35, 135], 36: [36, 136], 37: [37, 137], 38: [38, 138], 39: [39, 139], 40: [40, 140], 41: [41, 141], 42: [42, 142], 43: [43, 143], 44: [44, 144], 45: [45, 145], 46: [46, 146], 47: \n[47, 147], 48: [48, 148], 49: [49, 149], 50: [50, 150], 51: [51, 151], 52: [52, 152], 53: [53, 153], 54: [54, 154], 55: [55, 155], 56: [56, 156], 57: [57, 157], 58: [58, 158], 59: [59, 159], 60: [60, 160], 61: [61, 161], 62: [62, \n162], 63: [63, 163], 64: [64, 164], 65: [65, 165], 66: [66, 166], 67: [67, 167], 68: [68, 168], 69: [69, 169], 70: [70, 170], 71: [71, 171], 72: [72, 172], 73: [73, 173], 74: [74, 174], 75: [75, 175], 76: [76, 176], 77: [77, 177], 78: [78, 178], 79: [79, 179], 80: [80, 180], 81: [81, 181], 82: [82, 182], 83: [83, 183], 84: [84, 184], 85: [85, 185], 86: [86, 186], 87: [87, 187], 88: [88, 188], 89: [89, 189], 90: [90, 190], 91: [91, 191], 92: [92, 192], 93: \n[93, 193], 94: [94, 194], 95: [95, 195], 96: [96, 196], 97: [97, 197], 98: [98, 198], 99: [99, 199]}\n--- 0.0009963512420654297 seconds ---\n</code></pre>\n<p>Seems to be pretty similar then I try with list(range(10000)):</p>\n<pre><code>First Function:\n--- 0.015984535217285156 seconds ---\nMy Function:\n--- 0.005953311920166016 seconds ---\n</code></pre>\n<p>Here we see a difference.</p>\n<p>There is the code for tests - EDITED :</p>\n<pre><code>import time\nsample_data = list(range(1000000)) + list (range(1000000))\n# print ("Sample Data:\\n",sample_data, "\\n")\n\nprint("First Function:")\nstart_time = time.time()\n\nfrom itertools import groupby\ngive_groups = lambda dta: {item: list(map(lambda z: z[0], list(item_group))) for item, item_group in groupby(list(enumerate(dta)), lambda x:x[1])}\n# print(give_groups(sample_data))\ngive_groups(sample_data)\n\nprint("--- %s seconds ---" % (time.time() - start_time))\n\n\nprint("My Function:")\nstart_time = time.time()\nretdict = {}\nfor position, item in enumerate(sample_data):\n if item in retdict.keys():\n retdict[item].append(position)\n else:\n retdict[item] = [position]\n\nprint("--- %s seconds ---" % (time.time() - start_time))\n\n\n\nprint("Other Function:")\n\nfrom collections import defaultdict\n\nstart_time = time.time()\ndef dict_with_indices(dta):\n """ Returns a dictionary with a list of indices for each item in dta\n\n Args:\n dta (list): list of data to be indexed\n\n Returns:\n dict: dict with list of indices as values\n\n Examples:\n >>> dict_with_indices([1,2,3,3,1,0,5]]\n {1: [0, 4], 2: [1], 3: [2, 3], 0: [5], 5: [6]}\n """\n result = defaultdict(list)\n for idx, val in enumerate(dta):\n result[val].append(idx)\n return result\n\ndict_with_indices(sample_data)\n\nprint("--- %s seconds ---" % (time.time() - start_time))\n</code></pre>\n<p>Times for this new tests:</p>\n<pre><code>First Function:\n--- 1.9537413120269775 seconds ---\nMy Function:\n--- 0.7061352729797363 seconds ---\nOther Function:\n--- 0.6053769588470459 seconds ---\n</code></pre>\n<p>New Solution seems to be the better one, thanks to @agtoever :</p>\n<pre><code>from collections import defaultdict\n \n\n def dict_with_indices(dta):\n """ Returns a dictionary with a list of indices for each item in dta\n \n Args:\n dta (list): list of data to be indexed\n \n Returns:\n dict: dict with list of indices as values\n \n Examples:\n >>> dict_with_indices([1,2,3,3,1,0,5]]\n {1: [0, 4], 2: [1], 3: [2, 3], 0: [5], 5: [6]}\n """\n result = defaultdict(list)\n for idx, val in enumerate(dta):\n result[val].append(idx)\n return result\n \n dict_with_indices(sample_data)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T14:14:27.017",
"Id": "479212",
"Score": "0",
"body": "It makes the same as you alt_grouping function but I don't think that neither are slow. Can specify how you evaluate this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:24:03.727",
"Id": "479230",
"Score": "0",
"body": "I edited my awnser, with all explained :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:27:23.813",
"Id": "479231",
"Score": "0",
"body": "Thank you. I've retracted my down vote :) I find it a little hard to follow but that's the only problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:33:11.053",
"Id": "479237",
"Score": "0",
"body": "Thank you very much!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T07:29:23.053",
"Id": "479433",
"Score": "1",
"body": "You could shorten your code and increase readability by replacing the if-else with a `defaultdict` [like this](https://tio.run/##hVFNa4QwEL37K4Y9KYTiR7cHYYUe@gd6FVlSM3YDaiQZW5fS324nardSCo2QNxnnvcy8DFe6mD6b58aaDmrTtliTNr0D3Q3GEihs5NiS0jUFAR/AR@d3TZez7jlGFyqSUR4Ar8PhAM9Io2W@XCpZStor@HrOtNoRmAY2JjTGAsr6Apqw4yywVLAoPdpXt2r6xWkIPTnKbxpKcpIMvKCXwwnVytzu35G5jXzZ1zZ@NyEdvMl2RLfynybZDS3uBIqi@GPqMhGpyPhLRCyOVXUr/0hyKGMB95WAlMOEMWNMGTiMOTwyHhkfqs9v3xa06NhrOO1dX@defnu7tJqE79e7hf3YoZWEuyf4kSm5qrqTw4C9CpkWbVd4e7aSebC6p/Df4aJo/gI)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T07:34:22.770",
"Id": "479434",
"Score": "0",
"body": "Ok, I will add it to the awnser with times."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T13:54:55.963",
"Id": "244109",
"ParentId": "244055",
"Score": "2"
}
},
{
"body": "<blockquote>\n<p>#This is simple understandable code</p>\n</blockquote>\n<pre><code>alpha=['a','b','c','d','e']#list\ndic={}#dict\n\nalpha.sort(reverse=True)\nlength=len(alpha)\n\nfor key in range (length):\n value=alpha.pop()\n dic[key]=value\n\nprint(dic)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:28:59.300",
"Id": "479233",
"Score": "1",
"body": "Please can you explain how this is better than the OPs code. Code Review is here to teach people to fish, not just give them one. Additionally this looks like it doesn't work the same way."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:02:14.660",
"Id": "244114",
"ParentId": "244055",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": "244109",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T15:45:09.673",
"Id": "244055",
"Score": "4",
"Tags": [
"python"
],
"Title": "Takes a list and return a dict of distinct values pointing to a list of index locations of each value"
}
|
244055
|
<p>Can someone please review the code and suggest any improvements / changes? Note that this method works but wanted to see if there is a better way for self learning purpose JavaScript/jQuery.</p>
<p>Example
<a href="https://jsfiddle.net/tjmcdevitt/Lx0vnb89/4/" rel="nofollow noreferrer">https://jsfiddle.net/tjmcdevitt/Lx0vnb89/4/</a></p>
<pre><code>var AppType = [
['All'],
['API'],
['AWS'],
['Web']
];
$.each(AppType, function (index, AppType) {
var option = $('<option></option>').attr("value", AppType).text(AppType);
$("#ddlApplicationType").append(option);
});
</code></pre>
|
[] |
[
{
"body": "<p>I have a few suggestions for optimizing your code.</p>\n<p>Since ES6 came out it is considered best practice to declare variables as <code>const</code>. It is also a good practice to declare your variables at the top of your script. For example you are selecting the element <code>#ddlApplicationType</code> everytime you loop over your array. That is not necessary. Just select it once at the top of your script and reuse it as often as you want in your code by referencing the variable <code>const selectApplicationType</code>. If you know that you are going to reassign a variable you can use the <code>let</code> keyword. Like I did in the <code>$.each</code> function. <code>temp</code> gets reassigned everytime the <code>$.each</code> loops over it. I declared it inside this function because it is a temporarly used variable and will never be needed in the global scope.\nWhen using DOM elements you should check if they exist first. For example if you have multiple pages and a DOM element referenced in your code is missing all the following code will break.\nIn the example below I used string literals. I think it makes the code a bit more readable. I hope I could help you.</p>\n<pre><code>const AppType = [\n ['All'],\n ['API'],\n ['AWS'],\n ['Web']\n];\nconst selectApplicationType = $("#ddlApplicationType")\n\nif (selectApplicationType.length > 0) {\n $.each(AppType, (index, AppType) => {\n let temp = `<option value="${AppType}">${AppType}</option>`\n selectApplicationType.append(temp)\n })\n} else {\n console.log(`Element #ddlApplicationType is missing`)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T14:04:28.997",
"Id": "244169",
"ParentId": "244056",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244169",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T15:47:34.257",
"Id": "244056",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "jQuery dropdown using each"
}
|
244056
|
<h1>Problem/Background:</h1>
<p>I want to support only some special Unicode characters for my program (Greek letters and some math operators). C++ provides a <code>char</code> type, which is always 1 byte in size, however, this is too short to display all characters. Normally this is solved by choosing an encoding like UTF-8 (or 16/32). However, the C++ regex algorithms do not support UTF-8.</p>
<p>So the choice falls on the other data type <code>wchar_t</code>, which is a platform dependent wide character. On Windows, it spans 2 bytes, so it settles for UTF-16 encoding, while on Linux it's 4 bytes (UTF-32). While researching on this, everybody basically said, you always want to use <code>wchar_t</code> (or the respective container <code>std::wstring</code>) on Windows, but never on Linux. Since I don't need too many special characters, I settled on using the <code>char</code> type internally and convert incoming <code>std::wstring</code> to my own extended ASCII code page. For convenience, I kept the first 127 characters original to ASCII.</p>
<h1>What does my code do?</h1>
<p>The function <code>unicode_to_xascii</code> takes a <code>std::wstring</code> and quietly removes all characters that are not in my defined codepage. Characters with an <code>id > 255</code> will be converted in the respective <code>XASCII</code> value.</p>
<h1>Concerns/Questions:</h1>
<p>Please comment/answer on these additionally to anything else you might notice in the code.</p>
<ol>
<li>Obviously, there's the extra overhead for conversion, but since all other actions in between can be performed on 1 byte, instead of 2 or even 4 bytes, I think this is a valid trade off.</li>
<li>I tried to avoid magic numbers or obscure bit arithmetic. Please let me know if there's something that could be done clearer.</li>
<li>Now that I think about it, I could have probably worked something out via operator overloading. Is there a better approach than this functional one?</li>
</ol>
<pre><code>#pragma once
#ifdef __WIN32__
#include <io.h>
#include <fcntl.h>
#endif
#include <algorithm>
#include <array>
#include <iostream>
#include <regex>
#include <string>
namespace Utility
{
void setup_unicode()
{
std::setlocale(LC_ALL, "en_US.UTF-8");
#ifdef __WIN32__
_setmode(_fileno(stdout), _O_U16TEXT);
_setmode(_fileno(stdin), _O_U16TEXT);
#endif
}
namespace Unicode
{
constexpr uint16_t ASCII_END = 127;
constexpr uint16_t ALPHA = 913;
constexpr uint16_t OMEGA = 937;
constexpr uint16_t alpha = 945;
constexpr uint16_t omega = 969;
constexpr uint16_t circled_plus = 8853;
constexpr uint16_t circled_minus = 8854;
constexpr uint16_t circled_times = 8855;
constexpr uint16_t cross_product = 10799;
constexpr std::array<uint16_t, 4> math_operators = {circled_plus, circled_minus, circled_times, cross_product};
}
namespace XASCII
{
constexpr char BEGIN = '\xc0';
constexpr char ALPHA = BEGIN;
constexpr char OMEGA = ALPHA + Unicode::OMEGA - Unicode::ALPHA;
constexpr char alpha = OMEGA + 1;
constexpr char omega = alpha + Unicode::omega - Unicode::alpha;
constexpr char circled_plus = omega + 1;
constexpr char circled_minus = circled_plus + 1;
constexpr char circled_times = circled_minus + 1;
constexpr char cross_product = circled_times + 1;
constexpr std::array<char, 4> math_operators = {circled_plus, circled_minus, circled_times, cross_product};
constexpr char IGNORE = -1;
constexpr char REGEX_ALPHA_OMEGA[] = {XASCII::ALPHA, '-', XASCII::OMEGA};
constexpr char REGEX_ALPHA_omega[] = {XASCII::ALPHA, '-', XASCII::omega};
}
bool is_utf16_carry_mark_set(uint16_t i)
{
return i & ((1u << 15u) + (1u << 14u));
}
uint16_t to_int(wchar_t w)
{
#ifdef __unix__
auto *p = reinterpret_cast<uint32_t *>(&w);
if( *p >= 1u << 16u ){
*p = static_cast<unsigned char>(XASCII::IGNORE);
}
return static_cast<uint16_t>(*p);
#endif
#ifdef __WIN32__
auto *p = reinterpret_cast<uint16_t*>(&w);
if( is_utf16_carry_mark_set(*p) )
{
*p = XASCII::IGNORE;
}
return static_cast<uint16_t>(*p);
#endif
}
std::string unicode_to_xascii(const std::wstring &wstr)
{
std::string result;
unsigned p = 0, len = wstr.length();
result.resize(len);
for( unsigned k = 0; k < len; ++k ){
uint16_t character = to_int(wstr[k]);
if( character == static_cast<uint16_t>(XASCII::IGNORE)){
continue;
}
if( character <= Unicode::ASCII_END ){
result[p++] = static_cast<unsigned char>(character);
continue;
}
if( Unicode::ALPHA <= character && character <= Unicode::OMEGA ){
result[p++] = static_cast<unsigned char>(XASCII::ALPHA + (character - Unicode::ALPHA));
}
else if( Unicode::alpha <= character && character <= Unicode::omega ){
result[p++] = static_cast<unsigned char>(XASCII::alpha + character - Unicode::alpha);
continue;
}
auto index = std::find(Unicode::math_operators.cbegin(), Unicode::math_operators.cend(), character);
if( index != Unicode::math_operators.cend()){
result[p++] = XASCII::math_operators[index - Unicode::math_operators.cbegin()];
}
}
result.resize(p);
return result;
}
std::wstring xascii_to_unicode(const std::string &str)
{
std::wstring result;
unsigned p = 0, len = str.length();
result.resize(len);
for( unsigned k = 0; k < len; ++k ){
char character = str[k];
if( character == XASCII::IGNORE ){
continue;
}
if( character < XASCII::BEGIN ){
result[p++] = static_cast<wchar_t>(character);
}
else if( XASCII::ALPHA <= character && character <= XASCII::OMEGA ){
result[p++] = static_cast<wchar_t>(Unicode::ALPHA + (character - XASCII::ALPHA));
}
else if( XASCII::alpha <= character && character <= XASCII::omega ){
result[p++] = static_cast<wchar_t>(Unicode::alpha + (character - XASCII::alpha));
}
else{
auto index = std::find(XASCII::math_operators.cbegin(), XASCII::math_operators.cend(), character);
if( index != XASCII::math_operators.cend()){
result[p++] = static_cast<wchar_t>(Unicode::math_operators[index -
XASCII::math_operators.cbegin()]);
}
}
}
result.resize(p);
return result;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Correct me if I'm wrong but aren't functions and overloading operators basically the same thing, a glorified goto statement? I would only put it in if it makes it easier to read when you come back to it in 3 months.</p>\n<p>I would change all the <code>1u << x</code> to the hex value.\nThose carry marks will not change any time soon, so you could make them constants and not rely on that function.</p>\n<p>I think you forgot a <code>continue</code> in your for loop for <code>ALPHA && OMEGA</code></p>\n<p>Are you ever worried about a string longer than an unsigned characters? <code>unsigned k = 0; k < len; ++k</code> Are you restricting the size of the string else where?</p>\n<p>Other than that, it looks okay.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T23:42:48.340",
"Id": "244080",
"ParentId": "244057",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244080",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T15:59:11.223",
"Id": "244057",
"Score": "6",
"Tags": [
"c++",
"strings"
],
"Title": "Custom cross-platform extended ASCII converter"
}
|
244057
|
<p>The question is about printing alphabets in a rangoli pattern of size/dimension input by the user.</p>
<p><strong>Example:</strong></p>
<pre><code>size 3
----c----
--c-b-c--
c-b-a-b-c
--c-b-c--
----c----
</code></pre>
<p><a href="https://i.stack.imgur.com/2nn84.png" rel="nofollow noreferrer">The picture contains details about the challenge</a></p>
<p>OR</p>
<p><a href="https://www.hackerrank.com/challenges/alphabet-rangoli/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/alphabet-rangoli/problem</a></p>
<p><strong>Sample Code:</strong></p>
<pre><code>n = int(input('Enter a size: '))
alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for j in range(0, n-1):
ls_1 = str(''.join(alpha[n-1:abs(n-(j+2)):-1]))
ls_1 = ls_1 + ls_1[-2::-1]
ls = str('-'.join(ls_1))
print('-' * (((n - j) * 2) - 2) + ls + '-' * (((n - j) * 2) - 2))
ls_1 = str(''.join(alpha[n-1::-1]))
ls_1 = ls_1 + ls_1[-2::-1]
ls = str('-'.join(ls_1))
print(ls)
for j in range(n-2, -1, -1):
ls_2 = str(''.join(alpha[n-1:abs(n-(j+2)):-1]))
ls_2 = ls_2 + ls_2[-2::-1]
ls_s = str('-'.join(ls_2))
print('-' * (((n - j) * 2) - 2) + ls_s + '-' * (((n - j) * 2) - 2))
</code></pre>
<p><strong>Sample Output:</strong></p>
<pre><code>Enter a size: 5
--------e--------
------e-d-e------
----e-d-c-d-e----
--e-d-c-b-c-d-e--
e-d-c-b-a-b-c-d-e
--e-d-c-b-c-d-e--
----e-d-c-d-e----
------e-d-e------
--------e--------
</code></pre>
<p>Is the above code that I have done...is it a good code to say?
Also, I couldn't find any other way to solve the problem.
(I am a beginner in Python)</p>
|
[] |
[
{
"body": "<p>I think the general algorithm is OK, but you have a lot of repetition in your code! Also avoid writing out the alphabet by hand when you could have Python generate it for you. Here is the code without repetition:</p>\n<pre><code>n = int(input('Enter a size: '))\n\nalpha = [chr(ord('a') + i) for i in range(0, 26)]\n\nfor k in range(1 - n, n):\n j = n - abs(k) \n center = '-'.join(alpha[n-1:n-j:-1] + alpha[n-j:n])\n padding = '-' * abs(k) * 2\n print(padding + center + padding)\n</code></pre>\n<p>I used a single for-loop that goes from <code>1-n</code> to <code>n</code>, so this covers both the upper and lower half, and I also made it so you don't have to treat the center line as a special case.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T19:16:00.720",
"Id": "244066",
"ParentId": "244059",
"Score": "4"
}
},
{
"body": "<h1>Use built-ins</h1>\n<pre><code>alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\n</code></pre>\n<p>This is a very verbose and error-prone way of getting all of the ASCII lowercase letters.</p>\n<pre><code>from string import ascii_lowercase as alpha\n</code></pre>\n<p>will give approximately the same result. It is a string, instead of a list, but Python strings are effectively just lists of characters. In particular, <code>alpha[0]</code> will be <code>'a'</code> and <code>alpha[25]</code> will be <code>'z'</code>.</p>\n<h1>Unnecessary <code>str()</code></h1>\n<p>The result of a <code>''.join(...)</code> call will be a string. Wrapping this in a <code>str(...)</code> call is pointless.</p>\n<h1>Unnecessary <code>abs()</code></h1>\n<p><code>for j in range(0, n-1)</code> means that <code>j</code> will always be less than <code>n-1</code>. In other words:</p>\n<p><span class=\"math-container\">$$ j \\le n - 2 $$</span></p>\n<p>Consider, <code>abs(n-(j+2))</code>:\n<span class=\"math-container\">$$ j \\le n - 2$$</span>\n<span class=\"math-container\">$$ j + 2 \\le n$$</span>\n<span class=\"math-container\">$$ n - (j+2) \\ge 0$$</span>\nIn other words, the <code>abs(...)</code> is unnecessary, and just adds confusion.</p>\n<h1>General Comments</h1>\n<p>Follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP-8 guidelines</a> (spaces around operators, etc). Use functions. Use a main-guard.</p>\n<h1>Reworked & Simplified Code</h1>\n<pre><code>from string import ascii_lowercase\n\ndef print_rangoli(n: int) -> None:\n\n alpha = ascii_lowercase[:n]\n\n for row in range(- n + 1, n):\n row = abs(row)\n dashes = "-" * (2 * row)\n print(dashes + "-".join(alpha[:row:-1] + alpha[row:]) + dashes)\n\nif __name__ == '__main__':\n n = int(input("Enter a size: "))\n print_rangoli(n)\n \n</code></pre>\n<h1>Format Specification Mini-Language</h1>\n<p>Python's format statement (and <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals\" rel=\"noreferrer\">f-strings</a>) use a <a href=\"https://docs.python.org/3/library/string.html#format-specification-mini-language\" rel=\"noreferrer\">format specification mini-language</a>. This allow you substitute values into a larger string in fixed-width fields, with your choice of alignment and fill characters. Here, you'd want centre alignment, with <code>'-'</code> for the fill character.</p>\n<p>For example, <code>f"{'Hello':-^11}"</code> is a f-string, which places the string <code>'Hello'</code> into a field <code>11</code> characters wide, centre justified (<code>^</code>), with <code>'-'</code> used as a fill character. Producing <code>'---Hello---'</code>. Instead of a hard-coded width (<code>11</code> in the above example), we can use a computed <code>{width}</code> argument.</p>\n<p>Using this, we can further "simplify" (for some definition of simplify) the <code>print_rangoli</code> function:</p>\n<pre><code>def print_rangoli(n: int) -> None:\n\n width = n * 4 - 3\n alpha = ascii_lowercase[:n]\n\n for row in range(- n + 1, n):\n row = abs(row)\n print(f"{'-'.join(alpha[:row:-1] + alpha[row:]):-^{width}}")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T08:40:46.053",
"Id": "479184",
"Score": "1",
"body": "`def print_rangoli(n: int) -> None: ` \nKindly explain this syntax. I couldn't get it. Why the `None` statement used here? @AJNeufeld"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T11:01:13.317",
"Id": "479189",
"Score": "4",
"body": "@GobindaDeb That is a [type hint](https://stackoverflow.com/a/32558710/2912349)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T13:30:40.720",
"Id": "479206",
"Score": "2",
"body": "Functionally, this is no different from `def print_rangoli(n):`, but with the benefit that Python Type Checkers can warn you if you accidentally write `x = print_rangoli(True)` that a) you are not passing an integer argument to the function, and b) nothing will be returned to assign to `x`. Syntactically there is nothing wrong with that statement; you pass 1 argument to a function expecting 1 argument. Functionally, there is nothing wrong with it either; it will print a rangoli of size 1 & assign `None` to `x`. But logically it is an error. The seatbeats are optional… and mostly decorative."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T21:42:02.010",
"Id": "479795",
"Score": "3",
"body": "_strings are effectively just lists of characters_ — specifically, strings are sequences of characters."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T19:24:51.923",
"Id": "244068",
"ParentId": "244059",
"Score": "15"
}
}
] |
{
"AcceptedAnswerId": "244068",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T16:33:57.007",
"Id": "244059",
"Score": "9",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Alphabet Rangoli Challenge"
}
|
244059
|
<p>I have created a function that converts from UTF-16 to UTF-8.<br />
This function converts from UTF-16 to codepoint firstly, then from codepoint to UTF-8.</p>
<pre><code>void ToUTF8(char16_t *str) {
while (*str) {
unsigned int codepoint = 0x0;
//-------(1) UTF-16 to codepoint -------
if (*str <= 0xD7FF) {
codepoint = *str;
str++;
} else if (*str <= 0xDBFF) {
unsigned short highSurrogate = (*str - 0xD800) * 0x400;
unsigned short lowSurrogate = *(str+1) - 0xDC00;
codepoint = (lowSurrogate | highSurrogate) + 0x10000;
str += 2;
}
//-------(2) Codepoint to UTF-8 -------
if (codepoint <= 0x007F) {
unsigned char hex[2] = { 0 };
hex[0] = (char)codepoint;
hex[1] = 0;
cout << std::hex << std::uppercase << "(1Byte) " << (unsigned short)hex[0] << endl;
} else if (codepoint <= 0x07FF) {
unsigned char hex[3] = { 0 };
hex[0] = ((codepoint >> 6) & 0x1F) | 0xC0;
hex[1] = (codepoint & 0x3F) | 0x80;
hex[2] = 0;
cout << std::hex << std::uppercase << "(2Bytes) " << (unsigned short)hex[0] << "-" << (unsigned short)hex[1] << endl;
} else if (codepoint <= 0xFFFF) {
unsigned char hex[4] = { 0 };
hex[0] = ((codepoint >> 12) & 0x0F) | 0xE0;
hex[1] = ((codepoint >> 6) & 0x3F) | 0x80;
hex[2] = ((codepoint) & 0x3F) | 0x80;
hex[3] = 0;
cout << std::hex << std::uppercase << "(3Bytes) " << (unsigned short)hex[0] << "-" << (unsigned short)hex[1] << "-" << (unsigned short)hex[2] << endl;
} else if (codepoint <= 0x10FFFF) {
unsigned char hex[5] = { 0 };
hex[0] = ((codepoint >> 18) & 0x07) | 0xF0;
hex[1] = ((codepoint >> 12) & 0x3F) | 0x80;
hex[2] = ((codepoint >> 6) & 0x3F) | 0x80;
hex[3] = ((codepoint) & 0x3F) | 0x80;
hex[4] = 0;
cout << std::hex << std::uppercase << "(4Bytes) " << (unsigned short)hex[0] << "-" << (unsigned short)hex[1] << "-" << (unsigned short)hex[2] << "-" << (unsigned short)hex[3] << endl;
}
}
}
</code></pre>
<p>Also, you can compile and test the code from <a href="https://onlinegdb.com/r1TVL6w6L" rel="nofollow noreferrer">here</a></p>
<p><strong>What do you think about that function in terms of performance, and ease?</strong></p>
|
[] |
[
{
"body": "<p>First a special problem: Unicode 0 is a terminator char in strings in C/C++.\nModified UTF (i.e. UTF-8) deals with this by also doing the encoding for what officially should be one byte 0. As decoding poses no problem. You might consider this. For instance simply requiring modified UTF-16 on input as you check the terminator.</p>\n<pre><code> if (codepoint <= 0x007F && codepoint != 0) {\n</code></pre>\n<p>Now the actual review:</p>\n<ul>\n<li><p>(Optional) To cope with modified (<code>*str</code>) UTF-16, generating modified UTF-8:</p>\n<pre><code> if (codepoint <= 0x007F && codepoint != 0) {\n</code></pre>\n</li>\n<li><p>You are now giving the result to cout using an extra nul byte as terminator.</p>\n</li>\n<li><p>There should be a byte output stream. <em>An output stream parameter could be appended to per byte, without intermediate arrays; and only at the end might need a NUL byte.</em> If <code>str</code> occupies N UTF bytes, then the result will at most need 2<em>N UTF bytes. _N UTF-16 bytes ~ to N/2 code points ~ max 2</em>N UTF-8 (N/2 * 4-byte sequences)._</p>\n<p>That terminator should be added outside the loop.</p>\n</li>\n<li><p>Creating arrays is superfluous, immediately return the single bytes. <em>(This would be the case for delivering the result somewhat like <code>cout << ((codepoint >> 6) & 0x1F) | 0xC0</code>)</em></p>\n</li>\n<li><p>You nicely validate the input for illegal UTF-16 chars above the max. In java one would throw an exception, you just discard the char.</p>\n</li>\n<li><p><em>(A matter of taste)</em> Maybe consider an API with a string length as input parameter instead of relying on a NUL terminator. If the area of application is file based, that\nwould even be more natural.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T02:05:36.420",
"Id": "479306",
"Score": "0",
"body": "Thank you for your review, but can you clarify the point 3 and 4 more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T12:09:59.077",
"Id": "479644",
"Score": "0",
"body": "@LionKing sorry, was abroad for a couple of days, but I hope I could be less cryptic."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T11:54:47.067",
"Id": "244102",
"ParentId": "244060",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T16:36:57.570",
"Id": "244060",
"Score": "1",
"Tags": [
"c++",
"unicode",
"utf-8"
],
"Title": "The conversion from UTF-16 to UTF-8"
}
|
244060
|
<p>I have written a simple fibonacci function in Haskell that uses the State monad to save solutions to overlapping sub-problems. Now despite the function working I am not really happy with the solution, especially with the last map lookup. How can I improve my solution? Thank you.</p>
<pre class="lang-hs prettyprint-override"><code>module Lib (
fib
) where
import Control.Monad.State
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
type DP = Map Int Int
fib :: Int -> State DP Int
fib 0 = return 1
fib 1 = return 1
fib x = do
solved <- get
let m = Map.lookup x solved
case m of
Nothing -> do
prev1 <- fib (x - 1)
prev2 <- fib (x - 2)
put $ Map.insert x (prev1 + prev2) solved
Just value -> put $ Map.insert x value solved
gets (fromMaybe 0 . Map.lookup x)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T11:43:53.487",
"Id": "479195",
"Score": "1",
"body": "I might do a full review later, but the biggest issue I see is that here you overwrite the insertions from the two lines above at this point `put $ Map.insert x (prev1 + prev2) solved`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T17:08:49.427",
"Id": "479255",
"Score": "0",
"body": "@Franky I am not sure I follow you. :( The two lines above `put $ Map.insert x (prev1 + prev2) solved` just get the `Int` result from calling `fib` and then I just save the result on the `Map Int Int`. Now the `Just value -> put $ Map.insert x value solved` is doing an unnecessary write on the Map but I wasn't sure how to write it better."
}
] |
[
{
"body": "<p>I won't be reviewing this code for efficiency, since I'm not quite so comfortable with analyzing some combination of State monad, immutable data structures, and laziness.</p>\n<p>However, there are a few obvious changes you can make to your code.</p>\n<h1>Passing State Properly</h1>\n<p>This is what Franky was getting at with his comment, and it's a bit of a tricky bug. When you do</p>\n<pre><code>put $ Map.insert x (prev1 + prev2) solved\n</code></pre>\n<p>you use the <code>solved</code> that you get at the beginning of the function invocation. But your recursion goes from top-to-bottom, so if you're computing <code>fib 10</code>, <code>solved</code> is the empty map when you are getting the final answer. Essentially, your memo map keeps getting overwritten with maps that have less information. The fix is pretty easy.</p>\n<pre><code>prev1 <- fib (x - 1)\nprev2 <- fib (x - 2)\nsolved' <- get\nput $ Map.insert x (prev1 + prev2) solved'\n</code></pre>\n<p>Just get the updated state after the recursive invocations.</p>\n<h1>Naming</h1>\n<p>I think <code>solved</code> is ambiguous as to whether it refers to a single solution or the memo map. I would call it something like <code>solutions</code>, maybe <code>sols</code> or <code>fibs</code> if you feel like abbreviating. In light of the previous bug, you may wish to call the first one <code>initialSolutions</code> and later ones <code>updatedSolutions</code> or something like that (I just used <code>solutions</code> and <code>solutions'</code>).</p>\n<p>The name <code>m</code> is OK, but it doesn't really need to exist at all. You can just case on <code>Map.lookup x solved</code> directly instead of binding <code>m</code> and then casing on it.</p>\n<h1>The <code>case</code> Statement</h1>\n<p>It seems like you're trying to use the <code>case</code> statement to set up your memo map so that it always has a value for <code>x</code>. There are two things to address about this.</p>\n<h2>Indexing</h2>\n<p>If you, the programmer, are sure that <code>x</code> exists in the map (and in the <code>case</code> above you guarantee it), you could instead use the unsafe lookup <code>Map.!</code>. Given the option between returning an erroneous value silently (your <code>fromMaybe 0</code>) and crashing and burning in case of a bug, I would generally prefer the latter. So your last line would look something like <code>gets (Map.! x)</code>.</p>\n<h2>The Last Lookup</h2>\n<p>However, doing the lookup itself is inelegant. It <em>might</em> make sense if there was a lot of convoluted stuff happening between, but proper indexing doesn't get checked by the type system and doing a lookup takes (not much, but some) extra time. Fortunately, you don't need to do it. Since I'm going to assume you're learning Haskell, consider how you'd approach a similar problem in an imperative language. What would you do to change this code:</p>\n<pre><code>if (x in solutions):\n solutions[x] = solutions[x]\nelse:\n prev1 = fib(x-1)\n prev2 = fib(x-2)\n solutions[x] = prev1 + prev2\nreturn solutions[x]\n</code></pre>\n<p>There are many right answers, but one thing you can do is as follows (this particular code is nice because it avoids extra lookups):</p>\n<pre><code>if (x in solutions):\n return solutions[x]\nelse:\n prev1 = fib(x-1)\n prev2 = fib(x-2)\n solution = prev1 + prev2\n solutions[x] = solution\n return solution\n</code></pre>\n<p>Your <code>case</code> statement functions like the imperative <code>if</code> statement, except more powerful since you have guarantees on the types! So mirroring the imperative's revision, you can revise your code like so</p>\n<pre><code>case Map.lookup x solved of\n Just solution -> return solution\n Nothing -> do\n prev1 <- fib (x - 1)\n prev2 <- fib (x - 2)\n solutions' <- get\n let solution = prev1 + prev2\n put $ Map.insert x solutions' solved\n return solution\n</code></pre>\n<p>Now you don't need the last lookup. Notice how we also avoid the issue entirely of whether <code>x</code> is in <code>solutions</code>, because we explicitly handle the case where it is and isn't. This code doesn't have any unsafe lookups!</p>\n<h2>Addendum on Lookups</h2>\n<p>Now, even if you wanted to make your <code>case</code> statement only fill out the memo map instead of also returning the answers, I agree with you that you are doing unnecessary work.</p>\n<pre><code>Just value -> put $ Map.insert x value solved\n</code></pre>\n<p>The line above needlessly reinserts the value of <code>x</code>. The memo map already has <code>x</code>, and <code>x</code> is already set to <code>value</code>. If you wanted to otherwise keep your code the same, at least change this to</p>\n<pre><code>Just value -> return ()\n</code></pre>\n<p><code>put</code> has type <code>a -> State a ()</code>. It's a convention for monads to pass <code>()</code> as their return value if they perform an action that doesn't return anything (like how <code>putStrLn</code> has type <code>String -> IO ()</code>). You can simply <code>return ()</code> to do nothing instead of actually modifying the memo map, which I assume you did to fix a type error.</p>\n<h1>Revised Function</h1>\n<p>Included are comments noting the revision</p>\n<pre class=\"lang-hs prettyprint-override\"><code>fib :: Int -> State DP Int\nfib 0 = return 1\nfib 1 = return 1\nfib x = do\n -- Change to a more descriptive name\n solutions <- get\n -- Case directly on the value without intermediate variable\n case Map.lookup x solutions of\n Nothing -> do\n prev1 <- fib (x - 1)\n prev2 <- fib (x - 2)\n -- Get updated solutions\n solutions' <- get\n let solution = prev1 + prev2\n put $ Map.insert x solution solutions'\n -- Return solution directly\n return solution\n Just solution ->\n -- Return solution directly\n return solution\n -- Elide previous lookup\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T19:55:53.677",
"Id": "244136",
"ParentId": "244065",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244136",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T19:13:26.517",
"Id": "244065",
"Score": "2",
"Tags": [
"haskell",
"dynamic-programming",
"monads"
],
"Title": "How can I use the State monad effectively in Haskell?"
}
|
244065
|
<p>Early today, I gave an answer to someone where I <a href="https://codereview.stackexchange.com/a/243983/54031">recommended</a> using <code>IReadOnlyList<T></code>. Then I was asked why not just use a private setter, e.g. <code>public IList<T> { get; private set; }</code>? This was not an entirely unexpected question. I provided a small example as an update to my answer. However, my example really did not directly apply as a review to the OP's code. Thus, I thought I would post the example code here for its own review.</p>
<p>I am using C# and .NET Core 3.1.</p>
<p><strong>First</strong>, there is a very simple <code>User</code> class.</p>
<pre><code>namespace Read_Only_List_Example
{
public class User
{
// Intentionally a very simplified DTO class
public string Name { get; set; }
public bool IsAdmin { get; set; }
}
}
</code></pre>
<p><strong>Secondly</strong>, there is some class that does something with a list of users.</p>
<pre><code>using System.Collections.Generic;
using System.Linq;
namespace Read_Only_List_Example
{
public class SomeClassWithUsers
{
public SomeClassWithUsers(IEnumerable<User> users)
{
// This example requires independent copies of the user list.
UserList1 = users.ToList();
_users = users.ToList();
}
// SPOILER: just because we use a private setter does not mean this list is immune from external changes!
// Which is a way of saying that UserList1 is not entiredly safe from the public.
public List<User> UserList1 { get; private set; }
// Here _users is private and safe from public eyes, as is UserList2.
private List<User> _users = new List<User>();
public IReadOnlyList<User> UserList2 => _users;
public static SomeClassWithUsers CreateSample()
{
// NOTE that none of the initial sample users are Admins or "evil" (yet).
var users = new List<User>()
{
new User() {Name = "Alice", IsAdmin = false },
new User() {Name = "Bob", IsAdmin = false },
new User() {Name = "Carl", IsAdmin = false },
new User() {Name = "Dan", IsAdmin = false },
new User() {Name = "Eve", IsAdmin = false },
};
return new SomeClassWithUsers(users);
}
}
}
</code></pre>
<p>And <strong>finally</strong>, we have <code>Program.Main</code> to give the simple example:</p>
<pre><code>using System;
using System.Collections.Generic;
namespace Read_Only_List_Example
{
class Program
{
static void Main(string[] args)
{
var x = SomeClassWithUsers.CreateSample();
// Even though UserList1 has a private setter, I can still change individual members.
// Below, each user is made "evil" and granted full admin rights.
for (var i = 0; i < x.UserList1.Count; i++)
{
// Holy smokes! Someone can create an entirely new User.
x.UserList1[i] = new User() { Name = $"Evil {x.UserList1[i].Name}", IsAdmin = true };
}
Console.WriteLine("UserList1 - with a private setter - has been modifed!");
DisplayUsers(x.UserList1);
// But I cannot alter UserList2 in any way since it is properly marked as a IReadOnlyList.
// You cannot compile the code below. See for youself by uncommenting it.
//for (var i = 0; i < x.UserList2.Count; i++)
//{
// x.UserList2[i] = new User() { Name = $"Evil {x.UserList1[2].Name}", IsAdmin = true };
//}
Console.WriteLine("\nUserList2 - which is IReadOnlyList - remains unchanged.");
DisplayUsers(x.UserList2);
Console.WriteLine("\nPress ENTER key to close");
Console.ReadLine();
}
private static void DisplayUsers(IEnumerable<User> users)
{
foreach (var user in users)
{
Console.WriteLine($" {user.Name} {(user.IsAdmin ? "IS" : "is NOT")} an Admin.");
}
}
}
}
</code></pre>
<p>Here is an example of the console output:</p>
<pre><code>UserList1 - with a private setter - has been modifed!
Evil Alice IS an Admin.
Evil Bob IS an Admin.
Evil Carl IS an Admin.
Evil Dan IS an Admin.
Evil Eve IS an Admin.
UserList2 - which is IReadOnlyList - remains unchanged.
Alice is NOT an Admin.
Bob is NOT an Admin.
Carl is NOT an Admin.
Dan is NOT an Admin.
Eve is NOT an Admin.
Press ENTER key to close
</code></pre>
<p>There you go. I wanted to keep the example short and easy to follow, so things are kept a minimum. I did try to employ DRY where possible. The one area where someone could say there is dead code in comments, I would point out that it is there intentionally as part of a learning exercise.</p>
<p>Here's what happens if you uncomment the code that tries to alter <code>UserList2</code> from <code>Main</code>.</p>
<p><a href="https://i.stack.imgur.com/fPCUR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fPCUR.png" alt="enter image description here" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T20:46:14.373",
"Id": "479140",
"Score": "1",
"body": "I think you always should expose the lowest possible interface. IEnumerable preferably, But then we get that dredded multiple enumeration warning if we iterate it multiple times even though in most cases its a List or array underneath."
}
] |
[
{
"body": "<h2>The conclusion misses the point</h2>\n<p>Your code technically does touch on what makes a list readonly, but the example you've used to display that behavior suggests a completely different problematic scenario, i.e. that of mutable objects. This by itself has nothing to do with lists, regardless of whether they're readonly or not.</p>\n<p>So your example is not good. Not because the code doesn't work, but because it gets distracted by a completely unrelated problem, and the outcome you show is more related to that problem than it is to the readonly-ness of the collection.</p>\n<pre><code>UserList1 - with a private setter - has been modifed!\nEvil Alice IS an Admin.\n...\n\nUserList2 - which is IReadOnlyList - remains unchanged.\nAlice is NOT an Admin.\n...\n</code></pre>\n<p>While technically you did change the list by creating new users and overwriting the old users, it's not really a good example. <code>User</code> is a mutable class, and in your example I would be perfectly capable of doing this:</p>\n<pre><code>for (var i = 0; i < x.UserList2.Count; i++)\n{\n x.UserList2[i].IsAdmin = true;\n}\n</code></pre>\n<p>The mutability of your <code>User</code> class is a problem, but <code>IReadOnlyList<T></code> does not protect you against that.</p>\n<p>Had <code>User</code> been immutable, that's a different story. The combination of an immutable class contained in an <code>IReadOnlyList<T></code> would guard against that.</p>\n<p>But <em>even then</em>, you need to make sure that the object you expose as an <code>IReadOnlyList<T></code> cannot be cast back to a mutable type, e.g:</p>\n<pre><code>IReadOnlyList<string> readOnlyList = new List<string>() { "a" };\n \n(readOnlyList as List<string>).Add("b");\n \nConsole.WriteLine(String.Join(",", readOnlyList)); // prints "a, b"\n</code></pre>\n<p>So you really need many different components before you could validate your example as a valid example.</p>\n<p>But this is supposed to be a <strong>simple</strong> example on the purpose of <code>IReadOnlyList<T></code>, and you've really overcomplicated it with several unnecessary distractions.</p>\n<p>So here's my attempt to provide a clear example of the difference:</p>\n<hr />\n<h2>My version of this answer</h2>\n<p>There's a difference between setting a list:</p>\n<pre><code>myObject.MyList = new List<string>();\n</code></pre>\n<p>and setting the members of a list:</p>\n<pre><code>myObject.MyList.Add("new value");\n</code></pre>\n<p>These are two different actions, each of which you can guard against, but in a different way.</p>\n<p><strong>Private setters</strong> guard against the list itself being set:</p>\n<pre><code>public class PublicSetListClass\n{\n public List<string> MyList { get; set; } = new List<string>() { "original" };\n}\n\nvar myObject1 = new PublicSetListClass();\nmyObject1.MyList = new List<string>() { "new" }; // this is allowed\n\npublic class PrivateSetListClass\n{\n public List<string> MyList { get; private set; } = new List<string>() { "original" };\n}\n\nvar myObject2 = new PrivateSetListClass();\nmyObject2.MyList = new List<string>() { "new" }; // this is NOT allowed!\n</code></pre>\n<p>But public setters do not guard against the list's content being altered:</p>\n<pre><code>myObject1.MyList.Add("added"); // this is allowed\nmyObject2.MyList.Add("added"); // this is ALSO allowed!\n</code></pre>\n<p><strong><code>IReadOnlyList<T></code></strong>, on the other hand, guards against the content of the list being altered:</p>\n<pre><code>// this is the same PublicSetListClass object from before\nmyObject1.MyList.Add("added"); // this is allowed\n\npublic class PublicSetReadOnlyListClass\n{\n public IReadOnlyList<string> MyList { get; set; } = new List<string>() { "original" };\n}\n\nvar myObject3 = new PublicSetReadOnlyListClass();\nmyObject3.MyList.Add("added"); // this is NOT allowed\n</code></pre>\n<p>But <code>IReadOnlyList<T></code> does not guard against the list itself being replaced!</p>\n<pre><code>myObject1.MyList = new List<string>() { "new" }; // this is allowed\nmyObject3.MyList = new List<string>() { "new" }; // this is ALSO allowed!\n</code></pre>\n<p>So if you want a list that cannot be replaced and whose content cannot be altered, you need to <strong>both</strong> use a private setter and use an <code>IReadOnlyList<T></code> type (or any other readonly collection type):</p>\n<pre><code>public class PrivateSetReadOnlyListClass\n{\n public IReadOnlyList<string> MyList { get; private set; } = (new List<string>() { "original" }).AsReadOnly();\n}\n\nvar myObject4 = new PrivateSetReadOnlyListClass();\n\nmyObject4.MyList = new List<string>() { "new" }; // this is NOT allowed\nmyObject4.MyList.Add("added"); // this is NOT allowed\n</code></pre>\n<p>Notice I also added the <code>.AsReadOnly()</code> cast to prevent consumers from casting this readonly list back to its mutable <code>List<string></code> type. This would require the consumer to actively decide to recast it, but it should be guarded against when the consumer can be assumed to be malevolent.</p>\n<p><strong>To summarize</strong>, there are three different solutions at play here:</p>\n<ul>\n<li>If you don't want the list to be overwritten, give it a private setter.</li>\n<li>If you don't want the list's elements to be altered, make it a readonly list (or any other readonly collection type</li>\n<li>For further protection, ensure that the object you expose cannot be cast back to a writeable collection type</li>\n<li>If you dont want the properties of the list elements themselves to be altered, then those elements' type must be immutable.</li>\n</ul>\n<p>To make this list property, its elements, and its elements' properties truly immutable, you have to comply with all four of the bullet points.</p>\n<hr />\n<h2>Comparing your answer to mine</h2>\n<p>This is obviously subjective, but I wanted to point out exactly what I changed about your approach:</p>\n<ul>\n<li>In the beginning of the answer, I very quickly highlighted the two distinct behaviors we were comparing (setting a list vs setting the list's content) without elaborating. This helps readers give structure to the more verbose part of the answer that follows that introduction, which helps them understand that when they read the first behavior, they can already compare it to what the second behavior is going to be. This lowers the cognitive load as you've provided a thread to follow.\n<ul>\n<li>Compare this to your answer, where both the "first" and "second" parts don't actually address the concrete result. They are two preparatory sections (and not very small ones at that).</li>\n<li>Additionally, by providing a terse summary of the content in the beginning, readers who already understand this problem (or even those who don't even know what a list is) can quickly decide that they don't need to read the whole thing. It's a nice-to-have, really.</li>\n</ul>\n</li>\n<li>The demo code is terse and to the point, directly using <code>list.Add()</code> and <code>list = new ...</code> and nothing else, to highlight the specific behaviors that we're addressing.</li>\n<li>I broke up the demo code into small, independent pieces, each of which can be digested by themselves, as they all focus on one particular behavior. Each digestible snippet is max 3 lines long (class definition with one property, object initialization, using the object)\n<ul>\n<li>Comparatively, your code is formatted in a way that I need to read the whole thing before I can then understand the individual steps and why they are different - this requires a much bigger cognitive load. While I was able to follow it, keep in mind that your target audience is already learning about something that is new/foreign to them, so you want to reduce that cognitive load as much as possible.</li>\n</ul>\n</li>\n<li>I used <code>string</code> instead of <code>User</code>, since the specific type of your list elements doesn't actually matter when we're discussing list behavior by itself. The fact that your list types are generic doubly proves that point, though using a concrete class instead of a generic type parameter does lower the cognitive load somewhat. But if you use a complex type for that, you're actually increasing that cognitive load again.</li>\n<li>In your example, there wasn't really a purpose to doing the same thing for all five elements of the array. So I stuck to a list with one element. This meant I could skip the <code>for</code> loops, which simplifies the example and again reduces the cognitive load.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T14:19:08.977",
"Id": "244111",
"ParentId": "244067",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244111",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T19:21:01.860",
"Id": "244067",
"Score": "1",
"Tags": [
"c#",
".net-core"
],
"Title": "Example of why IReadOnlyList<T> is better than public List<T> { get; private set; }"
}
|
244067
|
<p>I've seen some other implementations of cat (even in Rust) on this site, but none attempted to completely implement the GNU cat CLI as far as I can tell. This version that I am developing is complete (minus the -u parameter that is ignored by GNU cat anyway) and, as far as I can tell, works.</p>
<p>Some problems:</p>
<ul>
<li>It requires proper Unicode unless -A, -v, or -e are passed.</li>
<li>The code is a bit of a mess and could use cleaning up. Mainly this involves the way I have divided it into functions as well as my implementation of error handling.</li>
<li>I repeat myself a couple of times here and there.</li>
</ul>
<p>After all, the reason I am doing this is to learn. Could someone show me where my code could be best improved? Be as pedantic as you'd like. Thanks in advance.</p>
<p><code>common</code> is my own crate which implements the basic argument parsing used here. I can supply it if someone wants it.</p>
<p>main.rs:</p>
<pre class="lang-rust prettyprint-override"><code>mod partial_char;
mod configuration;
use common::Arg;
use std::env;
use std::fs::File;
use std::io;
use std::io::BufRead;
use std::io::BufReader;
use partial_char::PartialChar;
use configuration::Configuration;
fn show_help(program_name: &str) {
print!("Usage: {0} [options] <file>...
Concatenate FILE(s) to standard output.
With no FILE, or when FILE is -, read standard input.
Options:
-A, --show-all Equivalent to -vET
-b, --number-nonblank Number all non-empty output lines, starting with 1
-e Equivalent to -vE
-E, --show-ends Display a '$' after the end of each line
-n, --number Number all output lines, starting with 1; ignored if -b was passed
-s, --squeeze-blank Suppress repeated adjacent blank lines, output one empty line instead of many
-t Equivalent to -vT
-T, --show-tabs Display TAB characters as '^I'
-v, --show-nonprinting Display control characters (except for LFD and TAB) using '^' notation and precede characters that have the high bit set with 'M-'
{0} normally reads and writes in binary mode, unless one of -bensAE is passed or standard output is a terminal. An exit status of zero indicates success, and a nonzero value indicates failure.
", program_name);
}
fn handle_args(raw_args: Vec<String>) -> Result<(Configuration, Vec<String>), String> {
let args = common::parse_args(&raw_args[1..]);
let mut config = Configuration::default();
let mut files: Vec<String> = vec![];
for arg in args {
match arg {
Arg::Flag(flag) => match flag.as_str() {
"h" | "help" => {
show_help(&raw_args[0]);
// I don't like this, but it's simple
return Err(String::new());
}
"A" | "show-all" => config.show_all(),
"b" | "number-nonblank" => config.number_nonblanks = true,
"e" => config.show_nonprinting_and_line_ends(),
"E" | "show-ends" => config.show_line_ends = true,
"n" | "number" => config.number_lines(),
"s" | "squeeze-blank" => config.squeeze_blanks = true,
"t" => config.show_nonprinting_and_tabs(),
"T" | "show-tabs" => config.show_tabs = true,
"v" | "show-nonprinting" => config.show_nonprinting = true,
_ => {
show_help(&raw_args[0]);
return Err(String::from("invalid argument"));
}
},
Arg::Positional(file_name) => files.push(file_name),
Arg::FlagEquals(k, v) => {
// no x=y flags in cat
show_help(&raw_args[0]);
return Err(format!("invalid argument {}={}", k, v));
}
}
}
if files.len() == 0 {
files.push("-".to_owned());
}
Ok((config, files))
}
fn main() -> Result<(), String> {
let (config, files) = match handle_args(env::args().collect()) {
Err(e) => match e.as_str() {
// help was printed
"" => return Ok(()),
// actual error
_ => return Err(e),
},
Ok((config, files)) => (config, files),
};
for file in files {
if file == "-" {
let stdin_handle = io::stdin();
let stdin_reader = BufReader::new(stdin_handle);
cat(stdin_reader, &config).map_err(|e| format!("reading stdin: {}", e))?;
} else {
let file_handle = File::open(&file).map_err(|e| format!("opening {}: {}", file, e))?;
let file_reader = BufReader::new(file_handle);
cat(file_reader, &config).map_err(|e| format!("reading {}: {}", file, e))?;
}
}
Ok(())
}
/// Prints the prior line to stdout.
///
/// Includes logic to print the line number as well.
///
/// ## Side effects:
/// * May add 1 to `line`.
/// * May append a '$' character to `line_buf`.
///
/// ## Return value:
///
/// A boolean specifying whether the line that just ended was blank.
fn handle_newline(
config: &Configuration,
line: &mut usize,
prev_line_was_blank: bool,
line_buf: &mut String,
) -> bool {
let current_line_is_blank =
(config.number_nonblanks || config.squeeze_blanks) && line_buf.is_empty();
if config.show_line_ends {
line_buf.push('$');
}
if !(config.squeeze_blanks && current_line_is_blank && prev_line_was_blank) {
// line should be printed
if config.number_lines || (config.number_nonblanks && !current_line_is_blank) {
// number line
print!("{:6} ", line);
*line += 1;
}
// print line
println!("{}", line_buf);
}
current_line_is_blank
}
/// Pushes a single byte onto `line_buf`, or modifies `partial_char`
/// in the case that the byte is part of a Unicode character.
///
/// ## Side effects:
/// * May edit `partial_char`'s attributes.
/// * May append to `line_buf`.
///
/// ## Errors:
///
/// Unicode parsing may fail. In this case, a String will be returned.
fn push_byte(
byte: u8,
partial_char: &mut PartialChar,
line_buf: &mut String,
) -> Result<(), String> {
if partial_char.num_bytes_left == 0 && byte & 0xc0 != 0xc0 {
line_buf.push(byte as char);
} else if byte & 0xc0 == 0xc0 {
// start of Unicode char
partial_char.start_char(byte)?;
} else {
// continued Unicode char
partial_char.continue_char(byte)?;
if partial_char.num_bytes_left == 0 {
// should not panic; validity was checked!
let uc = partial_char.finish_char().unwrap();
line_buf.push(uc);
}
}
Ok(())
}
/// Prints the contents of the reader to stdout.
fn cat<F>(mut reader: BufReader<F>, config: &Configuration) -> io::Result<()>
where
F: io::Read,
{
let mut line = 1usize;
let mut prev_line_was_blank = false;
// builds a UTF-8 char when necessary
let mut partial_char = PartialChar::new();
// holds the current line
let mut line_buf = String::new();
loop {
let buf = reader.fill_buf()?;
let len = buf.len();
if len == 0 {
// EOF
break;
}
for c in buf {
// handle non-printing, if necessary
let mut c_special_repr = if config.show_nonprinting {
print_char_escaped(*c)
} else {
String::new()
};
// handle tab character
if config.show_tabs && *c == b'\t' {
c_special_repr += &format!("^I");
}
// handle non-special character
if c_special_repr.is_empty() {
if *c == b'\n' {
let current_line_is_blank =
handle_newline(&config, &mut line, prev_line_was_blank, &mut line_buf);
prev_line_was_blank = current_line_is_blank;
} else {
push_byte(*c, &mut partial_char, &mut line_buf)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
}
} else {
line_buf.push_str(&c_special_repr);
}
}
reader.consume(len);
}
Ok(())
}
/// Converts a byte to its escaped form.
///
/// Bytes with the high bit (`0x80`) set are given the M- prefix.
///
/// Bytes with values from 0..31 (or 127)
/// are control characters, and thus prefixed with ^.
fn print_char_escaped(c: u8) -> String {
let mut c = c;
// do non-printing checks
let (meta, high_bit) = if c & 0x80 != 0 {
// high bit is set, unset it
c &= !0x80;
(format!("M-"), true)
} else {
(String::new(), false)
};
let c = c;
// now check for control chars
let cs = match c {
// null char
0 => format!("^@"),
// control char is represented as letter
1..=26 => {
if high_bit {
// 1 + 64 = 65 = 'A'
// 26 + 64 = 90 = 'Z'
format!("^{}", (c + 64) as char)
} else {
match c {
// TAB, ignore; it is handled by config.show_tabs
b'\t' => String::new(),
// LF, ignore; it is handled by config.show_line_ends
b'\n' => String::new(),
// other control chars are treated the same
_ => format!("^{}", (c + 64) as char),
}
}
}
// ESC
27 => format!("^["),
// FS
28 => format!("^\\"),
// GS
29 => format!("^]"),
// RS
30 => format!("^^"),
// US
31 => format!("^_"),
// DEL
127 => format!("^?"),
// printable char
_ => format!("{}", c as char),
};
meta + cs.as_str()
}
</code></pre>
<p>configuration.rs:</p>
<pre class="lang-rust prettyprint-override"><code>#[derive(Debug)]
pub struct Configuration {
pub show_nonprinting: bool,
pub show_tabs: bool,
pub squeeze_blanks: bool,
pub number_lines: bool,
pub show_line_ends: bool,
pub number_nonblanks: bool,
}
impl Default for Configuration {
fn default() -> Self {
Configuration {
show_nonprinting: false,
show_tabs: false,
show_line_ends: false,
squeeze_blanks: false,
number_lines: false,
number_nonblanks: false,
}
}
}
impl Configuration {
pub fn show_all(&mut self) {
self.show_nonprinting = true;
self.show_tabs = true;
self.show_line_ends = true;
}
pub fn show_nonprinting_and_tabs(&mut self) {
self.show_nonprinting = true;
self.show_tabs = true;
}
pub fn show_nonprinting_and_line_ends(&mut self) {
self.show_nonprinting = true;
self.show_line_ends = true;
}
pub fn number_lines(&mut self) {
if !self.number_nonblanks {
self.number_lines = true;
}
}
}
</code></pre>
<p>partial_char.rs:</p>
<pre class="lang-rust prettyprint-override"><code>use std::str::FromStr;
pub struct PartialChar {
bytes: [u8; 6],
num_bytes: u8,
pub num_bytes_left: u8,
}
impl PartialChar {
pub fn new() -> Self {
Self {
bytes: [0; 6],
num_bytes: 0,
num_bytes_left: 0,
}
}
pub fn start_char(&mut self, byte: u8) -> Result<(), String> {
// start at third bit
let mut mask = 0x20;
self.num_bytes_left = 1;
while byte & mask != 0 {
if mask == 0x02 {
// too many set bits to be valid
return Err(format!("Invalid UTF-8 start byte: 0x{:2x}", byte));
}
self.num_bytes_left += 1;
mask >>= 1;
}
self.num_bytes = 1;
self.bytes[0] = byte;
Ok(())
}
pub fn continue_char(&mut self, byte: u8) -> Result<(), String> {
// expected: first two bits are 0b10
if byte & 0xc0 != 0x80 {
return Err(format!("Invalid UTF-8 continuation byte: 0x{:2x}", byte));
}
self.num_bytes_left -= 1;
self.bytes[self.num_bytes as usize] = byte;
self.num_bytes += 1;
Ok(())
}
pub fn finish_char(&self) -> Result<char, String> {
if self.num_bytes_left != 0 || self.num_bytes == 0 {
return Err(String::from("does not contain a finished UTF-8 char"));
}
// unwrapping here because UTF-8 was already validated
let c = std::str::from_utf8(&self.bytes[..self.num_bytes as usize]).unwrap();
Ok(char::from_str(c).unwrap())
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T19:29:14.173",
"Id": "479134",
"Score": "1",
"body": "This is pretty cool! I think the first thing you could do is to start splitting it up into smaller functions to make it easier to maintain and read. The embedded if conditions is always hard to follow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T20:26:23.767",
"Id": "479137",
"Score": "0",
"body": "Thanks for the compliment. You're talking mainly about the 'cat' function, correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T20:31:53.530",
"Id": "479138",
"Score": "0",
"body": "I'm talking about every function that is over 15-20 lines of code. Which includes the main and cat functions. So yes :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T20:36:47.723",
"Id": "479139",
"Score": "0",
"body": "That's a tough restriction. I'll do my best :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T20:48:49.333",
"Id": "479141",
"Score": "1",
"body": "It does seem like a tough restriction, however on the long run smaller bits of code are easier to test (unit/integration testing), easier to maintain, easier to read, reduces code duplications, etc. Any company with coding standards would want this to be refactored. Lets not take into account someone joining your group to maintain this and just take the most simple example of, would you be able to easily remember how this works in a month or two? I'd be impressed. Anyway, keep up the good work!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T22:31:19.810",
"Id": "479148",
"Score": "0",
"body": "I have a second iteration. What is the correct way to post it here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T06:54:43.970",
"Id": "479171",
"Score": "0",
"body": "Replace your current code with the new code. Would also be nice to include the iteration number. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T05:29:49.830",
"Id": "479313",
"Score": "0",
"body": "Hm, that's a bit opinionated, to not implement only the exact function demanded by POSIX (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/cat.html) :p I'd probably get rid of the `if file == \"-\" ` expr and use a (filename,file handle) tuple for that or the like. Also your code is probably going to have big issues with long lines as you collect all bytes til NL in one buffer to pass around. This will get problematic if you happen to not have enough RAM. I think doing one-byte lookahead after a NL for the line number is a better solution"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T05:33:32.137",
"Id": "479315",
"Score": "0",
"body": "Uh, and it definitely requires Unicode or at least something ASCII based, even with -Ave this will break for SJIS, KOI8 or ISO8859. One might argue these to be legacy (I wouldn't wholly agree) as Rust basically does, but I definitely think this'd be too much for this implementation. Just implementing the POSIX feature set would btw. circumvent any encoding issues ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T08:24:28.810",
"Id": "479326",
"Score": "0",
"body": "@onContentStop *\"I have a second iteration. What is the correct way to post it here?\"* As long as there has been no review yet it's fine to change the code. However, an edit may not invalidate any already existing review. However, keep in mind that phrases like \"second iteration\" or \"my new variant\" can be misleading for possible reviewers, as they will check your question/post history. Your current version is, for most reviewers, the only version, unless you specifically link to a previous one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T08:25:29.087",
"Id": "479327",
"Score": "1",
"body": "@kemicofaghost your first comment could already have been a review ;). A short one, but it's a (30-second) review nonetheless. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T14:57:53.437",
"Id": "479354",
"Score": "0",
"body": "@larkey My goal wasn't necessarily to implement the POSIX switch, but to replicate the functionality of GNU cat. I could easily add a -u switch that does nothing, but what's the point? Good point on the lineBuf being potentially unbounded in size. I can work to fix that. The only reason I am not encoding agnostic at the moment is that lineBuf is a string. I can try and learn to use byte buffers for a more low-level implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T15:00:17.423",
"Id": "479355",
"Score": "0",
"body": "@Zeta Thanks for the clarification."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T16:32:25.553",
"Id": "479367",
"Score": "0",
"body": "@onContentStop Well, in POSIX -u does actually have an effect ;) To be encoding agnostic you'd need to implement encoders/decoders for the diverse codings. As someone who's done that for some Solaris distributions, I can't recommend doing this."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T19:25:04.920",
"Id": "244069",
"Score": "6",
"Tags": [
"rust"
],
"Title": "Simple-ish Rust implementation of 'cat'"
}
|
244069
|
<p>I am trying to callback C++ class methods from C. Now I have got something working, but am not sure if this is the best solution.</p>
<p>I am looking for feedback, as to if there is something wrong with this approach, and how could I make this better.</p>
<p>So, here goes my code:</p>
<p>This is the C++ class <code>Foo</code>. The class has the methods <code>getValue()</code> & <code>setValue()</code>, which I would like to like to be called-back from the C code:</p>
<p>Contents of <code>Foo.h</code>:</p>
<pre><code>#ifdef __cplusplus
class Foo
{
public:
Foo();
int getValue() const;
void setValue(int value);
private:
int value_;
};
#endif
// Free functions
int c_wrapper_getValue(void *arg1);
void c_wrapper_setValue(int value, void *arg1);
</code></pre>
<p>Contents of the source file, <code>Foo.cpp</code>:</p>
<pre><code>#include "Foo.h"
Foo::Foo() :
value_{0}
{}
int Foo::getValue() const
{
return value_;
}
void Foo::setValue(int value)
{
value_ = value;
}
void c_wrapper_setValue(int value, void *arg1)
{
Foo* foo_instance = static_cast<Foo*>(arg1);
foo_instance->setValue(value);
}
int c_wrapper_getValue(void *arg1)
{
Foo* foo_instance = static_cast<Foo*>(arg1);
return foo_instance->getValue();
}
</code></pre>
<p>Here is the code for the C files, which in turn call the <code>Foo</code> class members. First, the header <code>Test.h</code> file:</p>
<pre><code>#include <stdio.h>
#include "Foo.h"
#ifdef __cplusplus
extern "C" {
#endif
// Callback function pointers
typedef int (*get_handler_t)(void* arg1);
typedef void (*set_handler_t)(int foo, void* arg1);
void register_handler(get_handler_t g, set_handler_t s, void* p_instance);
// These are the functions which call the callback functions
int call_cpp_get_function();
void call_cpp_set_function(int value);
#ifdef __cplusplus
}
#endif
</code></pre>
<p>And finally the <code>Test.c</code> file:</p>
<pre><code>#include "Test.h"
static get_handler_t get_handler_ = NULL; /**< Getter function pointer of type int (*g)(void *). */
static set_handler_t set_handler_ = NULL; /**< Setter function pointer of type void (*s)(int, void *). */
static void* foo_object_instance = NULL; /**< Instance of Foo object. */
//! Registers the getter and setter function with the object of Class Foo
//! \param g Getter function pointer of type int (*g)(void *).
//! \param s Setter function pointer of type void (*s)(int, void *).
//! \param p_instance Instance of Foo object.
void register_handler(
int (*g)(void *),
void (*s)(int, void *),
void* p_instance)
{
get_handler_ = g;
set_handler_ = s;
foo_object_instance = p_instance;
}
//! Function calls the get function of class Foo
//! \return Value of value_ from class Foo
int call_cpp_get_function()
{
return get_handler_(foo_object_instance);
}
//! Function calls the set function of class Foo
//! \param value Value to be set in class Foo
void call_cpp_set_function(int value)
{
set_handler_(value, foo_object_instance);
}
</code></pre>
<p>Now I could create an object and call the functions present in my C file, which called back the C++ methods, like this:</p>
<pre><code>Foo foo_object;
register_handler(&c_wrapper_getValue, &c_wrapper_setValue, static_cast<void *>(&foo_object));
call_cpp_get_function();
call_cpp_set_function(35);
</code></pre>
<p>I do have some constraints in my case, for example I can't use STL, since the code is supposed to run on an embedded system. So, how bad is my code?</p>
|
[] |
[
{
"body": "<h3>Encapsulate stuff that shouldn't be <code>public</code></h3>\n<p>I'd rather make the callback functions private static functions of the c++ class This helps to encapsulate the nasty <code>void*</code>casts:</p>\n<pre><code>#ifdef __cplusplus\nclass Foo {\npublic:\n Foo();\n int getValue() const;\n void setValue(int value);\n\n void register_callbacks();\n\nprivate:\n int value_;\n\n static int cb_getValue(void *arg1);\n static void cb_wrapper_setValue(int value, void *arg1);\n};\n#endif\n</code></pre>\n<p>Implementation:</p>\n<pre><code>void Foo::register_callbacks() {\n register_handler(Foo::cb_getValue, Foo::cb_setValue, static_cast<void *>(this));\n}\n\nvoid Foo::cb_setValue(int value, void *arg1) {\n Foo* foo_instance = static_cast<Foo*>(arg1);\n foo_instance->setValue(value);\n}\n\nint Foo::cb_getValue(void *arg1) {\n Foo* foo_instance = static_cast<Foo*>(arg1);\n return foo_instance->getValue();\n}\n</code></pre>\n<p>Usage:</p>\n<pre><code>Foo foo_object;\nfoo_object.register_callbacks();\ncall_cpp_get_function();\ncall_cpp_set_function(35);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T21:26:07.180",
"Id": "479144",
"Score": "0",
"body": "This seems much more neater! Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T21:16:00.227",
"Id": "244072",
"ParentId": "244070",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244072",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T20:47:08.823",
"Id": "244070",
"Score": "3",
"Tags": [
"c++",
"c",
"callback"
],
"Title": "Callback C++ Class method from C"
}
|
244070
|
<p>I have <a href="https://codereview.stackexchange.com/questions/244007/laravel-scope-get-request-data-param">question about scope</a> yesterday, and someone gives an answer to don't return anything in scope. Is return something in scope really bad practice? Should I not return anything in the model except query?</p>
<p>Rather than scope, I want to create a normal method to return the select2 format. I have so many model/table that I need to return to select2 format, I think it's WET (write every time) if I must write every model or controller. I think I need to use DRY(Don't Repeat Yourself) principle, so I want to use a trait like below:</p>
<pre><code>trait ModelTrait
{
public static function getSelect2format($column = "name")
{
$data = static::select('id', $column.' as text')->orderBy($column, 'asc')->where($column, "like", "%".request()->q."%");
if (is_array(request()->filter) && !empty(request()->filter)) {
foreach(request()->filter as $key => $val)
{
if(in_array($key,$this->filterable))
{
$data = $data->where($key, $val);
}
}
}
$data = $data->limit(5)->get();
return $data;
}
}
</code></pre>
<p>I just need to call <code>use ModelTrait</code> in every model that I need and call it in the controller like below:</p>
<pre><code>public function selectJson()
{
$data = Customer::getSelect2Format("column_name");
return \Response::json($data);
}
</code></pre>
<p>Is the code above break the best practice?
What are the concerns or something that I need to improve?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T04:35:47.253",
"Id": "479161",
"Score": "1",
"body": "I'm sorry to inform you that your code is not working as intended. You cannot call a non-static method statically. Well actualy you can, but you will get a fatal error if the method uses `$this`. Your method uses `$this` on the very first line of its body. Not working code is off-topic on this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T05:42:41.513",
"Id": "479164",
"Score": "1",
"body": "@slepic Sorry, Actually I have not tested it. Now I tested it and it's working, just changed the method type to static and ``$this`` to ``static::`` , Hope you can improve more, Thank you."
}
] |
[
{
"body": "<blockquote>\n<p>I have question about scope yesterday, and someone gives an answer to don't return anything in scope. Is return something in scope really bad practice?</p>\n</blockquote>\n<ul>\n<li><p>This is because laravel is handling "it" for you.</p>\n</li>\n<li><p>getSelect2Format is not the best name since you are not handling formatting but apply a specific set of rules relevant to select2 js plugin.</p>\n</li>\n<li><p>I would suggest a repository class or a helper class to handle this task.</p>\n</li>\n<li><p>Your code is messy, very long lines too, which is hard to read! I would suggest following PSR-12.</p>\n</li>\n<li><p>I would suggest using <code>response()</code> or just <code>return $data</code> in controller class methods.</p>\n</li>\n<li><p>I would also suggest early returns in your methods to reduce nesting hence easy reviewing by reviewers.</p>\n</li>\n<li><p>suggest not using <code>->get()</code> in a method unless you are absolutely certain on what method should do. i.e. you might want to apply a scope to this query later on.</p>\n</li>\n<li><p>I suggest passing request data into the class to make it easier to test. Also, the less your class knows about other parts of the system the better.</p>\n</li>\n<li><p>Dont you have to use DB::raw for <code>$column.' as text'</code>?</p>\n</li>\n</ul>\n<pre><code>class select2Filters\n{\n public static function apply(\n Model $model, \n array $data, \n string $column = 'name', \n int $limit = 5\n ) {\n $filter = Arr::get($data, 'filter');\n \n return $model::selectRaw(['id', "{$column} as text"])\n ->where($column, 'like', "%{$data['q']}%")\n ->when(is_array($filter), function($query) use ($filter) {\n $query->where(Arr::only($filter, $model::filterable)); \n })\n ->orderBy($column, 'asc')\n ->limit($limit)\n ->get();\n }\n}\n</code></pre>\n<p>I would also suggest adding an interface to each model that should have support for <code>select2Filters</code>. That interface should inforce <code>filterable</code> variable.</p>\n<p>I would personally not use <code>static</code>, that way you can add configuration methods, i.e. setLimit(). OR use data struct class to contain data needed for <code>select2Filters</code> class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T12:17:50.073",
"Id": "479535",
"Score": "0",
"body": "Thanks for your review, I like it. And sorry, my code was written when I write this question(without any ide/editor) so it's not formatted correctly. Usually, I use auto formatted to PSR12 using PhpStrom code formatted. And actually, I just created my own library for this case and also to learn or improve my skill, maybe I will create a question about that library. About PSR12, I have another question which maybe you can help https://stackoverflow.com/questions/62480588/how-to-set-phpstorm-code-style-as-styleci-style-rule"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T15:02:16.247",
"Id": "479552",
"Score": "0",
"body": "Hi, I am afraid I have no idea on how to handle formatting in php storm, from what I know you meant to have a config which defines formatting and that configuration can be downloaded from the official psr website"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T09:39:26.220",
"Id": "244252",
"ParentId": "244071",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244252",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T20:53:10.463",
"Id": "244071",
"Score": "2",
"Tags": [
"php",
"laravel",
"trait"
],
"Title": "Using method trait to return something in laravel model"
}
|
244071
|
<p>I'm wondering whether there is a way to make this even more efficient or reduce the number of variables.</p>
<pre class="lang-py prettyprint-override"><code>import random
numberOfStreaks = 0
results = []
head_streak = ['H'] * 6
tail_streak = ['T'] * 6
sample_size = 1000000
for i, experimentNumber in enumerate(range(sample_size)):
# Code that creates a list of 100 'heads' or 'tails' values.
results.append(random.choice(('H', 'T')))
# Code that checks if there is a streak of 6 heads or tails in a row.
try:
temp = results[i-5:]
if temp == head_streak or temp == tail_streak:
numberOfStreaks += 1
except:
pass
print('Chance of streak: %s%%' % (numberOfStreaks / sample_size))
</code></pre>
|
[] |
[
{
"body": "<pre><code> # Code that creates a list of 100 'heads' or 'tails' values.\n results.append(random.choice(('H', 'T')))\n</code></pre>\n<p>This comment is severely misleading: the code does not create a list of 100 values, it create an infinitely growing list that extends up to <code>sampleSize</code> values by the time the program terminates.</p>\n<hr />\n<p>Independently of the misleading comment, this is a bad idea, and can be avoided by limiting the size of the <code>results</code> list in some say (<code>del results[:-6]</code>, or <code>results = results[-6:]</code>, I'm not sure which is better). This would also obsolete the <code>temp</code> variable, because the <code>results</code> array would no longer contain extra flips.</p>\n<hr />\n<pre><code> try:\n temp = results[i-5:]\n if temp == head_streak or temp == tail_streak:\n numberOfStreaks += 1\n except:\n pass\n</code></pre>\n<p>Bare <code>except</code> statements are a bad idea. Bare <code>except:pass</code> statements even more so. Among other problems, it means that if you press Ctrl-C while your code is executing that section, the code won't exit.</p>\n<p>It's not clear what exception you are trying to catch (<code>results[i-5:]</code> doesn't throw an error if <code>results</code> is less than five items long; it just truncates the list), so I can't suggest a direct replacement, but I would recommend either catching a specific exception, or removing the try-catch entirely.</p>\n<hr />\n<p>Python lists natively support negative indexing, so you can simplify <code>results[i-5:]</code> to <code>results[-6:]</code> and remove the <code>i</code> variable entirely. As suggested by the question asker in the comments, this makes the <code>enumerate</code> call unnecessary.</p>\n<hr />\n<p>The <code>i</code> variable will then be unused. It's clearer to name variables you don't use as <code>_</code>, so it's easy to tell that they aren't used.</p>\n<hr />\n<p>Full code:</p>\n<pre><code>import random\nnumberOfStreaks = 0\nresults = []\nhead_streak = ['H'] * 6\ntail_streak = ['T'] * 6\nsample_size = 1000000\nfor _ in range(sample_size):\n # Code that generates another 'heads' or 'tails' value\n results.append(random.choice(('H', 'T')))\n\n # Code that checks if there is a streak of 5 heads or tails in a row.\n results = results[-6:]\n if results == head_streak or results == tail_streak:\n numberOfStreaks += 1\n\nprint('Chance of streak: %s%%' % (numberOfStreaks / sample_size))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T22:24:44.747",
"Id": "479147",
"Score": "0",
"body": "in that case i wouldn't even need enumerate would i, for i in range(samplesize) works"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T22:11:08.500",
"Id": "244075",
"ParentId": "244073",
"Score": "1"
}
},
{
"body": "<h1>Eliminating useless code</h1>\n<p>Enumerating a range is really pointless</p>\n<pre><code>In [6]: sample_size = 5\n\nIn [7]: for i, experimentNumber in enumerate(range(sample_size)):\n ...: print(i, experimentNumber)\n ...: \n0 0\n1 1\n2 2\n3 3\n4 4\n</code></pre>\n<p>So we can easily replace one by the other. We do not even need to replace as <code>experimentNumber</code> is not used anywhere. Next we notice that <code>i</code> is also used only once where we can replace <code>results[i-5:]</code> by superior construct <code>results[-6:]</code>.\nWe also eliminate the superfluous exception handling. So far this is already covered by @ppperys answer.</p>\n<h1>Efficiency</h1>\n<p>you create a complet list of length <code>sample_size</code> of random values in memory. This is not required and may be a problem on big sample sizes. As you always need the last 6 values only you could go for <code>collections.deque</code> which can maintain a <code>maxlen</code>.</p>\n<pre><code>from collections import deque\nresults = deque(maxlen=6)\n</code></pre>\n<p>For the evaluation made easy we do not use <code>('H', 'T')</code> but numbers. We do not need to comare with a streak any more but do it arithmetically. Here is the only pitfall - we must check if the queue is filled completely to not accidentally accept a short sequence of zeros.</p>\n<pre><code>for _ in range(sample_size):\n results.append(random.choice((0, 1)))\n if len(results) == 6 and sum(results) in (0, 6):\n numberOfStreaks += 1\n</code></pre>\n<p>This not only saves memory but we also get rid of a temporary <code>temp</code> and the predifined <code>head_streak</code> and <code>tail_streak</code>. We notice the magic number <code>6</code> appearing multiple times - use a variable. We also make a testable function. We end up with</p>\n<pre><code>import random\nfrom collections import deque\n\ndef streak_probability(streak_len, sample_size):\n results = deque(maxlen=streak_len)\n numberOfStreaks = 0\n for _ in range(sample_size):\n results.append(random.choice((0, 1)))\n if len(results) == streak_len and sum(results) in (0, streak_len):\n numberOfStreaks += 1\n return numberOfStreaks / sample_size\n\n\nprint('Chance of streak: %s%%' % (streak_probability(6, 1000000))\n</code></pre>\n<h1>Algorithm</h1>\n<p>This simulation will give good results for big numbers of <code>sample_size</code>. However if the sample size was smaller than <code>6</code> it will always return <code>0</code>. As you divide the final streak count by the sample size you indicate, that you would like to get the probability of a streak per "additional" coin toss. So we should fill the queue before starting to count. That way an average of a large number of runs with a small sample size would match a single run of a large sample size. If we prefill we do not have to check the fill state of the queue (yes I filled to the max while one less would be sufficient).</p>\n<pre><code>def prefilled_streak_probability(streak_len, sample_size):\n results = deque((random.choice((0, 1)) for _ in range(streak_len)), maxlen=streak_len)\n numberOfStreaks = 0\n for _ in range(sample_size):\n results.append(random.choice((0, 1)))\n if sum(results) in (0, streak_len):\n numberOfStreaks += 1\n return numberOfStreaks / sample_size\n</code></pre>\n<p>Now test the difference - we compare the original sample size of 1.000.000 to 100.000 repetitions of sample size 10</p>\n<pre><code>s=10\nn=100000\nprint('no prefill')\nprint('Single big sample - Chance of streak: %s%%' % (streak_probability(6, s*n)))\nprobs = [streak_probability(6, s) for _ in range(n)]\nprint('Multiple small samples - Chance of streak: %s%%' % (sum(probs)/len(probs)))\n\nprint('with prefill')\nprint('Single big sample - Chance of streak: %s%%' % (prefilled_streak_probability(6, s*n)))\nprobs = [prefilled_streak_probability(6, s) for _ in range(n)]\nprint('Multiple small samples - Chance of streak: %s%%' % (sum(probs)/len(probs)))\n</code></pre>\n<p>we get</p>\n<pre><code>no prefill\nSingle big sample - Chance of streak: 0.031372%\nMultiple small samples - Chance of streak: 0.01573599999999932%\nwith prefill\nSingle big sample - Chance of streak: 0.031093%\nMultiple small samples - Chance of streak: 0.031131999999994574%\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T21:53:32.350",
"Id": "479409",
"Score": "0",
"body": "You could use `random.choices` and drop the loop for shorter and more readable code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T07:21:57.077",
"Id": "479620",
"Score": "0",
"body": "@agtoever Right. But I was explicitely going for a smaller memory footprint. If going for speed I would change not only the random function but also the streak counting."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T16:06:25.180",
"Id": "244121",
"ParentId": "244073",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244075",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T21:30:25.220",
"Id": "244073",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"random"
],
"Title": "Python - Predicting the probability of 6 Heads or Tails in a row from a set sample size"
}
|
244073
|
<p>So as a starter Java project I decided to web scrape some data (specifically all historically No. 1 ranked players for weeks starting from 1973) from the ATP website, and do something with it (IPR). I'm in the process of <strong>refactoring my working web scraper</strong> and wanted some feedback.</p>
<ul>
<li><p>Currently my scraper retrieves the No.1s - or so it seems. I haven't tested it apart from just printing it to my console and verifying it that way. One thing I feel is that I can tighten some of the exception handling, but I wasn't sure how what test cases to develop in JUnit for that. Any tips?</p>
</li>
<li><p>More importantly, feedback on the code style would be really appreciated! The bulk of my code is in <code>Scraper</code> (duh), but I'm not sure I'm too comfortable with having various static methods. That being said, a sprawling main function is not ideal either, especially when there are separable pieces of the logic that the scraper performs. Does this indicate I need to somehow break the Scraper design into smaller objects? What be a good design practice?</p>
</li>
<li><p>Any other feedback, especially related to best practices and idioms in Java would be appreciated (I come from a primarily C & C++ background).</p>
</li>
</ul>
<p>Here's my code:</p>
<p>Scraper:</p>
<pre><code>package Scraper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
public class Scraper {
public static void main() {
final String ATP_URL_PREFIX = "https://www.atptour.com/en/rankings/singles?";
final String ATP_URL_SUFFIX = "&rankRange=0-100";
// get the list of historical ranking weeks - basically from 1973-present.
ArrayList<String> weeks = new ArrayList<String>();
weeks = getWeeksForRankings(ATP_URL_PREFIX, weeks);
// weeks might be null if no valid HTML
if (weeks.size() == 0) {
System.out.println("Please provide a historical time range! Cannot rank otherwise!");
return;
}
getPlayerNames(ATP_URL_PREFIX, ATP_URL_SUFFIX, weeks);
}
static ArrayList getWeeksForRankings(String url, ArrayList<String> weeks) {
try {
final Document document = Jsoup.connect(url).get();
// extract the series of list items corresponding to the ranking weeks, from the dropdown menu
Elements rankingWeeksList = document.getElementsByAttributeValue("data-value", "rankDate").select("ul li");
for (Element li : rankingWeeksList) {
// for accessing the relevant week's ranking page later, the rankDate= param in the URL takes '-'s
// instead of dots so we replace the characters here and then add them to out list.
String week = li.text().replaceAll("\\.", "-");
weeks.add(week);
}
} catch (IOException e) {
System.out.println("Error while connecting and parsing HTML: " + e);
System.exit(1);
} catch (Exception e) {
System.out.println("Fatal Error: " + e);
System.exit(1);
}
Collections.reverse(weeks); // start from 1973.
return weeks;
}
static void getPlayerNames(String url_prefix, String url_suffix, ArrayList<String> weeks) {
// dynamically update a player's ranking and animate his status
for (String week : weeks) {
String url = url_prefix+"rankDate="+week+url_suffix;
try {
final int SECONDS_TO_MILLISECONDS = 1000;
// time out is an issue. ideally, try mutliple times to get the data??
final Document document = Jsoup.connect(url).timeout(180 * SECONDS_TO_MILLISECONDS).get();
Element player = document.getElementsByClass("player-cell").first();
if (player == null) {
continue;
} else {
System.out.println("Week: " + week + " No.1: "+ player.text());
}
} catch (IOException e) {
System.out.println("Error while connecting and parsing HTML: " + e);
System.exit(1);
}
}
}
}
</code></pre>
<p>Main Driver:</p>
<pre><code>package tennisProject;
import Scraper.Scraper;
public class TennisProject {
public static void main(String[] args) {
Scraper.main();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T20:08:41.237",
"Id": "479401",
"Score": "2",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Please consider posting a new question as follow-up instead, feel free to add links back-and-forth for bonus context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T20:12:37.297",
"Id": "479402",
"Score": "0",
"body": "oh, sorry I wasn't aware of that! I'll post a new question as a follow up, thank you!"
}
] |
[
{
"body": "<h2>Some style issues first:</h2>\n<ul>\n<li><p>Package names should be all lowercase ASCII letters. No <code>camelCase</code>, <code>PascalCase</code>, <code>snake_case</code> or <code>kebab-case</code>. So <code>tennisproject</code> and <code>scanner</code>.</p>\n</li>\n<li><p>Local variables should never be uppercase <code>SNAKE_CASE</code>, but <code>camelCase</code>. So <code>atpUrlPrefix</code> instead of <code>ATP_URL_PREFIX</code> and so on. You probably want those to be class <em>constants</em> anyways, which use uppercase <code>SNAKE_CASE</code>. These are <strong>fields</strong> that are <code>private static final</code>.</p>\n</li>\n<li><p>The same is true for parameters. Always <code>camelCase</code>. So <code>urlPrefix</code> <code>url_prefix</code> and so on.</p>\n</li>\n<li><p>Don't declare a method called <code>main</code> that isn't actually a Java style main method. It's confusing. You can get rid of the <code>TennisProject</code> class all together.</p>\n</li>\n</ul>\n<hr />\n<h2>Some notes on code snippets before I present a "cleaned up" version</h2>\n<pre><code>ArrayList<String> weeks = new ArrayList<>();\nweeks = getWeeksForRankings(ATP_URL_PREFIX, weeks);\n</code></pre>\n<p>No need to create a list and pass it to the method here. Remove the list parameter and have the method create the list. Also change the return type of <code>getWeeksForRankings</code> from <code>ArrayList</code> to <code>List<String></code>. Raw type usage is discouraged, and there is usually no need for the caller to know which list implementation is returned. The same is true for the parameter. Use the broadest type of Collection possible.</p>\n<hr />\n<pre><code>} catch (IOException e) {\n System.out.println("Error while connecting and parsing HTML: " + e);\n System.exit(1);\n} catch (Exception e) {\n System.out.println("Fatal Error: " + e);\n System.exit(1);\n}\n</code></pre>\n<p>(Re)throw the exception(s) after handling them (in your case, handling them is just printing out an error message) if the error is unrecoverable instead of using <code>System.exit</code> and let the caller handle the exception. In your case, it would just be the runtime terminating the application.</p>\n<hr />\n<pre><code>if (weeks.size() == 0) {\n</code></pre>\n<p>Use <code>weeks.isEmpty()</code> instead.</p>\n<hr />\n<h2>"Cleaned up" code</h2>\n<p>Now, I would make it so that <code>Scanner</code> is an instantiable class with instance methods. That way you can create multiple instances and pass different parameters if needed.</p>\n<p>First, we add a Result POJO:</p>\n<pre><code>public class WeeklyResult {\n private final String week;\n private final String playerName;\n\n public WeeklyResult(final String week, final String playerName) {\n this.week = week;\n this.playerName = playerName;\n }\n\n public String getWeek() {\n return week;\n }\n\n public String getPlayerName() {\n return playerName;\n }\n}\n</code></pre>\n<p>Now, the cleaned up <code>Scraper</code> class. The changes are substantial, so please read the explanation below.</p>\n<pre><code>import org.jsoup.Jsoup;\nimport org.jsoup.nodes.Document;\nimport org.jsoup.nodes.Element;\nimport org.jsoup.select.Elements;\n\nimport java.io.IOException;\nimport java.time.Duration;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\npublic class Scraper {\n private final String urlPrefix;\n private final String urlSuffix;\n private final Duration timeout;\n\n public Scraper(final String urlPrefix, final String urlSuffix, final Duration timeout) {\n this.urlPrefix = urlPrefix;\n this.urlSuffix = urlSuffix;\n this.timeout = timeout;\n }\n\n public List<WeeklyResult> scrape() throws IOException {\n final List<String> weeks = loadWeeks();\n\n return loadResults(weeks);\n }\n\n private List<String> loadWeeks() throws IOException {\n final Document document = loadDocument(urlPrefix);\n final Elements elements = selectRankingWeeksElements(document);\n final List<String> result = extractWeeks(elements);\n\n return notEmptyElseThrow(result);\n }\n\n private Document loadDocument(final String url) throws IOException {\n return Jsoup.connect(url).timeout((int) timeout.toMillis()).get();\n }\n\n private static List<String> extractWeeks(final Collection<Element> elements) {\n return elements.stream()\n .map(Scraper::extractWeek)\n .collect(Collectors.toList());\n }\n\n private List<WeeklyResult> loadResults(final List<String> weeks) throws IOException {\n final List<WeeklyResult> result = new ArrayList<>();\n\n for (final String week : weeks) {\n loadWeeklyResult(week).ifPresent(result::add);\n }\n\n return result;\n }\n\n private Optional<WeeklyResult> loadWeeklyResult(final String week) throws IOException {\n final Document document = loadDocument(weeklyResultUrl(week));\n final Element playerCell = selectPlayerCellElement(document);\n\n return Optional.ofNullable(playerCell).map(element -> new WeeklyResult(week, element.text()));\n }\n\n private String weeklyResultUrl(final String week) {\n return urlPrefix + "rankDate=" + week + urlSuffix;\n }\n\n private static String extractWeek(final Element li) {\n return li.text().replaceAll("\\\\.", "-");\n }\n\n private static Elements selectRankingWeeksElements(final Document document) {\n final Elements result = document.getElementsByAttributeValue("data-value", "rankDate")\n .select("ul li");\n\n Collections.reverse(result);\n return result;\n }\n\n private static List<String> notEmptyElseThrow(final List<String> weeks) throws IOException {\n if (weeks.isEmpty()) {\n throw new IOException("Please provide a historical time range! Cannot rank otherwise!");\n }\n\n return weeks;\n }\n\n private static Element selectPlayerCellElement(final Document document) {\n return document.getElementsByClass("player-cell").first();\n }\n\n public static void main(final String[] args) throws IOException {\n final Scraper scraper =\n new Scraper("https://www.atptour.com/en/rankings/singles?", "&rankRange=0-100", Duration.ofSeconds(180));\n\n for (final WeeklyResult weeklyResult : scraper.scrape()) {\n System.out.println("Week: " + weeklyResult.getWeek() + " No.1: " + weeklyResult.getPlayerName());\n }\n }\n}\n</code></pre>\n<p>You will notice that there are a lot of methods, but all methods are <strong>very small</strong>. In fact they are so small that <strong>no method has more than four lines of actual code.</strong></p>\n<p>Nobody expects you to do this right of the bat as a novice, but it is something you can strive towards. Notice that the code got <strong>longer</strong>, which many people think is a bad thing. It isn't. The fact that every method is no longer than four lines makes each methods purpose blindingly obvious, especially if you use meaningful names.</p>\n<p>As I said earlier, I made the <code>Scraper</code> an instantiable object that has the url prefix and suffix as constructor parameters, as well as the desired timeout as a <code>Duration</code> object.</p>\n<p>I've made all the error handling a responsibility of the caller. Ideally, you might want to define your own exception and wrap the IOExceptions in them, for example you could have a <code>ScraperException</code> that is thrown when the Scraper encounters an error.</p>\n<p>Note also that all the result handling is moved to the caller also. The caller receives a result object in form of a <code>List<WeeklyResult></code> and can do with it whatever they please. If you want to handle results as soon as they are parsed but want to stay flexible, you migth want to consider using <a href=\"https://en.wikipedia.org/wiki/Callback_(computer_programming)\" rel=\"nofollow noreferrer\">Callbacks</a>.</p>\n<hr />\n<h2>Questions</h2>\n<blockquote>\n<ol>\n<li>Collection vs Elements for the parameter of extractWeeks: does this again relate to “use the broadest type of collection possible”?</li>\n</ol>\n</blockquote>\n<p>To be honest, it wasn't a conscious choice since I let the IDE perform <em>Extract Method</em>, but generally, yes. <code>Elements</code> is a type of <code>Collection<Element></code>, but none of it's features are needed in <code>extractWeeks</code> so you might as well use <code>Collection<Element></code> to make the method more broadly applicable (even though you might not need it).</p>\n<blockquote>\n<ol start=\"2\">\n<li>static member functions vs non-static: I’m definitely going to look into this more myself but I couldn’t help getting confused over why certain functions (like extractWeeks) were static, but others (like weeklyResultUrl) are not static. In both cases, the object doesn’t directly call it, so wouldn’t it make sense to declare all such functions as static?</li>\n</ol>\n</blockquote>\n<p>Methods can't be <code>static</code> if they use members of their class. Since <code>weeklyResultUrl</code> uses the fields <code>urlPrefix</code> and <code>urlSuffix</code>, it cannot be <code>static</code>. I could declare all methods none-<code>static</code>, but declaring a method <code>static</code> has a few advantages to the reader and to the programmer:</p>\n<p>When calling a <code>static</code> method, you can be sure that it does not modify the instance state. Likewise, when inside a <code>static</code> method, you are not able to modify the instance state. Both of these decrease the mental load when reading and writing code.</p>\n<p>Also, since a <code>static</code> clearly doesn't require an instance to function, you are able to call a <code>public static</code> method without an instance from outside the class.</p>\n<blockquote>\n<ol start=\"3\">\n<li>The noEmptyElseThrow strictly isn’t an IOException, is it? Can I throw other exceptions instead (IllegalArgumentExcpetion or NullPointerException, and I’m not sure which is the more suited of the two?), and if so would the caller have to rethrow them?</li>\n</ol>\n</blockquote>\n<p>Yes, technically you're right. I don't think either of the Exceptions you suggested are quite what you'd want. I would only ever throw <code>IllegalArgumentExcpetion</code> if you pass an invalid argument to a method. I would assume that you could extract the numbers from <code>&rankRange=0-100</code> and add them as an argument to the method. Then IAE might be more applicable.</p>\n<p>There's something to be said about throwing a checked exception, which might be some further reading points as well.</p>\n<p>But NPE definitely doesn't fit. Only ever throw an NPE if something is <code>null</code> when it shouldn't be.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T02:31:15.153",
"Id": "479159",
"Score": "1",
"body": "I realize this might be a little advanced, so if you have any further questions, please let me know and I will try to answer them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T23:24:02.837",
"Id": "479293",
"Score": "0",
"body": "First of all, thanks a lot for the review, there's a LOT of valuable insights in your comment! I'm still going through a bit of them, so I'll probably ask more questions over the course of the coming day but I've got a few questions for the moment, see my post below."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T23:43:13.897",
"Id": "479298",
"Score": "0",
"body": "You're welcome! See my edited answer for answers to your questions. Additionally, I would recommend checking out Robert C. Martins excellent *Clean Code: A Handbook of Agile Software Craftsmanship*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T19:32:48.103",
"Id": "479391",
"Score": "0",
"body": "I moved my comments to my questions so everyone referring to this will have an easier time. I also added a bunch of questions to clarify a bit about cleaner exception handling - it'd be great if you could get to them whenever you have time! I think for the most part I have a much better idea of how to strengthen my code, so thanks again and I hope I'm not asking too much of you by asking too many questions :D"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T02:31:09.453",
"Id": "244087",
"ParentId": "244074",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "244087",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T21:46:55.527",
"Id": "244074",
"Score": "8",
"Tags": [
"java",
"web-scraping"
],
"Title": "Webscraping tennis data"
}
|
244074
|
<p>Date Detection:</p>
<p>Write a regular expression that can detect dates in the DD/MM/YYYY format.</p>
<p>Assume that the days range from 01 to 31, the months range from 01
to 12, and the years range from 1000 to 2999. Note that if the day or month
is a single digit, it’ll have a leading zero.</p>
<p>Then store these strings into variables named month, day, and
year, and write additional code that can detect if it is a valid date.</p>
<p>April,
June, September, and November have 30 days, February has 28 days, and
the rest of the months have 31 days. February has 29 days in leap years.
Leap years are every year evenly divisible by 4, except for years evenly divisible by 100, unless the year is also evenly divisible by 400. Note how this calculation makes it impossible to make a reasonably sized regular expression
that can detect a valid date.</p>
<pre class="lang-py prettyprint-override"><code>import re
def check_date(day, month, year):
# April, June, September, November = 30 days/ February = 28 days, unless leapyear so 29/ rest has 31 days
month_dict = {4: 30, 6: 30, 9: 30, 11: 30, 2: 28}
day_bound = month_dict.get(month, 31)
# month is february
if day_bound == 28:
# checks if the year is a leap year
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
day_bound = 29
else:
day_bound = 29
# if the day is in the range of possible days
if day <= day_bound:
return True
return False
# DD/MM/YYYY
string = "31/02/2020"
date_regex = re.compile(r"([0-2]\d|3[01])/(0\d|1[0-2])/([12]\d{3})")
match = date_regex.search(string)
valid = False
if match:
day = int(match.group(1))
month = int(match.group(2))
year = int(match.group(3))
valid = check_date(day, month, year)
if valid:
print(f'Day: {day}, Month: {month}, Year: {year}')
else:
print('Invalid Date!')
</code></pre>
|
[] |
[
{
"body": "<h1>Docstrings / Type hints</h1>\n<p>These allow you to describe how your code works in a pythonic manner. Docstrings allow IDE's and other documentation tools to see what your function/class does. Type hints allow you to show what types of parameters are accepted, and what types of values are returned.</p>\n<h1><code>check_date</code></h1>\n<p>Instead of calculating a leap year yourself, you can use <code>calendar.isleap</code> from the <a href=\"https://docs.python.org/3/library/calendar.html\" rel=\"nofollow noreferrer\">calendar</a> module.</p>\n<h1>Return comparisons, not raw booleans</h1>\n<p>Instead of</p>\n<pre><code>if day <= day_bound:\n return True\nreturn False\n</code></pre>\n<p>do this</p>\n<pre><code>return day <= day_bound\n</code></pre>\n<p>Does the exact same thing, but looks a lot nicer.</p>\n<h1>Split code into functions</h1>\n<p>You've done a good job splitting your code into functions, but I think you could use one more. Instead of parsing the date in the "main" code, put that code in another function, and pass it the date string.</p>\n<pre><code>def get_date_values(...) -> ...:\n ...\n</code></pre>\n<p>With all these changes, your final code would look something like this:</p>\n<pre><code>import re\nimport calendar\nfrom typing import Tuple, Union\n\ndef check_date(day: int, month: int, year: int) -> bool:\n """\n Returns a bool based on if the date passed is a valid date.\n\n :param int day: Day.\n :param int month: Month.\n :param int year: Year.\n\n :return: True if a valid date, False otherwise.\n """\n # April, June, September, November = 30 days/ February = 28 days, unless leapyear so 29/ rest has 31 days\n month_dict = {4: 30, 6: 30, 9: 30, 11: 30, 2: 28}\n day_bound = month_dict.get(month, 31)\n\n if day_bound == 28:\n if calendar.isleap(year):\n day_bound = 29\n\n return day <= day_bound\n\n\ndef get_date_values(date: str) -> Union[Tuple[int, int, int], None]:\n """\n Returns a tuple containing the day, month, and year of the passed date.\n\n :param str date: Date to parse and retrieve values.\n\n :return: Either a Tuple, or for an invalid date, None.\n """\n date_regex = re.compile(r"([0-2]\\d|3[01])/(0\\d|1[0-2])/([12]\\d{3})")\n match = date_regex.search(date)\n if match:\n return (int(match.group(1)), int(match.group(2)), int(match.group(3)))\n return None\n\n\nif __name__ == "__main__":\n date = "31/02/2020" #DD/MM/YYYY\n if check_date(*get_date_values(date)):\n print('Valid Date!')\n else:\n print('Invalid Date!')\n</code></pre>\n<p>I'll explain a bit more since I made some changes I haven't mentioned already.</p>\n<h1>Unpacking</h1>\n<pre><code>if check_date(*get_date_values(date)):\n</code></pre>\n<p>This line unpacks each item from the tuple returned by <code>get_date_values</code> and passes them to the function. Since the tuple has three values, and <code>check_date</code> accepts three parameters, the <code>*</code> unpacks the tuple and passes each value to the function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T12:44:54.960",
"Id": "479202",
"Score": "0",
"body": "unpacking needs an existing tuple. this is an error not present in the OPs code"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T00:24:39.120",
"Id": "244081",
"ParentId": "244077",
"Score": "2"
}
},
{
"body": "<p>Just in case there might be a restriction on using standard date functions, the leap year logic can be reduced to one conditional block:</p>\n<pre><code>if day_bound == 28 and ((year % 4 == 0 and year % 100 != 0)\n or year % 400 == 0):\n day_bound = 29\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T06:26:54.913",
"Id": "479169",
"Score": "1",
"body": "Or even better, separate this in its own function"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T00:33:58.190",
"Id": "244082",
"ParentId": "244077",
"Score": "2"
}
},
{
"body": "<p>There are some problems in your code structure and testability.</p>\n<h1>Provide a testable function that covers the given task completely</h1>\n<p>If you want to test your code against the requirements you will need a function</p>\n<pre><code>def is_valid_date_string(s):\n #[...]\n</code></pre>\n<p>that you can use in testing, e. g.</p>\n<pre><code>assert is_valid_date_string("31/02/2020") == True\n</code></pre>\n<p>that function shall not contain I/O (other than logging).\nSo we restructure your main code like</p>\n<pre><code>def is_valid_date_string(string):\n # DD/MM/YYYY\n date_regex = re.compile(r"([0-2]\\d|3[01])/(0\\d|1[0-2])/([12]\\d{3})")\n match = date_regex.search(string)\n if match:\n day = int(match.group(1))\n month = int(match.group(2))\n year = int(match.group(3))\n return check_date(day, month, year)\n return False\n\nif __name__ == '__main__':\n string = "31/02/2020"\n if is_valid_date_string(string):\n print(string)\n else:\n print('Invalid Date!')\n</code></pre>\n<p>Now we can introduce more tests</p>\n<pre><code>if __name__ == '__main__':\n assert True == is_valid_date_string("01/01/2020")\n\n # false\n assert False == is_valid_date_string("00/01/2020")\n assert False == is_valid_date_string("01/00/2020")\n assert False == is_valid_date_string("01/01/0000")\n assert False == is_valid_date_string("31/04/2020")\n assert False == is_valid_date_string("30/02/2020")\n assert False == is_valid_date_string("31/02/2020")\n\n # leap\n assert False == is_valid_date_string("29/02/2001")\n assert True == is_valid_date_string("29/02/2004")\n assert False == is_valid_date_string("29/02/2100")\n assert True == is_valid_date_string("29/02/2400")\n\n # format\n assert False == is_valid_date_string("asdf")\n assert False == is_valid_date_string("1/2/2020")\n</code></pre>\n<p>We see two cases failing. Which part is responsible? Regex or check_date?\ncheck_date does not check any date but the upper limit of days only. Hence either the name is wrong or the implementation.\ncheck_date does silently assume its parameters are somewhat correct which may! not be enforced by the usage. This real danger!\nWe also cannont test the function properly and we definitely shall not expose it. A user might get date as integer triple from somewhere and use your function to verify like</p>\n<pre><code>check_date(5, 90, 999)\n</code></pre>\n<p>We also cannot test it as we do not know the contracts</p>\n<pre><code>assert False == check_date(5, 90, 999)\nassert False == check_date(35, 9, 999)\n</code></pre>\n<p>One fails, the other test is successful.</p>\n<p>We shall incorporate the code into our is_valid_date_string function directly (or as private function).</p>\n<p>Bottom line - do not mess with date/time manually, use a library</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T12:42:38.603",
"Id": "244105",
"ParentId": "244077",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244081",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T22:46:33.480",
"Id": "244077",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"regex"
],
"Title": "Python - Making A Valid Date Checker - using Regular Expressions"
}
|
244077
|
<p>I've made a simple terminal-based analog clock for Linux in AEC. Here we go:</p>
<pre><code>Syntax GAS
;This is yet another example of how to target Linux using GNU Assembler.
AsmStart ;What follows is code produced by GCC 9.3.0 on Linux, I don't understand much of it either, and it's not important.
.file "analogClock.c"
.text
.comm result,4,4
.comm i,4,4
.comm x,4,4
.comm y,4,4
.comm currentSign,4,4
.comm centerX,4,4
.comm centerY,4,4
.comm distance,4,4
.comm clockRadius,4,4
.comm output,7360,32
.comm hour,4,4
.comm minute,4,4
.comm second,4,4
.comm angle,4,4
.comm endOfTheHandX,4,4
.comm endOfTheHandY,4,4
.comm coefficientOfTheDirection,4,4
.comm windowWidth,4,4
.comm windowHeight,4,4
.comm lowerBoundX,4,4
.comm upperBoundX,4,4
.comm lowerBoundY,4,4
.comm upperBoundY,4,4
.comm isXWithinBounds,4,4
.comm isYWithinBounds,4,4
.comm expectedY,4,4
.comm expectedX,4,4
.comm j,4,4
.comm ASCIIofSpaceAsFloat32,4,4
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
leal 4(%esp), %ecx
.cfi_def_cfa 1, 0
andl $-16, %esp
pushl -4(%ecx)
pushl %ebp
.cfi_escape 0x10,0x5,0x2,0x75,0
movl %esp, %ebp
pushl %ecx
.cfi_escape 0xf,0x3,0x75,0x7c,0x6
subl $36, %esp
subl $12, %esp
leal -20(%ebp), %eax
pushl %eax
call time
addl $16, %esp
subl $12, %esp
leal -20(%ebp), %eax
pushl %eax
call localtime
addl $16, %esp
movl %eax, -16(%ebp)
movl -16(%ebp), %eax
movl 8(%eax), %eax
movl %eax, -28(%ebp)
fildl -28(%ebp)
fstps hour
movl -16(%ebp), %eax
movl 4(%eax), %eax
movl %eax, -28(%ebp)
fildl -28(%ebp)
fstps minute
movl -16(%ebp), %eax
movl (%eax), %eax
movl %eax, -28(%ebp)
fildl -28(%ebp)
fstps second
#APP
AsmEnd ;And now finally follows a program written in AEC.
windowWidth:=80
windowHeight:=23
ASCIIofSpace<=" \0\0\0" ;As integer. We know we are dealing with a...
ASCIIofNewLine<="\n\0\0\0" ;32-bit low-endian machine.
ASCIIofStar<="*\0\0\0"
i:=0
While i<windowWidth*windowHeight ;First, fill the window with spaces and newlines.
If mod(i,windowWidth)=windowWidth-1
AsmStart
.intel_syntax noprefix
fild dword ptr ASCIIofNewLine
fstp dword ptr currentSign
.att_syntax
AsmEnd
Else
AsmStart
.intel_syntax noprefix
fild dword ptr ASCIIofSpace
fstp dword ptr currentSign
fld dword ptr currentSign
fstp dword ptr ASCIIofSpaceAsFloat32
.att_syntax
AsmEnd
EndIf
output[i]:=currentSign
i:=i+1
EndWhile
centerX:=windowWidth/2-mod(windowWidth/2,1)
centerY:=windowHeight/2-mod(windowHeight/2,1)
clockRadius:=(centerX<centerY)?(centerX):(centerY)-1
i:=0
While i<windowWidth*windowHeight ;Next, draw the circle which represents the clock.
y:=i/windowWidth-mod(i/windowWidth,1) ;When I didn't put "floor" into my programming language...
x:=mod(i,windowWidth)
distance:=sqrt((x-centerX)*(x-centerX)+(y-centerY)*(y-centerY)) ;Pythagorean Theorem.
If abs(distance-clockRadius)<3/4
AsmStart
.intel_syntax noprefix
fild dword ptr ASCIIofStar
fstp dword ptr currentSign
.att_syntax
AsmEnd
output[i]:=currentSign
EndIf
i:=i+1
EndWhile
AsmStart
.intel_syntax noprefix
jmp ASCIIofDigits$
ASCIIofDigits:
.macro writeDigits startingWith=0
.byte '0'+\startingWith,0,0,0 #".byte" is to GNU Assembler about the same as "db" is to FlatAssembler.
.if \startingWith < 9
writeDigits \startingWith+1
.endif
.endm
writeDigits #The goal is to make Assembler output the ASCII of "0\0\0\01\0\0\02\0\0\0...9\0\0\0" inside the executable (if the instruction pointer points to it, it will, of course, be an invalid instruction).
ASCIIofDigits$:
.att_syntax
AsmEnd
;Label of "12"...
AsmStart
.intel_syntax noprefix
fild dword ptr [ASCIIofDigits+1*4] #The ASCII of '1'.
fstp dword ptr currentSign
.att_syntax
AsmEnd
output[(centerY-clockRadius+1)*windowWidth+centerX]:=currentSign
AsmStart
.intel_syntax noprefix
fild dword ptr [ASCIIofDigits+2*4] #The ASCII of '2'.
fstp dword ptr currentSign
.att_syntax
AsmEnd
output[(centerY-clockRadius+1)*windowWidth+centerX+1]:=currentSign
AsmStart
.intel_syntax noprefix
fild dword ptr [ASCIIofDigits+6*4] #The ASCII of '6'.
fstp dword ptr currentSign
.att_syntax
AsmEnd
output[(centerY+clockRadius-1)*windowWidth+centerX]:=currentSign
AsmStart
.intel_syntax noprefix
fild dword ptr [ASCIIofDigits+3*4] #The ASCII of '3'.
fstp dword ptr currentSign
.att_syntax
AsmEnd
output[centerY*windowWidth+centerX+clockRadius-1]:=currentSign
AsmStart
.intel_syntax noprefix
fild dword ptr [ASCIIofDigits+9*4] #The ASCII of '9'.
fstp dword ptr currentSign
.att_syntax
AsmEnd
output[centerY*windowWidth+centerX-clockRadius+1]:=currentSign
AsmStart
.intel_syntax noprefix
fild dword ptr [ASCIIofDigits+1*4] #The ASCII of '1'.
fstp dword ptr currentSign
.att_syntax
AsmEnd
y:=centerY-(clockRadius-1)*cos(360/12)
y:=y-mod(y,1)
output[y*windowWidth+centerX+sin(360/12)*(clockRadius-1)]:=currentSign
AsmStart
.intel_syntax noprefix
fild dword ptr [ASCIIofDigits+2*4] #The ASCII of '2'.
fstp dword ptr currentSign
.att_syntax
AsmEnd
y:=centerY-(clockRadius-1.5)*cos(2*360/12)
y:=y-mod(y,1)
output[y*windowWidth+centerX+sin(2*360/12)*(clockRadius-1.5)]:=currentSign
AsmStart
.intel_syntax noprefix
fild dword ptr [ASCIIofDigits+4*4] #The ASCII of '4'.
fstp dword ptr currentSign
.att_syntax
AsmEnd
y:=centerY-(clockRadius-1)*cos(4*360/12)
y:=y-mod(y,1)
output[y*windowWidth+centerX+sin(4*360/12)*(clockRadius-1)]:=currentSign
AsmStart
.intel_syntax noprefix
fild dword ptr [ASCIIofDigits+5*4] #The ASCII of '5'.
fstp dword ptr currentSign
.att_syntax
AsmEnd
y:=centerY-(clockRadius-1)*cos(5*360/12)
y:=y-mod(y,1)
output[y*windowWidth+centerX+sin(5*360/12)*(clockRadius-1)]:=currentSign
AsmStart
.intel_syntax noprefix
fild dword ptr [ASCIIofDigits+7*4] #The ASCII of '7'.
fstp dword ptr currentSign
.att_syntax
AsmEnd
y:=centerY-(clockRadius-1)*cos(7*360/12)
y:=y-mod(y,1)
output[y*windowWidth+centerX+sin(7*360/12)*(clockRadius-1)]:=currentSign
AsmStart
.intel_syntax noprefix
fild dword ptr [ASCIIofDigits+8*4] #The ASCII of '8'.
fstp dword ptr currentSign
.att_syntax
AsmEnd
y:=centerY-(clockRadius-1)*cos(8*360/12)
y:=y-mod(y,1)
output[y*windowWidth+centerX+sin(8*360/12)*(clockRadius-1)]:=currentSign
;Label "10"...
AsmStart
.intel_syntax noprefix
fild dword ptr [ASCIIofDigits+1*4] #The ASCII of '1'.
fstp dword ptr currentSign
.att_syntax
AsmEnd
y:=centerY-(clockRadius-1.5)*cos(10*360/12)
y:=y-mod(y,1)
output[y*windowWidth+centerX+sin(10*360/12)*(clockRadius-1.5)]:=currentSign
AsmStart
.intel_syntax noprefix
fild dword ptr [ASCIIofDigits+0*4] #The ASCII of '0'.
fstp dword ptr currentSign
.att_syntax
AsmEnd
y:=centerY-(clockRadius-1.5)*cos(10*360/12)
y:=y-mod(y,1)
output[y*windowWidth+centerX+sin(10*360/12)*(clockRadius-1.5)+1]:=currentSign
;Label "11"...
AsmStart
.intel_syntax noprefix
fild dword ptr [ASCIIofDigits+1*4] #The ASCII of '1'.
fstp dword ptr currentSign
.att_syntax
AsmEnd
y:=centerY-(clockRadius-1.5)*cos(11*360/12)
y:=y-mod(y,1)
output[y*windowWidth+centerX+sin(11*360/12)*(clockRadius-1.5)]:=currentSign
AsmStart
.intel_syntax noprefix
fild dword ptr [ASCIIofDigits+1*4] #The ASCII of '1'.
fstp dword ptr currentSign
.att_syntax
AsmEnd
y:=centerY-(clockRadius-1.5)*cos(11*360/12)
y:=y-mod(y,1)
output[y*windowWidth+centerX+sin(11*360/12)*(clockRadius-1.5)+1] := currentSign
j:=0
While j<3
If j=0
angle:=(mod(hour+minute/60,12))*(360/12)
ElseIf j=1
angle:=minute*(360/60)
Else
angle:=second*(360/60)
EndIf
endOfTheHandX:=centerX+sin(angle)*clockRadius/(j=0?2:j=1?3/2:4/3) ;Hour hand will be the shortest, and the hand that shows the seconds will be the longest.
endOfTheHandY:=centerY-cos(angle)*clockRadius/(j=0?2:j=1?3/2:4/3)
coefficientOfTheDirection:=(endOfTheHandY-centerY)/(endOfTheHandX-centerX)
debugString <= "Drawing line between (%d,%d) and (%d,%d).\n\0"
AsmStart
.intel_syntax noprefix
.ifdef DEBUG #Conditional assembly, this will only be assembled if you tell GNU Assembler (by modifying the file or using command line) that you want to enable debugging.
fld dword ptr endOfTheHandY
fistp dword ptr result
push dword ptr result #This (pushing a "dword" onto the system stack) breaks the compatibility with 64-bit Linux (but you can still enable it by disabling debugging)!
fld dword ptr endOfTheHandX
fistp dword ptr result
push dword ptr result
fld dword ptr centerY
fistp dword ptr result
push dword ptr result
fld dword ptr centerX
fistp dword ptr result
push dword ptr result
lea ebx,debugString
push ebx
call printf
.endif #End of the conditional assembly.
.att_syntax
AsmEnd
i:=0
While i<windowWidth*windowHeight
lowerBoundX:=(endOfTheHandX<centerX)?(endOfTheHandX):(centerX)
upperBoundX:=(endOfTheHandX>centerX)?(endOfTheHandX):(centerX)
lowerBoundY:=(endOfTheHandY<centerY)?(endOfTheHandY):(centerY)
upperBoundY:=(endOfTheHandY>centerY)?(endOfTheHandY):(centerY)
y:=i/windowWidth-mod(i/windowWidth,1)
x:=mod(i,windowWidth)
isXWithinBounds:=(x>lowerBoundX | x=lowerBoundX) & (x<upperBoundX | x=upperBoundX) ;Damn... Now I understand why almost every programming language supports the "<=" and ">=" operators, no matter how much harder they make the language to tokenize.
isYWithinBounds:=(y>lowerBoundY | y=lowerBoundY) & (y<upperBoundY | y=upperBoundY)
If isXWithinBounds=1 & isYWithinBounds=1
expectedY:=(x-centerX)*coefficientOfTheDirection+centerY
expectedX:=(y-centerY)*(1/coefficientOfTheDirection)+centerX
debugString1 <= "The point (%d,%d) is within bounds, expectedY is %d and expectedX is %d.\n\0"
AsmStart
.intel_syntax noprefix
.ifdef DEBUG
fld dword ptr expectedX
fistp dword ptr result
push dword ptr result
fld dword ptr expectedY
fistp dword ptr result
push dword ptr result
fld dword ptr y
fistp dword ptr result
push dword ptr result
fld dword ptr x
fistp dword ptr result
push dword ptr result
lea ebx,debugString1
push ebx
call printf
.endif
.att_syntax
AsmEnd
ASCIIofLetterH<="h\0\0\0"
ASCIIofLetterM<="m\0\0\0"
ASCIIofLetterS<="s\0\0\0"
If j=0
AsmStart
.intel_syntax noprefix
fild dword ptr ASCIIofLetterH
fstp dword ptr currentSign
.att_syntax
AsmEnd
ElseIf j=1
AsmStart
.intel_syntax noprefix
fild dword ptr ASCIIofLetterM
fstp dword ptr currentSign
.att_syntax
AsmEnd
Else
AsmStart
.intel_syntax noprefix
fild dword ptr ASCIIofLetterS
fstp dword ptr currentSign
.att_syntax
AsmEnd
EndIf
If (upperBoundX=lowerBoundX | upperBoundY=lowerBoundY) & output[i]=ASCIIofSpaceAsFloat32
output[i]:=currentSign
EndIf
If (abs(expectedY-y)<3/4 | abs(expectedX-x)<3/4) & output[i]=ASCIIofSpaceAsFloat32
output[i]:=currentSign
EndIf
EndIf
i:=i+1
EndWhile
j:=j+1
EndWhile
;Draw some ornament...
ASCIIofLetterX<="x\0\0\0"
AsmStart
.intel_syntax noprefix
fild dword ptr ASCIIofLetterX
fstp dword ptr currentSign
.att_syntax
AsmEnd
i:=0
While i<windowWidth*windowHeight
y:=i/windowWidth-mod(i/windowWidth,1)
x:=mod(i,windowWidth)
If abs(windowHeight-2*ln(1+abs((x-centerX)/2))-y)<1-abs(x-centerX)/(centerX*95/112) & x>1/2*centerX & x<3/2*centerX & output[i]=ASCIIofSpaceAsFloat32 ;The logarithmic curve looks somewhat like a lemma of a flower.
output[i]:=currentSign
EndIf
i:=i+1
EndWhile
AsmStart ;And here goes how, according to GCC 9.3.0, you print the table and finish an Assembly program on 32-bit Linux (I don't understand that either, and it's not important).
#NO_APP
movl $0, -12(%ebp)
jmp .L2
.L3:
movl -12(%ebp), %eax
movss output(,%eax,4), %xmm0
cvttss2sil %xmm0, %eax
subl $12, %esp
pushl %eax
call putchar
addl $16, %esp
addl $1, -12(%ebp)
.L2:
cmpl $1839, -12(%ebp)
jle .L3
movl $0, %eax
movl -4(%ebp), %ecx
.cfi_def_cfa 1, 0
leave
.cfi_restore 5
leal -4(%ecx), %esp
.cfi_def_cfa 4, 4
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (GNU) 9.3.0"
.section .note.GNU-stack,"",@progbits
AsmEnd
</code></pre>
<p>The executable is available <a href="https://github.com/FlatAssembler/ArithmeticExpressionCompiler/blob/master/ArithmeticExpressionCompiler.zip?raw=true" rel="nofollow noreferrer">here</a>, it's called <code>analogClock.elf</code>. So, what do you think about it?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T23:58:17.423",
"Id": "479155",
"Score": "2",
"body": "If this is code that was created by gcc, it doesn’t seem to be on topic here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T08:09:54.530",
"Id": "479179",
"Score": "0",
"body": "@Edward what if part of it is generated by GCC? Drawing the clock is done in AEC."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T11:15:22.670",
"Id": "479190",
"Score": "2",
"body": "The issues are 1) that the code you post must be created by you and 2) \"AEC\" is unknown. If it's something you wrote, at least post a link. Right now the code is off topic here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T11:36:38.270",
"Id": "479193",
"Score": "1",
"body": "@Edward Yes, AEC is something I wrote, it's available here: https://flatassembler.github.io/compiler.html . And most of the code I posted here is written by me, I've just used GCC for things I don't happen to know how to do in Assembly, and they can't be done in AEC either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T11:42:14.420",
"Id": "479194",
"Score": "5",
"body": "Because nobody other than you knows the AEC syntax (and it doesn't appear to be documented) code written in it is going to be unreviewable. What you might find more fruitful would be to post the code for your compiler and get a review of that instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T14:58:28.650",
"Id": "479223",
"Score": "3",
"body": "From the comments this seems on-topic to me. You've written most of it, so no authorship problems. However as Edward has said I believe this will go unanswered."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-17T22:52:54.730",
"Id": "244078",
"Score": "1",
"Tags": [
"console",
"linux",
"assembly"
],
"Title": "Analog Clock in AEC"
}
|
244078
|
<p>I am using dropzone and XLSX to load excel documents and then convert them into json.</p>
<p>The goal is to upload as many documents as possible and it will create an object with a key of the file name and then the value as the data. The problem I notice is that reader.onload is not available immediately after calling readAsArrayBuffer(). My solution was to use setTimeout. I am wondering if there is another method that I might be able to use instead of setTimeout as though it works perfectly, I feel it is more of a hack and maybe something exists that I have not learned or just don't know well enough. Here is my code inside the react element.</p>
<pre><code>const [showLoader, setShowLoader] = useState(false)
const [filePaths, setFilesPaths] = useState([]);
const [parsedData, setParsedData] = useState({})
const [validationErrors, setValidationErrors] = useState([])
const [fileTypeError, setFileTypeError] = useState("")
const [uploadError, setUploadError] = useState("")
const onDrop = useCallback((acceptedFiles) => {
setShowLoader(true)
let data = {...parsedData};
let files = [...filePaths];
let errors = []
if (validationErrors.length > 0) {
setValidationErrors([])
}
if (fileTypeError) {
setFileTypeError("")
}
if (uploadError) {
setUploadError("")
}
acceptedFiles.forEach((file) => {
const reader = new FileReader()
reader.onabort = () => console.log('file reading was aborted')
reader.onerror = () => console.log('file reading has failed')
reader.onload = () => {
const isExcelFile = file.type === XLSX_MIME_TYPE
if (!isExcelFile) {
setFileTypeError("One or more of the files added were removed because they were not excel files");
return;
}
if (filePaths.includes(file.path)) {
setUploadError("One or more of the files wasn't added because a file of that name already exists");
return
}
let bstr = reader.result;
const wb = XLSX.read(bstr, { type: 'array', bookVBA : true, cellDates: true, cellStyles: true});
/* Get first worksheet */
const wsname = wb.SheetNames[0];
const ws = wb.Sheets[wsname];
/* Convert array of arrays */
const data = XLSX.utils.sheet_to_json(ws);
const validateData = data.map(dataItem => {
const validTypes = ["Major", "Patch", "Maint", "Dependency", "Infrastructure"]
if (!dataItem["Application Description"] || !validTypes.includes(dataItem["Event Type"]) || !dataItem["Event Type"]) {
return "error"
} else {
return "valid"
}
})
if (validateData.includes("error")) {
reader.errorMessage = "error";
} else {
reader.data = [...data].map((item, index) => {
return {
id: index,
...item
}
})
}
}
reader.readAsArrayBuffer(file)
setTimeout(() => {
if (reader.errorMessage) {
errors.push(`${file.path} contains errors, please make sure it was filled out correctly`)
} else {
files.push(file.path)
data[file.path] = reader.data
}
}, 250)
})
setTimeout(() => {
if (errors.length > 0) {
setValidationErrors(errors)
}
setFilesPaths(files)
setParsedData(data)
setShowLoader(false)
}, 250)
}, [
validationErrors,
fileTypeError,
uploadError,
parsedData,
filePaths
])
</code></pre>
<p>So in short the code isn't broken. I'm just curious if I am going about achieving the result that I want correctly. If not doing correctly or if a better method I would love to know and understand how that works. I appreciate everyones help.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T01:23:58.033",
"Id": "244084",
"Score": "1",
"Tags": [
"javascript",
"excel",
"json",
"react.js"
],
"Title": "Excel to Json getting file data into state in React JS"
}
|
244084
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.