body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I need to extract all member accesses to expression parameter (and make sure, that they are not nested). For instance, for expression: <code>a => a.A + a.B</code> I need to receive list <code>{"A", "B"}</code>. For expression <code>a => a.B.C</code> exception should be thrown, as we have nested member access.</p>
<p>I wrote the following class, but I'm not too satisfied with it. Mainly because I don't like pattern "Call, then access member for result", because it decreases code maintainability and allows introducing hard to find bugs (ie. what if I accidentally access results later without calling etc.)</p>
<p>I'm wondering, if this class might be implemented in such way, so that I could call:</p>
<pre><code>List<string> members = new MemberExpressionVisitor<A, bool>().GetMembers(a => a.A + a.B);
</code></pre>
<p>My current solution follows:</p>
<pre><code>private class MemberExpressionVisitor<T1, T2> : ExpressionVisitor
{
private Expression<Func<T1, T2>> originalExpression = null;
private HashSet<string> accessedMembers = null;
public override Expression Visit(Expression node)
{
if (originalExpression == null)
{
if (node is Expression<Func<T1, T2>> startExpression)
{
originalExpression = startExpression;
accessedMembers = new HashSet<string>();
var result = base.Visit(node);
originalExpression = null;
return result;
}
else
{
throw new InvalidOperationException($"Passed expression must be of type Expression<Func<{typeof(T1).Name},{typeof(T2).Name}>>!");
}
}
else
{
return base.Visit(node);
}
}
protected override Expression VisitMember(MemberExpression node)
{
if (node.Expression is MemberExpression)
throw new InvalidOperationException("Nested member accesses are not allowed!");
if (node.Expression is ParameterExpression parameterExpression)
{
if (parameterExpression.Name == originalExpression.Parameters[0].Name)
accessedMembers.Add(node.Member.Name);
}
return base.VisitMember(node);
}
public List<string> GetAccessedMembers() => accessedMembers.ToList();
}
</code></pre>
<p>Example call:</p>
<pre><code>public class B
{
public int P => 5;
}
public class A
{
public B B => new B();
public int C => 8;
}
static void Main(string[] args)
{
Expression<Func<A, bool>> exp = a => a.B != null && a.C ==8;
MemberExpressionVisitor<A, bool> visitor = new MemberExpressionVisitor<A, bool>();
visitor.Visit(exp);
Console.WriteLine(String.Join(", ", visitor.GetAccessedMembers()));
Console.ReadKey();
}
</code></pre>
<hr />
<p><strong>Edit:</strong> Safer, but with clumsy "processing" field.</p>
<pre><code>private class MemberExpressionExtractor : ExpressionVisitor
{
private bool processing = false;
private string parameterName;
private readonly HashSet<string> accessedMembers = new HashSet<string>();
public List<string> ExtractMembers<T1, T2>(Expression<Func<T1, T2>> expression)
{
try
{
processing = true;
parameterName = expression.Parameters[0].Name;
accessedMembers.Clear();
Visit(expression);
}
finally
{
processing = false;
}
return accessedMembers.ToList();
}
public override Expression Visit(Expression node)
{
if (!processing)
throw new InvalidOperationException("Use ExtractMembers<T1, T2> instead.");
return base.Visit(node);
}
protected override Expression VisitMember(MemberExpression node)
{
if (node.Expression is MemberExpression)
throw new InvalidOperationException("Nested member accesses are not allowed!");
if (node.Expression is ParameterExpression parameterExpression)
{
if (parameterExpression.Name == parameterName)
accessedMembers.Add(node.Member.Name);
}
return base.VisitMember(node);
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T22:00:03.517",
"Id": "491180",
"Score": "0",
"body": "Do you really need to only collect member accesses off the original lambda's first parameter?"
}
] |
[
{
"body": "<p>What if you nested the <code>MemberExpressionVisitor</code> class inside another class? Since I like extension methods, create a static class that contains an extension method on <code>Expression<Func<T,TRes>></code> that creates the visitor, runs it and returns the result:</p>\n<pre><code>static class LambdaExt {\n public static List<string> GetAccessedMemberNames<T, TRes>(this Expression<Func<T, TRes>> startExpr) {\n var v = new MemberExpressionVisitor<T, TRes>();\n v.Visit(startExpr);\n\n return v.GetAccessedMembers();\n }\n\n // put MemberExpressionVisitor definition here\n}\n</code></pre>\n<p>Now you can use it like:</p>\n<pre><code>Console.WriteLine(String.Join(", ", exp.GetAccessedMemberNames()));\n</code></pre>\n<p>Alternatively, you can add a constructor to <code>MemberExpressionVisitor</code>:</p>\n<pre><code>public MemberExpressionVisitor(Expression<Func<T1, T2>> startExpression) {\n originalExpression = startExpression;\n Visit(startExpression);\n}\n</code></pre>\n<p>remove the <code>Visit</code> override entirely, and simplify the extension method to:</p>\n<pre><code>public static List<string> GetAccessedMemberNames<T, TRes>(this Expression<Func<T, TRes>> startExpr) =>\n new MemberExpressionVisitor<T,TRes>(startExpr).GetAccessedMembers();\n</code></pre>\n<p>This has the compiler enforce type safety, assuming you know your lambda expression variables types properly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T08:01:18.843",
"Id": "520874",
"Score": "0",
"body": "Once you're hiding the `MemberExpressionVisitor`, is there any gain in the type parameters of `MemberExpressionVisitor`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T20:38:06.327",
"Id": "520939",
"Score": "1",
"body": "@ZevSpitz I think you should be able to replace `Expression<Func<T1,T2>>` with `LambdaExpression` and it should all work."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T22:09:05.180",
"Id": "250342",
"ParentId": "244366",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T07:54:46.637",
"Id": "244366",
"Score": "4",
"Tags": [
"c#",
"comparative-review"
],
"Title": "Extracting member-accesses from an expression in C#"
}
|
244366
|
<p>I'm new to Javascript and Web Dev in general, so they'll likely be some conventions that I'm not aware of.</p>
<p>I'm at an odds of whether to use Javascript's functional features more. In my opinion it's easier to read Java-like imperative code than the concise functional features that I see JS programmers use a lot, however I'm open to writing in a more functional style if most other programmers prefer it.</p>
<pre><code>"use strict"
const array = [];
const MIN_ARRAY_LENGTH = 20;
const MAX_ARRAY_LENGTH = 100;
const global = {
length : -1,
speed : 10,
currentAlgorithm: undefined
}
// Maps the algorithm selection buttons innerHTML onto the actual algorithms
const pickAlgorithm = new Map([
["Insertion Sort", insertionSort],
["Selection Sort", selectionSort],
["Quick Sort", quickSort],
["Heap Sort", heapSort]
]);
generateNewStepArray();
addEventListeners();
async function run() {
if (isSorted())
alert("Array already sorted!");
else {
removeEventListeners();
await global.currentAlgorithm();
addEventListeners();
}
}
// Generate an array where the bars are a random height
function generateNewRandomArray() {
const minBarSize = 10;
const maxBarSize = 500;
clearArray();
global.length = rng(MIN_ARRAY_LENGTH, MAX_ARRAY_LENGTH);
for (let i = 0; i < global.length; i++)
array.push(rng(minBarSize, maxBarSize));
createVisualBarsFromArray();
}
// Generate new array which when sorted forms a triangle
function generateNewStepArray() {
clearArray();
global.length = rng(MIN_ARRAY_LENGTH, MAX_ARRAY_LENGTH);
for (let i = 0; i < global.length; i++)
array.push(i * 6);
shuffleNoAnimation();
createVisualBarsFromArray();
}
// Helper function for generating new arrays
function clearArray() {
array.length = 0;
}
// Helper function for generateNewStepArray()
function shuffleNoAnimation() {
array.sort(() => Math.random() - Math.random());
}
function addEventListeners() {
addEventListenerForRun();
addEventListenersForArrayGeneration();
addEventListenerForShuffle();
addEventListenersForAlgoSelection();
addEventListenerForSpeedSlider();
}
function addEventListenerForRun() {
const runDOM = document.querySelector("#run");
runDOM.addEventListener("click", run);
}
function addEventListenersForArrayGeneration() {
const randArrayDOM = document.querySelector("#rand-array");
const stepArrayDOM = document.querySelector("#step-array");
randArrayDOM.addEventListener("click", generateNewRandomArray);
stepArrayDOM.addEventListener("click", generateNewStepArray);
}
function addEventListenerForShuffle() {
const shuffleDOM = document.querySelector("#shuffle");
shuffleDOM.addEventListener("click", shuffle);
}
function addEventListenersForAlgoSelection() {
const algoSelectionMenu = document.querySelectorAll(".select-algo");
for (let i = 0; i < algoSelectionMenu.length; i++)
algoSelectionMenu[i].addEventListener("click", handleUserAlgorithmSelection);
}
function addEventListenerForSpeedSlider() {
const sliderDOM = document.querySelector("#speed-toggle");
sliderDOM.addEventListener("change", updateSpeed);
}
// Temporarily remove event listeners for functions you don't want interrupting another function
// i.e this prevents the user trying to generate a new array while the previous one is still being sorted
function removeEventListeners() {
removeEventListenerForRun();
removeEventListenersForArrayGeneration();
removeEventListenerForShuffle();
}
function removeEventListenerForRun() {
const runDOM = document.querySelector("#run");
runDOM.removeEventListener("click", run);
}
function removeEventListenersForArrayGeneration() {
const randArrayDOM = document.querySelector("#rand-array");
const stepArrayDOM = document.querySelector("#step-array");
randArrayDOM.removeEventListener("click", generateNewRandomArray);
stepArrayDOM.removeEventListener("click", generateNewStepArray);
}
function removeEventListenerForShuffle() {
const shuffleDOM = document.querySelector("#shuffle");
shuffleDOM.removeEventListener("click", shuffle);
}
// Helper function for run()
function isSorted() {
for (let i = 1; i < global.length; i++)
if (array[i - 1] > array[i])
return false;
return true;
}
// Handle user selecting which algorithm they want to run
function handleUserAlgorithmSelection(clickable) {
const algoButton = clickable.target;
const barColor = "#7FDBFF";
resetAlgoButtonColorsToDefault();
algoButton.style.color = barColor;
global.currentAlgorithm = pickAlgorithm.get(algoButton.innerHTML);
}
// Reset all of the algorithm selection buttons to their default colour of white
function resetAlgoButtonColorsToDefault() {
const algoSelectionMenu = document.querySelectorAll(".select-algo");
for (let i = 0; i < algoSelectionMenu.length; i++)
algoSelectionMenu[i].style.color = "white";
}
// Change speed of algorithm based on user changing value of slider
function updateSpeed(clickable) {
const slider = clickable.target;
global.speed = slider.value;
}
function createVisualBarsFromArray() {
clearVisualBars();
const containerDOM = document.querySelector("#bar-container");
for (let i = 0; i < global.length; i++)
containerDOM.append(createNewVisualBar(i));
}
// Helper function for createVisualBarsFromArray()
function clearVisualBars() {
const containerDOM = document.querySelector("#bar-container");
containerDOM.innerHTML = '';
}
// Helper function for createVisualBarsFromArray()
function createNewVisualBar(index) {
const newBar = document.createElement("div");
const defaultHeight = 100;
newBar.className = "bar";
newBar.setAttribute("style", "height: " + defaultHeight + "px");
newBar.setAttribute("style", "height: " + array[index] + "px");
return newBar;
}
async function insertionSort() {
var j;
for (let i = 0; i < global.length; i++) {
j = i;
while (j >= 1 && array[j] < array[j - 1])
await swap(j, --j);
}
}
async function selectionSort() {
var min;
for (let limit = 0; limit < global.length; limit++) {
min = indexOfMinElement(limit);
await swap(limit, min);
}
}
// Helper function for selectionSort. Only considers elements of an index greater than indexLimit
function indexOfMinElement(indexLimit) {
var min = Infinity;
var minIndex;
for (let i = indexLimit; i < global.length; i++) {
if (array[i] <= min) {
minIndex = i;
min = array[i];
}
}
return minIndex;
}
async function quickSort() {
await quickSortBody(0, global.length - 1);
}
async function quickSortBody(lower, upper) {
if (lower < upper) {
let pivot = await partition(lower, upper);
await quickSortBody(lower, pivot - 1);
await quickSortBody(pivot + 1, upper);
}
}
// Helper function for quickSort, partition section of array between lower and upper and return index of pivot
async function partition(lower, upper) {
const pivot = array[upper];
var i = lower;
for (let j = lower; j <= upper; j++) {
if (array[j] < pivot) {
await swap(i, j);
i++;
}
}
await swap(i, upper);
return i;
}
async function heapSort() {
await buildHeap();
for (let i = global.length - 1; i > 0; i--) {
await swap(0, i);
await heapify(0, i);
}
}
async function buildHeap() {
for (let i = Math.floor(global.length / 2) - 1; i >= 0; i--)
await heapify(i, global.length);
}
async function heapify(root, cutoff) {
var max = root;
var left = 2 * root + 1;
var right = 2 * root + 2;
if (right < cutoff && array[right] > array[max])
max = right;
if (left < cutoff && array[left] > array[max])
max = left;
if (root != max) {
await swap(root, max);
await heapify(max, cutoff);
}
}
// Swap items at the given indexes
async function swap(i, j) {
return new Promise((resolve) => {
const temp = array[i];
array[i] = array[j];
array[j] = temp;
setTimeout(() => {
renderSwapInView(i, j);
resolve();
}, global.speed);
});
}
// Update the DOM based on element indices that were swapped by the algorithm
function renderSwapInView(i, j) {
const containerDOM = document.querySelector("#bar-container");
containerDOM.children[i].setAttribute("style", "height: " + array[i] + "px");
containerDOM.children[j].setAttribute("style", "height: " + array[j] + "px");
}
async function shuffle() {
removeEventListeners();
for (let i = 0; i < global.length; i++)
await swap(i, rng(0, global.length));
addEventListeners();
}
//Generates a random number whose value lies between lower and upper
function rng(lower, upper) {
return Math.floor(Math.random() * (upper - lower)) + lower;
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T08:41:51.803",
"Id": "244368",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"sorting",
"quick-sort",
"data-visualization"
],
"Title": "Sorting Algorithm Visualiser in Javascript"
}
|
244368
|
<p>I have a dataframe like so:</p>
<pre><code>id variable value
1 x 5
1 y 5
2 x 7
2 y 7
</code></pre>
<p>Now for every row, I want to add a calculated row. This is what I am doing as of now:</p>
<pre><code>a = 2
b = 5
c = 1
d = 3
df2 = pd.DataFrame(columns = ["id", "variable", "value"])
for index, row in df.iterrows():
if row['variable'] == 'x':
df2 = df2.append({'id':row['id'], 'variable':'x1', 'value':a*row['value']+b}, ignore_index=True)
else:
df2 = df2.append({'id':row['id'], 'variable':'y1', 'value':c*row['value']+d}, ignore_index=True)
df = pd.concat([df, df2])
df = df.sort_values(['id', 'variable'])
</code></pre>
<p>And so finally I get:</p>
<pre><code>id variable value
1 x 5
1 x1 15
1 y 5
1 y1 8
2 x 7
2 x1 19
2 y 7
2 y1 10
</code></pre>
<p>But surely there must be a better way to do this. Perhaps where I could avoid for loop and sorting, as there are a lot of rows.</p>
|
[] |
[
{
"body": "<h1>iterrows</h1>\n<p>Of all the ways to iterate over a pandas DataFrame, <code>iterrows</code> is the worst. This creates a new series for each row. this series also has a single dtype, so it gets upcast to the least general type needed. This can lead to unexpected loss of information (large ints converted to floats), or loss in performance (object dtype).</p>\n<p>Slightly better is <code>itertuples</code></p>\n<h1>append</h1>\n<p>Appending row per row can be very slow (<a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html\" rel=\"noreferrer\">link1</a><a href=\"https://stackoverflow.com/a/31675177/1562285\">link2</a>)</p>\n<p>Better would be to assembly them in a list, and make a new DataFrame in 1 go.</p>\n<h1>vectorise</h1>\n<p>One easy change you can make is not iterating over the database in 'Python' space, but using boolean indexing</p>\n<pre><code>x = df["variable"] == "x"\ny = df["variable"] == "y"\n\ndf2 = df.copy()\ndf2.loc[x, "value"] = df.loc[x, "value"] * a + b\ndf2.loc[y, "value"] = df.loc[y, "value"] * c + d\ndf2.loc[x, "variable"] = "x1"\ndf2.loc[y, "variable"] = "y1"\n</code></pre>\n<h1>wide vs long</h1>\n<p>This can be made a lot easier by reforming your dataframe by making it a bit wider:</p>\n<pre><code>df_reformed = (\n df.set_index(["id", "variable"]).unstack("variable").droplevel(0, axis=1)\n)\n</code></pre>\n<blockquote>\n<pre><code>variable x y\nid \n1 5 5\n2 7 7\n</code></pre>\n</blockquote>\n<p>Then you can calculate x1 and y1 vectorised:</p>\n<pre><code>df_reformed.assign(\n x1=df_reformed["x"] * a + b, \n y1=df_reformed["y"] * c + d\n)\n</code></pre>\n<p>and then convert this back to the long format:</p>\n<pre><code>result = (\n df_reformed.assign(\n x1=df_reformed["x"] * a + b, \n y1=df_reformed["y"] * c + d\n )\n .stack()\n .rename("value")\n .sort_index()\n .reset_index()\n)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T09:54:38.443",
"Id": "244370",
"ParentId": "244369",
"Score": "6"
}
},
{
"body": "<p>I agree with the accepted answer. An alternative way to frame this is a <a href=\"https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#multiindex-advanced-indexing\" rel=\"nofollow noreferrer\">multi-index</a>, with indices of <code>id</code> and <code>variable</code>.</p>\n<p>You will then effectively have three-dimensional data, where the first dimension is an integral ID, the second dimension is a categorical variable name, and the third dimension is your value.</p>\n<p>You could extend this concept even further, with dimensions of <code>id</code>, <code>variable</code> (only to contain <code>x</code> and <code>y</code>), <code>subscript</code> (0 or 1, whatever that represents in your context), and <code>value</code>. Certain indexing operations will be made easier by this approach.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T14:44:19.870",
"Id": "244381",
"ParentId": "244369",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "244370",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T09:21:29.977",
"Id": "244369",
"Score": "5",
"Tags": [
"python",
"performance",
"pandas"
],
"Title": "Pandas add calculated row for every row in a dataframe"
}
|
244369
|
<p>I have a large image and I am extracting and processing tiles in batches of a given size. A tile is normally a 256x256 region and batches are normally a power of 2.</p>
<p>In the below example the number of tiles per cols is 3 and the number of tiles per rows is 5, and I want batches of 3.</p>
<p><a href="https://i.stack.imgur.com/qdkeK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qdkeK.png" alt="Tiling large image" /></a></p>
<p>Legend: Yellow rectangle = tile, Red rectangle = batch of tiles, Blue rectangle = full image</p>
<p>Is my code Pythonic enough, can I get extra speed?</p>
<pre><code>import numpy as np
batch_size = 3
input_raster = ... numpy array of shape (3,image_width,image_height)
output_raster = ...numpy array of shape (3,image_width,image_height)
nb_tiles_per_cols = 3
nb_tiles_per_rows = 5
total = nb_tiles_per_cols * nb_tiles_per_rows
remaining = total
for i in range(0,total,batch_size):
size = min(remaining,batch_size)
batch_input = np.ndarray((size,256,256,1))
for j in range(0,size):
# handle index i+j
indexRC = i+j
col = indexRC % nb_tiles_per_cols
row = indexRC // nb_tiles_per_cols
# read tile from input raster of shape (3,256*nb_tiles_per_rows,256*nb_tiles_per_cols)
img = input_raster[:,row*256:(row+1)*256,col*256:(col+1)*256]
# process img to get input_image
...
batch_input[j] = input_image
# inference.predict return an array of shape (size,256,256,1)
predictions = inference.predict(batch_input)
for j in range(0,size):
# handle index i+j
indexRC = i+j
col = indexRC % nb_tiles_per_cols
row = indexRC // nb_tiles_per_cols
output_raster[row*256:(row+1)*256,col*256:(col+1)*256] = predictions[j]
remaining -= size
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T10:31:36.100",
"Id": "479755",
"Score": "0",
"body": "Rather than using `lang-python` to get syntax highlighting you can add the Python tag to enable it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T14:13:17.907",
"Id": "479766",
"Score": "0",
"body": "_the number of tiles per cols is 3_ - are you sure? Isn't that the number of columns per tile?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T14:31:46.673",
"Id": "479768",
"Score": "1",
"body": "If you look at the example image, there are 3 tiles vertically and 5 tiles horizontally. The full image is made of 15 tiles. So the number of tiles in a column is 3. A tile is a yellow rectangle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T14:37:53.557",
"Id": "479769",
"Score": "0",
"body": "Oh. A \"legend\" such as \"yellow is a tile; red is a batch\" would help."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T10:01:24.200",
"Id": "244371",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Splitting an image in batches of tiles"
}
|
244371
|
<p>I'm not sure if I'm even approaching this correctly (still very much learning), but this is what I'm attempting to accomplish:
My script gets an array from a column (tab names of the sheet) and then calls another function to copy those tabs (this part works fine). What I'm attempting to add is a separate list of properties that I want to assign to each copied sheet (visibility, color, etc.) This secondary list is on another tab, so my thought was that within my first loop (that determines which tabs to copy), I would have a nested loop that would find the match to the tab name and then bring those variables in to be associated with the sheet name.</p>
<p>My secondary <code>for</code> loop <em>works</em>, but it seems counter intuitive or somewhat redundant. It feels like a lot of wasted effort to loop through the "properties array" for every loop, but maybe it <em>is</em> necessary.</p>
<pre class="lang-js prettyprint-override"><code>function getSheetArray(ui, ss, settingsSheet, updateID, latestVersion, versionRangeName, updateSheet, updateSheetsSheet, sheetsToUpdateRangeName, updateSheetsVals) {
var updateSheetsLength = updateSheetsVals.filter(String).length;
if (updateSheetsLength == null) {
return
}
var sheetDataRange = updateSheetsSheet.getRange(2, 1, updateSheetsLength, 1);
const sheetData = sheetDataRange.getValues();
var updateSheet = SpreadsheetApp.openById(updateID);
var tabSheet = updateSheet.getSheetByName("tabDefinitions");
var tabDataRange = tabSheet.getRange(2, 1, tabSheet.getMaxRows() - 1, tabSheet.getMaxColumns());
const tabData = tabDataRange.getValues();
var tabProps = [];
for (var i = 0; i < sheetData.length; i++) {
var sheetName = sheetData[i];
for (var j = 0; j < tabData.length; j++) {
if (sheetName == tabData[j][0]) {
var tabProps = [
tabName = tabData[j][0],
tabVisibility = tabData[j][3],
tabUpdVisibility = tabData[j][4],
tabClearData = tabData[j][5],
tabFormat = tabData[j][6],
tabPosition = tabData[j][7],
tabColor = tabData[j][8]
];
}
}
console.log("tabProps = ", tabProps);
console.log("tabName = " + tabName);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I don't know enough about the shape of <code>testData</code> to write great code, but you could preprocess and convert <code>testData</code> from an array to an object or Map of key-value pairs. By using the first element of each item in <code>testData</code> as the key, then you can convert your <span class=\"math-container\">\\$O(n)\\$</span> inner "search" loop into a constant time <span class=\"math-container\">\\$O(1)\\$</span> key lookup. This would reduce your overall complexity from something on the order of <span class=\"math-container\">\\$O(n^2)\\$</span> to a nicer linear <span class=\"math-container\">\\$O(n)\\$</span> algorithm.</p>\n<p><strong>Note</strong>: This assumes your data has unique values sitting at index 0 of each element in the main array. The difference being your code returns the first match, but the following technically return the last match as duplicate key overwrite existing value(s).</p>\n<p>Something like:</p>\n<pre><code>var tabData = tabDataRange\n .getValues()\n .reduce((tabData, data) => ({ ...tabData, [data[0]]: data }), {});\n</code></pre>\n<p>Then your loop becomes</p>\n<pre><code>for (var i = 0; i < sheetData.length; i++) {\n var sheetName = sheetData[i];\n\n if (tabData[sheetName]) {\n var data = tabData[sheetName];\n var tabProps = [\n tabName = data[0],\n tabVisibility = data[3],\n tabUpdVisibility = data[4],\n tabClearData = data[5],\n tabFormat = data[6],\n tabPosition = data[7],\n tabColor = data[8]\n ];\n break; // <-- found data, break out of loop early\n }\n console.log("tabProps = ", tabProps);\n console.log("tabName = " + tabName);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T09:11:07.897",
"Id": "244434",
"ParentId": "244380",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T14:44:01.737",
"Id": "244380",
"Score": "2",
"Tags": [
"javascript",
"array",
"google-apps-script",
"google-sheets"
],
"Title": "Nesting for loops to find matches in different tables"
}
|
244380
|
<p>I have a query that outputs a list of products with some fields from other tables. That query works fine.</p>
<p>Now, I'm attempting to retrieve the available stock for each product in that list. I'm not sure if I'm doing it correctly or in the most performant way. Here's what I've got working so far.</p>
<pre><code>select distinct
p.id,
p.name
if(coalesce(x.in - x.out, 0) = 0, 0, 1) as quantity,
[other fields from joined tables]
from products p
[a bunch of inner joins]
left join (
select
s.id_products,
sum(case when s.type = 'in' then s.quantity else 0 end) as 'in',
sum(case when s.type = 'out' then s.quantity else 0 end) as 'out'
from stock s
group by s.id_products
) x on x.id_products = p.id_products
group by id
</code></pre>
<hr />
<p><strong>EDIT</strong>: I made a mistake in the query the <code>if</code> statement in the select is just for a flag display. Please replace the following.</p>
<blockquote>
<pre><code>if(coalesce(x.in - x.out, 0) = 0, 0, 1) as quantity,
</code></pre>
</blockquote>
<pre><code>(x.in - x.out, 0) as quantity,
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T18:01:38.723",
"Id": "479781",
"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 should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)."
}
] |
[
{
"body": "<h2>Discarded sums</h2>\n<p>You calculate these sums:</p>\n<pre><code>sum(case when s.type = 'in' then s.quantity else 0 end) as 'in', \nsum(case when s.type = 'out' then s.quantity else 0 end) as 'out' \n</code></pre>\n<p>but then reduce them to a 0/1 here:</p>\n<pre><code>if(coalesce(x.in - x.out, 0) = 0, 0, 1) as quantity,\n</code></pre>\n<p>This means that a <code>sum</code> is not appropriate at all. This should be refactored to an <code>if exists</code>, where the predicate compares <code>s.type</code> to <code>in</code>/<code>out</code> and checks that <code>s.quantity > 0</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T17:57:37.127",
"Id": "479780",
"Score": "0",
"body": "Hello @Reinderien, I accidentally leave that...but is just for a flag display. I will now add an edit to my post"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T17:44:13.270",
"Id": "244399",
"ParentId": "244383",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T14:58:35.567",
"Id": "244383",
"Score": "2",
"Tags": [
"performance",
"sql",
"mysql"
],
"Title": "Query to retrieve available stock"
}
|
244383
|
<p>Update:</p>
<p>This is an older version of the question/script. The new version can be found here: <a href="https://codereview.stackexchange.com/questions/244736/part-2-send-http-request-for-each-row-in-excel-table/244756">Part 2: Send HTTP request for each row in Excel table</a></p>
<hr />
<p>I have an Excel spreadsheet where users can batch-enter records and load them into an external system (via HTTP).</p>
<p><a href="https://i.stack.imgur.com/mpBI2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mpBI2.png" alt="enter image description here" /></a></p>
<p>This is what the VBA in the spreadsheet does:</p>
<ol>
<li>A custom function concatenates columns with parameters into the <code>Concatenated Variables</code> column.</li>
<li>Loops through each row in the table where <code>Load? = y</code></li>
<li>Sends an HTTP request to an external system using the value in the <code>URL</code> column.</li>
<li>Returns a message (created, updated, or error) and stores it in the <code>Message</code> column.</li>
<li>Puts the current date into the <code>Message Timestamp</code> column.</li>
</ol>
<p>Question:</p>
<p>How can the code be improved?</p>
<hr />
<pre><code>Option Explicit
Public Sub LoadRecords()
'Refreshes the Concatenated Variables column
Application.CalculateFull
Dim tbl As ListObject
Dim x As Long
Dim colNumLoad As Long
Dim colNumMessage As Long
Dim colNumURL As Long
Dim colNumTimestamp As Long
Dim response As String
Dim message As String
Dim colorIndex As Integer
Set tbl = ActiveSheet.ListObjects("tblData")
colNumLoad = getColNum("Load?")
colNumMessage = getColNum("Message")
colNumURL = getColNum("URL")
colNumTimestamp = getColNum("Message Timestamp")
'Clear the cell formatting in the Message column
'More info: VBA Guide To ListObject Excel Tables - 'https://www.thespreadsheetguru.com/blog/2014/6/20/the-vba-guide-to-listobject-excel-tables
tbl.ListColumns(colNumMessage).Range.Interior.colorIndex = 0
'Loop through each data body row in the table
For x = 1 To tbl.ListRows.Count
If UCase(tbl.ListRows(x).Range.Cells(1, colNumLoad)) = "Y" Then
'Send an HTTP request to Maximo using the value in the URL column
response = getHTTP(tbl.ListRows(x).Range.Cells(1, colNumURL))
'Return a message (created, updated, or error) and store it in the Message column.
tbl.ListRows(x).Range(1, colNumMessage).Value = response
'Put the current date into the Message Timestamp column. Note: This is the Excel date, not a date from Maximo.
tbl.ListRows(x).Range(1, colNumTimestamp).Value = Now()
'Change background colour in the Message column for rows that were loaded. Uses the Left function to get the first word or character from the message.
'More info: https://www.excel-easy.com/vba/examples/background-colors.html
message = Left(tbl.ListRows(x).Range(1, colNumMessage).Value, 7)
Select Case message
Case "Created"
colorIndex = 43 '(Green)
Case "Updated"
colorIndex = 37 '(Blue)
Case Else
colorIndex = 3 '(Red)
End Select
tbl.ListRows(x).Range(1, colNumMessage).Interior.colorIndex = colorIndex
End If
Next x
End Sub
'More info: https://stackoverflow.com/questions/817602/gethttp-with-excel-vba
Public Function getHTTP(ByVal url As String) As String
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", url, False: .Send
getHTTP = StrConv(.responseBody, vbUnicode)
End With
End Function
Function getColNum(ColName As String) As Long
Dim tbl As ListObject
Dim x As Long
Set tbl = ActiveSheet.ListObjects("tblData")
For x = 1 To tbl.ListColumns.Count
If tbl.ListColumns(x).Name = ColName Then
getColNum = x
Exit For
End If
Next x
End Function
'Concatenate the columns that contain parameters into the Concatenated Variables column.
Function CONCATVARS(RowNum As Integer) As String
Dim tbl As ListObject
Dim x As Long
Dim varConcat As String
Set tbl = ActiveSheet.ListObjects("tblData")
For x = 1 To tbl.ListColumns.Count
If Left(tbl.ListColumns(x).Name, 2) = "v_" Then
If varConcat <> "" Then
varConcat = VarConcat & "&"
End If
'The MID function removes the "v_" prefix from the string
varConcat = varConcat & Mid(tbl.ListColumns(x).Name & "=" & tbl.Range.Cells(RowNum, x), 3)
End If
Next x
CONCATVARS = varConcat
End Function
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T15:38:49.840",
"Id": "479879",
"Score": "1",
"body": "For large data, its better to reduce number of loops. The `getColNum` function is having one loop. You can avoid it using [Range.Find](https://docs.microsoft.com/en-us/office/vba/api/excel.range.find) method. `tbl.Range.Rows(1).Cells.Count` will give you total number of columns in the ListObject. `colNumURL = tbl.Range.Rows(1).Find(\"URL\", Range(\"A1\"), xlValues, xlWhole, xlByRows, xlNext).Column` will give you column number of \"URL\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T13:54:39.890",
"Id": "479991",
"Score": "0",
"body": "Over in the [VBA Rubberducking](https://chat.stackexchange.com/rooms/14929/vba-rubberducking) chat, @MathieuGuindon suggested I run the code through rubberduckvba.com's Inspection tool. *\"...will not just tell you that Option Explicit is missing, it will also explain why you want Option Explicit enabled everywhere. Many inspection ideas stemmed from questions frequently asked on Stack Overflow, and again explain what’s going on and why that might be a problem. If you’re new to VBA, Rubberduck inspections can teach you things about how VBA works, that many veterans took years to learn about!\"*"
}
] |
[
{
"body": "<h2>Constants</h2>\n<p>Use constants to make it easier to read and modify your code as names change.</p>\n<pre><code>Public Const TblDataName = "tblData"\nPublic Const TblDataLoadColumn = "Load?"\nPublic Const TblDataMessageColumn = "Message"\nPublic Const TblDataNumURLColumn = "URL"\nPublic Const TblDataTimestampColumn = "Message Timestamp"\n\n\nPublic Sub LoadRecords()\n 'some code ....\n Set tbl = ActiveSheet.ListObjects(TblDataName)\n colNumLoad = getColNum(TblDataLoadColumn)\n colNumMessage = getColNum(TblDataMessageColumn)\n colNumURL = getColNum(TblDataNumURLColumn)\n colNumTimestamp = getColNum(TblDataTimestampColumn)\n</code></pre>\n<p>This setup will allow you to easily update your string references without have to review every line of code.</p>\n<h2>Avoid Using ActiveSheet</h2>\n<blockquote>\n<pre><code>Set tbl = ActiveSheet.ListObjects("tblData")\n</code></pre>\n</blockquote>\n<p>Using ActiveSheet makes your code fragile, easy to break, and limits code reuse. It is a best practice to change your Worksheet's CodeName and reference the Worksheets by their CodeNames.</p>\n<p>I like to add references to my ListObjects as properties of their worksheets.</p>\n<p><img src=\"https://i.stack.imgur.com/BKAbg.png\" alt=\"Add ListObject as a Property of the Worksheet\" /></p>\n<h2>Function getColNum can be removed</h2>\n<p>Here is the correct way to retrieve the ListColumn Index:</p>\n<p><img src=\"https://i.stack.imgur.com/G0kYi.png\" alt=\"ListColumn Name to Index\" /></p>\n<h2>Function CONCATVARS</h2>\n<p>Functions names should be Pascal case. I alternate between <code>Pascal</code> and <code>camelCase</code> but never all uppercase. Only constants and Enums should be all upper case (although I have been converted to using Pascal case for them also).</p>\n<p><code>varConcat</code> is very descriptive if you compare it to its context and figure out its meaning. However, you can deduce the usage of text and str without knowing its context. For such a short block of code I prefer using s. Using shorter simpler names often make the code easier to read.</p>\n<pre><code>Function ConcatVars(tbl As ListObject, RowNum As Integer) As String\n Dim Column As ListColumn\n Dim s As String\n \n For Each Column In tbl.ListColumns\n If Column.Name Like "v_*" Then\n s = s & IIf(Len(s) > 0, "&", "") _\n & Mid(Column.Name & "=" & Column.Range.Cells(RowNum).Value, 3)\n End If\n Next\n\n ConcatVars = s\n\nEnd Function\n</code></pre>\n<p><img src=\"https://i.stack.imgur.com/Yj6nQ.png\" alt=\"ConcatVars\" /></p>\n<h2>Refactored Code</h2>\n<pre><code>Option Explicit\nPublic Const TblDataName = "tblData"\nPublic Const TblDataLoadColumn = "Load?"\nPublic Const TblDataMessageColumn = "Message"\nPublic Const TblDataNumURLColumn = "URL"\nPublic Const TblDataTimestampColumn = "Message Timestamp"\n\nPublic Sub LoadRecords()\n Rem Refreshes the Concatenated Variables column\n Application.CalculateFull\n Dim message As String, response As String\n Dim n As Long\n \n With DataSheet.GetTblData\n .ListColumns(TblDataMessageColumn).Range.Interior.colorIndex = 0\n For n = 1 To .ListRows.Count\n If UCase(.ListColumns(TblDataLoadColumn).DataBodyRange(n).Value) = "Y" Then\n response = getHTTP(.ListColumns(TblDataNumURLColumn).DataBodyRange(n).Value) 'Send an HTTP request to Maximo using the value in the URL column\n .ListColumns(TblDataMessage).DataBodyRange(n) = response\n\n Rem Put the current date into the Message Timestamp column. Note: This is the Excel date, not a date from Maximo.\n .ListColumns(TblDataTimestampColumn).DataBodyRange(n) = Now()\n \n With .ListColumns(TblDataMessageColumn).DataBodyRange(n)\n message = Left(response, 7) 'Return a message (created, updated, or error) and store it in the Message column.\n .Interior.colorIndex = Switch(message = "Created", 43, message = "Updated", 37, True, 3)\n End With\n \n End If\n Next\n End With\nEnd Sub\n</code></pre>\n<h2>Addendum</h2>\n<p>I added a sample. It shows how I would setup the project and demonstrates a couple of different techniques for working with ListObjects.</p>\n<p><a href=\"https://drive.google.com/file/d/1RLvyTpLrS-SfrO8PJ4II1PFSqkM-N6TY/view?usp=sharing\" rel=\"nofollow noreferrer\">Table Demo</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T18:58:42.037",
"Id": "480039",
"Score": "0",
"body": "Regarding your ConcatVars() function: I'm struggling with the `tbl As ListObject` part. How would I pass in the `tbl` value to the function? Would I pass it in from the Excel sheet when calling the function? Right now the formula is just `=concatvars(ROW())`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T19:00:48.190",
"Id": "480041",
"Score": "0",
"body": "In general, I'm not quite understanding how the `GetTblData()` function works. Would you mind explaining it a bit further?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T13:25:03.103",
"Id": "480113",
"Score": "0",
"body": "I think I get it now: [CodeName as constant?](https://stackoverflow.com/questions/62583341/codename-as-constant)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T14:56:01.283",
"Id": "480125",
"Score": "0",
"body": "@User1973 Pretty much. I mocked up a demo for you [Table Demo](https://drive.google.com/file/d/1RLvyTpLrS-SfrO8PJ4II1PFSqkM-N6TY/view?usp=sharing). Thanks for accepting my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T15:33:14.893",
"Id": "480136",
"Score": "0",
"body": "Thanks! Working through the demo now. On a side note: would it be a better practice to convert `For n = 1 To .ListRows.Count` to a `For Each`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T21:40:21.847",
"Id": "480178",
"Score": "1",
"body": "@User1973 Its personal preference. I prefer `for each` while working with objects."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T17:26:17.667",
"Id": "244457",
"ParentId": "244387",
"Score": "3"
}
},
{
"body": "<p>TinMan posted his answer while I was typing mine out but I'm pretty much done so I'm just going to answer anyway!</p>\n<h2>Use of ActiveSheet</h2>\n<p>This is probably the biggest issue with the code as is. Unless you don't know beforehand what sheet you'll be working with, you want to avoid <code>ActiveSheet</code> as it refers to whatever sheet the user is currently looking at, which may not even be in the same workbook! If this is intentional (say you might want to run this macro on a variety of different sheets but you never know while coding what sheets you want to run it on) then you can ignore this, but that seems unlikely since you refer to tables by name. This is an easy fix, you just change <code>set tbl = ActiveSheet.ListObjects("tblData")</code> to <code>set tbl = Sheet1.ListObjects("tblData")</code> (or whatever the codename for the sheet you're working with is).</p>\n<p><strong>Magic numbers</strong></p>\n<p>Using comments to explain random numbers in your code is good, but I prefer using constants to increase readability a tiny bit. That way you could change this</p>\n<pre><code> message = Left(tbl.ListRows(x).Range(1, colNumMessage).Value, 7)\n Select Case message\n Case "Created"\n colorIndex = 43 '(Green)\n Case "Updated"\n colorIndex = 37 '(Blue)\n Case Else\n colorIndex = 3 '(Red)\n End Select\n</code></pre>\n<p>to</p>\n<pre><code> message = Left(tbl.ListRows(x).Range(1, colNumMessage).Value, 7)\n Select Case message\n Case "Created"\n colorIndex = GREEN\n Case "Updated"\n colorIndex = BLUE\n Case Else\n colorIndex = RED\n End Select\n</code></pre>\n<p>and declare somewhere up top <code>Const GREEN = 43</code> etc. However, I don't know what that random 7 is about. That should likely be a variable as well.</p>\n<p><strong>GetColNum()</strong></p>\n<p>I actually had a function just like this in the program I'm working on right now until I realized there's a built-in and way easier way to do it. You can just assign all of your column number variables to <code>tbl.listcolumns("whateverColumn").Index</code>. Then, you can just get rid of that function.</p>\n<p><strong>Integers</strong></p>\n<p>Except for a few niche cases (I think if you want to save the result of a msgbox to a variable you have to use integers), you should basically always use <code>long</code>s instead of <code>integer</code>s. VBA automatically converts integers to longs behind-the-scenes so declaring as integer doesn't actually save any memory or anything (and actually adds a miniscule amount of time to your process since your data type has to be converted).</p>\n<p><strong>Variable Names</strong></p>\n<p>Code is meant to be read by people as well as machines, so you might as well make your variable names more readable! Variables like <code>colNumLoad</code> can become <code>loadColumnIndex</code> or something similar that isn't unnecessarily truncated.</p>\n<p><strong>Wall of Declarations</strong></p>\n<p>This point is kind of debated (a lot of people like to throw all their variables at the top for some reason), but I find that declaring variables close to where you use them helps readability and reduces the chance of winding up with unused variables. I didn't 100% follow through with this in my updated version below because all of the column numbers felt like properties to me</p>\n<p><strong>The For Loop in LoadRecords()</strong></p>\n<p>To me, this loop makes sense as a <code>for each</code> loop instead of just a <code>for</code> loop. (I just noticed you even say "loops through each" in your comment!) Realistically, this probably won't improve performance or anything, but I do think its a little simpler to read. Also, for half of the lines, you use <code>.range.cells</code> but for the other half just <code>.range</code>. I went with the latter because it seemed unnecessary to have both, but either way it's important to be consistent!</p>\n<p>Also, since you have <code>response = getHTTP()</code> and <code>tbl.ListRows(x).Range(1, colNumMessage).Value = response</code>, you can cut out the response variable and just directly assign the return value of getHTTP to the range value.</p>\n<p><strong>ConcatVars()</strong></p>\n<p>Typically in VBA, function names use Pascal case. I also changed the name to <code>ConcatenateVariables()</code> for the reasons outlined above.</p>\n<h2>Refactored Code</h2>\n<p>Overall, this is a very good start! I hope my answer is helpful.</p>\n<pre><code>Option Explicit\n\nPublic Sub LoadRecords()\n\n Const GREEN = 43\n Const BLUE = 37\n Const RED = 3\n \n 'Refreshes the Concatenated Variables column\n Application.CalculateFull\n\n Dim recordTable As ListObject\n Set recordTable = Sheet1.ListObjects("tblData") 'or whatever sheet you're working with\n \n Dim loadColumnIndex As Long\n Dim messageColumnIndex As Long\n Dim URLColumnIndex As Long\n Dim timestampColumnIndex As Long\n \n loadColumnIndex = recordTable.ListColumns("Load?").Index\n messageColumnIndex = recordTable.ListColumns("Message").Index\n URLColumnIndex = recordTable.ListColumns("URL").Index\n timestampColumnIndex = recordTable.ListColumns("Message Timestamp").Index\n \n 'Clear the cell formatting in the Message column\n 'More info: VBA Guide To ListObject Excel Tables - 'https://www.thespreadsheetguru.com/blog/2014/6/20/the-vba-guide-to-listobject-excel-tables\n recordTable.ListColumns(messageColumnIndex).Range.Interior.colorIndex = 0\n\n Dim currentRow As ListRow\n 'Loop through each data body row in the table\n For Each currentRow In recordTable.ListRows\n If UCase(currentRow.Range(columnindex:=loadColumnIndex).Value) = "Y" Then\n \n 'Send an HTTP request to Maximo using the value in the URL column,\n 'Return a message (created, updated, or error) and store it in the Message column.\n currentRow.Range(columnindex:=messageColumnIndex).Value = getHTTP(currentRow.Range(columnindex:=URLColumnIndex).Value)\n \n 'Put the current date into the Message Timestamp column. Note: This is the Excel date, not a date from Maximo.\n currentRow.Range(columnindex:=timestampColumnIndex).Value = Now()\n\n 'Change background colour in the Message column for rows that were loaded. Uses the Left function to get the first word or character from the message.\n 'More info: https://www.excel-easy.com/vba/examples/background-colors.html\n Dim message As String\n message = Left(currentRow.Range(columnindex:=messageColumnIndex).Value, 7)\n \n Dim colorIndex As Long\n Select Case message\n Case "Created"\n colorIndex = GREEN\n Case "Updated"\n colorIndex = BLUE\n Case Else\n colorIndex = RED\n End Select\n\n currentRow.Range(columnindex:=messageColumnIndex).Interior.colorIndex = colorIndex\n\n End If\n Next\n\nEnd Sub\n\n'More info: https://stackoverflow.com/questions/817602/gethttp-with-excel-vba\nPublic Function getHTTP(ByVal url As String) As String\n\n With CreateObject("MSXML2.XMLHTTP")\n .Open "GET", url, False: .Send\n getHTTP = StrConv(.responseBody, vbUnicode)\n End With\n\nEnd Function\n\n'Concatenate the columns that contain parameters into the Concatenated Variables column.\nFunction ConcatenateVariables(ByVal RowNum As Long) As String\n\n Const PREFIX_LENGTH = 2\n Const PREFIX_END = 3 'you can probably choose better names for these\n\n Dim recordTable As ListObject\n Set recordTable = Set recordTable = Sheet1.ListObjects("tblData") 'or whatever sheet you're working with\n\n Dim currentColumn As ListColumn\n For Each currentColumn In recordTable.ListColumns\n If Left(currentColumn.Name, PREFIX_LENGTH) = "v_" Then\n Dim result As String\n If result <> vbNullString Then\n result = result & "&"\n End If\n 'The MID function removes the "v_" prefix from the string\n result = result & Mid(currentColumn.Name & "=" & currentColumn.Range(RowNum), PREFIX_END) 'prefix_length + 1 is also probably a good replacement for prefix_end\n End If\n Next\n\n ConcatenateVariables = result\n\nEnd Function\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T17:46:02.000",
"Id": "244459",
"ParentId": "244387",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244457",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T15:38:59.350",
"Id": "244387",
"Score": "7",
"Tags": [
"beginner",
"vba",
"excel",
"http"
],
"Title": "Part 1: Send HTTP request for each row in Excel table"
}
|
244387
|
<p>Our testing suite is configured using a type of hierarchical config file similar to <code>.ini</code> or <code>.toml</code> files. Each 'block' is a test that is run on our cluster. I'm working on adding unique ids to each test that will help map results to tests over time. A small example of a config file would be:</p>
<pre><code>[Tests]
[test1]
type = CSVDIFF
input = test1.i
output = 'test1_chkfile.csv'
max_tol = 1.0e-10
unique_id = fa3acd397ae0d633194702ba6982ee93da09b835945845771256f19f44816f31
[]
[test2]
type = CSVDIFF
input = test2.i
output = 'test2_chkfile.csv'
[]
[]
</code></pre>
<p>The idea is to check all of these files and for tests that don't have an id, create it and write it to the file. I would like a quick code-review on my style, convention, and logic. Here is the script that will be run as a part of the CI precheck:</p>
<pre><code>#!/usr/bin/env python3
import hashlib
import sys
from glob import glob
from textwrap import dedent
from time import time
from collections import UserDict
from typing import List, AnyStr, Any
import pyhit # type: ignore
class StrictDict(UserDict):
"""Custom dictionary class that raises ValueError on duplicate keys.
This class inherits from collections.UserDict, which is the proper
way to create a subclass inheriting from `dict`. This dictionary
will raise an error if it is given an `unique_id` key that it has
previously indexed. Otherwise, it provides all methods and features
of a standard dictionary.
"""
def __setitem__(self, key: Any, value: Any) -> None:
try:
current_vals = self.__getitem__(key)
raise ValueError(
dedent(
f"""\
Duplicate key '{key}' found!
First id found in {current_vals[0]}, line {current_vals[1]}.
Duplicate id found in {value[0]}, line {value[1]}.\
"""
)
)
except KeyError:
self.data[key] = value
def hashnode(node: pyhit.Node) -> str:
"""Return a sha256 hash of spec block to be used as a unique id."""
# time() returns the number of seconds since Jan. 1st, 1970 in UTC.
hash_str = node.fullpath + str(time()) + node.render()
sha_signature = hashlib.sha256(hash_str.encode()).hexdigest()
return sha_signature
def fetchnodes(root: pyhit.Node) -> List[pyhit.Node]:
"""Return a list of children nodes that will either have or need ids."""
nodes = []
for node in root.children[0].descendants:
# Ensure we only grab blocks that contain specification vars.
if node.get("type") is None:
continue
nodes.append(node)
return nodes
def indexnodes(file_paths: List[AnyStr]) -> StrictDict:
"""Return dictionary containing a list of nodes for every file."""
node_dict = StrictDict()
for file_path in file_paths:
root = pyhit.load(file_path)
node_dict[(file_path, root)] = fetchnodes(root)
return node_dict
def indexids(node_dict: StrictDict) -> StrictDict:
"""Return a dictionary of ids containing file and line info."""
id_dict = StrictDict()
for (file_path, _), nodes in node_dict.items():
for node in nodes:
unique_id = node.get("unique_id")
if unique_id is None:
continue
else:
id_dict[unique_id] = (file_path, node.line("unique_id"))
return id_dict
def writeids(node_dict: StrictDict, id_dict: StrictDict) -> int:
"""Return number of files written that needed a hashed id."""
num = 0
for (file_path, root), nodes in node_dict.items():
# Assume we won't need to write any new files
write_p = False
for node in nodes:
if node.get('unique_id') is None:
hash_str = hashnode(node)
node['unique_id'] = hash_str
id_dict[hash_str] = (file_path, node.line("unique_id"))
write_p = True
if write_p:
pyhit.write(file_path, root)
num += 1
return num
def main():
"""Driving function for script."""
# Make sure to run script in root of BISON.
assessment_specs = glob("./assessment/**/*/assessment", recursive=True)
spec_dict = indexnodes(assessment_specs)
id_dict = indexids(spec_dict)
num_files_written = writeids(spec_dict, id_dict)
if num_files_written > 0:
print("Your code requires assessment file changes.")
print("You can run ./scripts/unique_assessment_id.py in the top level of your repository.")
print("Then commit the changes and resubmit.")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
</code></pre>
|
[] |
[
{
"body": "<h2>Generators</h2>\n<p>In this:</p>\n<pre><code>nodes = []\nfor node in root.children[0].descendants:\n # Ensure we only grab blocks that contain specification vars.\n if node.get("type") is None:\n continue\n nodes.append(node)\nreturn nodes\n</code></pre>\n<p>you do not need to construct a list like this. Instead, perhaps</p>\n<pre><code>return (\n node for node in root.children[0].descendants\n if node.get('type') is not None\n)\n</code></pre>\n<p>This will remain a generator until it is materialized to a <code>list</code> or <code>tuple</code>, etc., which you might not need if you iterate over the results once.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T19:56:25.447",
"Id": "479789",
"Score": "0",
"body": "Suppose I'm trying to modify those nodes placed in the generator. If I loop through the generator and modify those nodes, will it be saved in memory when I later write the modifications to the file?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T19:58:14.143",
"Id": "479790",
"Score": "0",
"body": "I'm not completely clear on what you're asking, but you can either cast to a `list`, modify it and then write to a file; or you can iterate to a second generator with your modifications and then write to a file. The first method requires O(n) in memory and the second O(1)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T16:14:25.350",
"Id": "479887",
"Score": "1",
"body": "Great, followed your advice and was able to refactor so I only iterate once. I totally forgot that generators get \"used up\" after looping through them. Thanks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T16:56:30.960",
"Id": "244395",
"ParentId": "244388",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244395",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T15:47:55.860",
"Id": "244388",
"Score": "2",
"Tags": [
"python",
"file-system",
"hashcode"
],
"Title": "Checking hierarchical config files for hashed id and informing the user of changes"
}
|
244388
|
<p>I needed a tool to monitor VM's running on my server in relatively real-time (similar to <code>top</code> or the many variants out there). The main things I need to keep track of are:</p>
<ul>
<li><p>All VM's listed via <code>virsh list --all</code>;</p>
<pre class="lang-none prettyprint-override"><code> Id Name State
----------------------------------------------------
13 Experiments-Proxy running
- Experiments-PHP shut off
- Experiments-Python shut off
</code></pre>
</li>
<li><p>All networks listed via <code>virsh net-list --all</code>;</p>
<pre class="lang-none prettyprint-override"><code> Name State Autostart Persistent
----------------------------------------------------------
default inactive yes yes
net_10_1_1_0 active yes yes
net_10_1_2_0 active yes yes
net_10_1_3_0 active yes yes
</code></pre>
</li>
<li><p>All storage pools listed via <code>virsh pool-list --all</code>;</p>
<pre class="lang-none prettyprint-override"><code> Name State Autostart
-------------------------------------------
Experiments active yes
images active yes
</code></pre>
</li>
</ul>
<p>To do this, I built a small Python script using curses that effectively does three things:</p>
<ol>
<li>Lists all the aforementioned components;</li>
<li>Updates the list on a regular basis (every 2 seconds, basically);</li>
<li>Allows basic management of the aforementioned components (start, stop);</li>
</ol>
<p>All of this is rather simple, if long and convoluted.</p>
<p>To start with, I built a function that runs the <code>virsh</code> command with the arguments I need to. I discarded the error output because I honestly don't care about it for this tool.</p>
<pre><code>def virsh(command, arg):
out, _ = subprocess.Popen(['virsh', command, arg], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
out = re.split('[\r\n]+', out.decode("utf-8"))
return list(map(lambda line: list(map(lambda x: x.strip(), re.split('\\s{2,}', line))), out))
</code></pre>
<p>This allows me to do something like the following further on in the script:</p>
<pre><code>vms = virsh('list', '--all')[2:][:-1]
nets = virsh('net-list', '--all')[2:][:-1]
pools = virsh('pool-list', '--all')[2:][:-1]
</code></pre>
<p>Next, I needed a way to print a table in curses. This went relatively smooth as well, as all I did was push a list of columns and items into a function, with a few extra parameters:</p>
<pre><code>def print_table(stdscr, head_color, sel_color, sel_i, x, y, cols, gray_sel, items):
total_len = sum(list(map(lambda col: col[1] + 1, cols)))
stdscr.insstr(y, x, ' ' * total_len, head_color)
col_offset = 0
if sel_i > -1:
stdscr.addstr(y + sel_i + 1, x, ' ' * total_len, sel_color)
c = 0
for (name, minsize, gray) in cols:
stdscr.addstr(y, x + col_offset, name, head_color)
i = 1
for item in items:
color_offset = 1 if sel_i == (i - 1) else 0
color = curses.color_pair(color_offset)
gray_color = curses.color_pair(color_offset + (3 if gray_sel(item) else 0))
stdscr.addstr(y + i, x + col_offset, item[c], gray_color if gray else color)
i += 1
col_offset += minsize + 1
c += 1
</code></pre>
<p>Next, I needed to print a "help" at the bottom of the screen. For this I simply list each keystroke / command, and a single word about what it does. I might have a list like <code>[("TAB", "Next"), ("F1", "Start"), ("F2", "Stop"), ("F10", "Quit")]</code>:</p>
<pre><code>def print_help(stdscr, help_color, helps):
height, width = stdscr.getmaxyx()
stdscr.insstr(height - 1, 0, ' ' * width, help_color)
max_len = max(list(map(lambda x: len(x[1]), helps))) + 1
offset = 0
for (key, name) in helps:
stdscr.insstr(height - 1, offset, key)
stdscr.insstr(height - 1, offset + len(key), name, help_color)
offset += len(key) + max_len
</code></pre>
<p>The next step is running all the logic to render the screen. For this, I built a <code>render</code> function that takes all the parameters I need:</p>
<pre><code>def set_x_for_yes(x): return 'X' if x == 'yes' else ' '
def render(stdscr, vms, nets, pools, sel, sel_i):
pool_diff = 2
longest_net = max(list(map(lambda net: len(net[0]), nets)))
longest_pool = max(list(map(lambda pool: len(pool[0]), pools)))
longest_net = max(longest_net, longest_pool - pool_diff)
height, width = stdscr.getmaxyx()
net_offset = width - longest_net - 9 - pool_diff - 3
vm_width = net_offset - 3 - 9 - 1 - 2
vm_table = [("ID", 3, False), ("VM", vm_width - 1, True), ("STATUS", 9, False)]
net_table = [("NET", longest_net, True), ("STATUS", 8, False), ("A", 1, False), ("P", 1, False)]
pool_table = [("POOL", longest_net + pool_diff, True), ("STATUS", 8, False), ("A", 1, False)]
nets = list(map(lambda net: [net[0], net[1], set_x_for_yes(net[2]), set_x_for_yes(net[3])], nets))
pools = list(map(lambda pool: [pool[0], pool[1], set_x_for_yes(pool[2])], pools))
tables = [
(0, 0, 0, vm_table, lambda vm: vm[2] != "running", vms),
(1, net_offset, 0, net_table, lambda net: net[1] != "active", nets),
(2, net_offset, len(nets) + 2, pool_table, lambda pool: pool[1] != "active", pools)
]
head_color = curses.color_pair(2)
sel_color = curses.color_pair(1)
for (sel_c, x, y, table, sel_test, items) in tables:
print_table(stdscr, head_color, sel_color, sel_i if sel == sel_c else -1, x, y, table, sel_test, items)
print_help(
stdscr,
curses.color_pair(1),
[("TAB", "Next"), ("F1", "Start"), ("F2", "Stop"), ("F10", "Quit")])
</code></pre>
<p>This builds up all the components to pass to the rendering functions.</p>
<p>Lastly, I have a <code>main</code> function that I use <code>curses.wrapper</code> to run. This allows curses to setup all the screen components, and clean the screen up when it ends (either with success or failure):</p>
<pre><code>def main(stdscr):
curses.curs_set(0)
curses.halfdelay(20)
curses.start_color()
curses.use_default_colors()
curses.init_pair(1, 0, 6)
curses.init_pair(2, 0, 2)
curses.init_pair(3, 8, -1)
curses.init_pair(4, 8, 6)
sel = 0
sel_i = 0
start_commands = ['start', 'net-start', 'pool-start']
stop_commands = ['destroy', 'net-destroy', 'pool-destroy']
while True:
vms = virsh('list', '--all')[2:][:-1]
nets = virsh('net-list', '--all')[2:][:-1]
pools = virsh('pool-list', '--all')[2:][:-1]
args = [vms, nets, pools]
arg_indexes = [1, 0, 0]
stdscr.clear()
render(stdscr, vms, nets, pools, sel, sel_i)
stdscr.refresh()
c = stdscr.getch()
if c == curses.KEY_F10:
exit()
elif c == ord('\t'):
sel = 0 if sel == 2 else sel + 1
elif c == curses.KEY_DOWN or c == curses.KEY_UP:
sel_i += -1 if c == curses.KEY_UP else 1
elif (c == curses.KEY_F1 or c == curses.KEY_F2) and sel_i < len(args[sel]):
commands = stop_commands if c == curses.KEY_F2 else start_commands
virsh(commands[sel], args[sel][sel_i][arg_indexes[sel]])
if sel_i == -1:
sel_i += 1
if sel_i >= len(args[sel]):
sel_i = len(args[sel]) - 1
curses.wrapper(main)
</code></pre>
<p>This also has all the key-handling logic to adjust the scene.</p>
<p>I have yet to set up scrolling on each table, but that is beyond the scope of this question.</p>
<p>Once all is said and done, running the script gives me an output of the following:</p>
<p><a href="https://i.stack.imgur.com/lOBIg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lOBIg.png" alt="virsh-monitor result" /></a></p>
<p>Any and all comments welcome. I don't have any PEP-8 flags in PyChar, so I'm thinking I'm already off to a good start here.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T11:59:37.633",
"Id": "479844",
"Score": "0",
"body": "Not using the libvirt Python API?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T12:13:06.867",
"Id": "479845",
"Score": "1",
"body": "@MichaelHampton Didn't know there was one, but that would make a valid answer. ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T13:00:37.693",
"Id": "479851",
"Score": "0",
"body": "Unfortunately Python is not a language I'm particularly strong in, so I may have to pass that on to someone else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T22:41:23.350",
"Id": "479927",
"Score": "2",
"body": "@MichaelHampton If you're interested, I posted an answer converting this to the libvirt API"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T16:18:03.340",
"Id": "481257",
"Score": "1",
"body": "Is this something you're willing to release in a public repo? I'd be interested in using it if you do"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T16:19:47.307",
"Id": "481258",
"Score": "1",
"body": "@CanadianLuke I actually already did ;) https://github.com/ellersoft/virsh-monitor"
}
] |
[
{
"body": "<h2>Subprocess</h2>\n<pre><code>out, _ = subprocess.Popen(['virsh', command, arg], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()\n</code></pre>\n<p>is a little clunky; consider</p>\n<pre><code>def virsh(*args):\n out = subprocess.check_output(('virsh', *args))\n</code></pre>\n<p>This will also:</p>\n<ul>\n<li>check for the error level after execution</li>\n<li>allow for an arbitrary number of command-line arguments</li>\n</ul>\n<h2>Comprehensions</h2>\n<p>Let's see if we can translate this:</p>\n<pre><code>list(\n map(\n lambda line: list(\n map(\n lambda x: x.strip(), re.split('\\\\s{2,}', line)\n )\n ), \n out\n )\n)\n</code></pre>\n<p>from the old functional style to the new comprehension style. I also had to expand the above because it was a golfed nightmare.</p>\n<pre><code>[\n [\n x.strip()\n for x in re.split(r'\\s{2,}', line)\n ]\n for line in out\n]\n</code></pre>\n<p>Also note the use of a raw string for your regex.</p>\n<p>Similarly, this:</p>\n<pre><code>sum(list(map(lambda col: col[1] + 1, cols)))\n</code></pre>\n<p>can be</p>\n<pre><code>sum(col[1] + 1 for col in cols)\n</code></pre>\n<h2>Type hints</h2>\n<p>This:</p>\n<pre><code>def print_table(stdscr, head_color, sel_color, sel_i, x, y, cols, gray_sel, items):\n</code></pre>\n<p>could really benefit from them. For instance, maybe <code>x</code> and <code>y</code> are <code>x: int, y: int</code>.</p>\n<h2>Enumerate</h2>\n<pre><code> i = 1\n for item in items:\n # ...\n i += 1\n</code></pre>\n<p>should be</p>\n<pre><code>for i, item in enumerate(items):\n</code></pre>\n<h2>Implicit tuple unpack</h2>\n<pre><code>for (name, minsize, gray) in cols:\n</code></pre>\n<p>does not need parens.</p>\n<h2>Else-after-exit</h2>\n<pre><code> exit()\n elif c == ord('\\t'):\n</code></pre>\n<p>does not need an <code>elif</code>; an <code>if</code> will suffice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T15:49:14.690",
"Id": "479882",
"Score": "0",
"body": "2 nitpicks—1. nothing wrong with the functional style *except* forcing the generators to materialize as lists; I would let everything be lazy where possible (and formatting helps, too). 2. The elif does a far better job conveying the *structure* of the program, even if an if would suffice. Just at a glance, and elif chain tells me I dont have to examine in detail every branch to find the control flow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T15:54:54.673",
"Id": "479883",
"Score": "0",
"body": "@D.BenKnoble Re. lazy - I was aiming for direct equivalence, where a generator would not be. The OP uses the outputs of that comprehension in `render` in a manner incompatible with a generator since they're consumed more than once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T16:09:52.640",
"Id": "479886",
"Score": "0",
"body": "fair enough: didn’t read that part too closely."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T16:45:09.463",
"Id": "244393",
"ParentId": "244390",
"Score": "14"
}
},
{
"body": "<h1>Style</h1>\n<p>Your style is quite good, but you can tell that the code isn't written by a Pythonista.</p>\n<ul>\n<li><p>Whilst line length can be a touchy subject, it's mostly left at 79 if you follow PEP 8 or 90 if you're running Black.<br />\nThis is causing me to have a suboptimal experience editing your code.</p>\n</li>\n<li><p>Defining functions on one line, like <code>set_x_for_yes</code>, are normally big no-nos.</p>\n</li>\n<li><p>I'm not a fan of your single letter variables. But I'm also not entirely sure what I'd replace most of them with.</p>\n</li>\n<li><p>(Potential religious war) The 'Pythonic' form of <code>list(map(...))</code> is a list comprehension.\nFor example in <code>virsh</code> we can use:</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>return list(map(lambda line: list(map(lambda x: x.strip(), re.split('\\\\s{2,}', line))), out))\n</code></pre>\n</blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>return [\n [x.strip() for x in re.split('\\\\s{2,}', line)]\n for line in out\n]\n</code></pre>\n</li>\n<li><p>Like most interpreted languages there is no 'main' entry point.\nAs the code is interpreted from top to bottom.\nHowever sometimes we don't want code to run if it is not the 'main' script.\nTo deal with this we can use an <code>if __name__ == '__main__'</code> guard to prevent this code running if you import it.</p>\n</li>\n<li><p>Python is quite allergic to chaining, and so it's common for the <code>subprocess.Popen</code> and <code>.communicate()</code> chain to be split across two assignments.</p>\n<pre class=\"lang-py prettyprint-override\"><code>proc = subprocess.Popen(\n ['virsh', command, arg],\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT\n)\nout, _ = proc.communicate()\n</code></pre>\n</li>\n<li><p>Having unneeded parentheses are really discouraged as they impede readability.</p>\n</li>\n</ul>\n<h1>Changes</h1>\n<ul>\n<li><p>In <code>print_table</code>, converting the iterator returned from <code>map</code> to a <code>list</code> is unneeded.\nAdditionally we can opt to use a generator expression instead.\nThis is the same as the list comprehension before except it is wrapped in parentheses <code>()</code> and builds a generator.\nPython has some sugar when a generator expression is the only argument to a function and lets you drop the double parentheses <code>()</code>.</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>sum(list(map(lambda col: col[1] + 1, cols)))\n</code></pre>\n</blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>sum(col[1] + 1 for col in cols)\n</code></pre>\n</li>\n<li><p>In <code>print_table</code>, it's nice to see you using the <code>' ' * total_len</code> sugar.</p>\n</li>\n<li><p>In <code>print_table</code>, we can use <code>enumerate</code> rather than manually looping through <code>c</code> and <code>i</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i, item in enumerate(items, 1):\n</code></pre>\n</li>\n<li><p>In <code>print_table</code>, rather than using a turnery to build 1 or 0, you can just use <code>int</code>.\nI would also be surprised if the functions don't support taking a bool in-place for an integer.</p>\n</li>\n<li><p>In <code>print_table</code>, <code>col_offset</code> is only ever used as <code>x + col_offset</code>. At which point you might as well just update <code>x</code>.</p>\n</li>\n<li><p>In <code>print_table</code>, you can merge the <code>if grey else</code> turnery into the <code>gray_color</code> line to build the correct colour with less lines of code.</p>\n</li>\n</ul>\n<p>Additional changes not made to the below code:</p>\n<ul>\n<li><p>It would be nice to add an Enum to make building the colour pairs easier. By using an <code>IntFlag</code> we can get the benefits of it acting like an int and act like flags.\nHowever your current mapping makes this hard.\nI would change it so the last bit is to change if the colour is grey.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Colours(enum.IntFlag):\n DEFAULT = 0\n GRAY = 1\n SELECT = 2\n HEAD = 4\n</code></pre>\n<p>This has a couple of benefits:</p>\n<ol>\n<li>If you decide to later change what the values are it is easier.</li>\n<li>We can use <code>Colours.DEFAULT</code> or <code>Colours.SELECT | Colours.GRAY</code> to select the wanted colours.</li>\n<li>It means we can change <code>print_help</code> to not use magic numbers.</li>\n</ol>\n</li>\n<li><p>In <code>render</code>, I would rearrange a lot of the table information.</p>\n<p>The following values never change:</p>\n<ul>\n<li>Headers.</li>\n<li>Which columns can be grey.</li>\n<li>Mutations (<code>set_x_for_yes</code>) to the items.</li>\n<li>Selecting grey rows, <code>gray_sel</code> / <code>sel_test</code>.</li>\n</ul>\n<p>Values that can change each run:</p>\n<ul>\n<li>The x position.</li>\n<li>The y position.</li>\n<li>The items.</li>\n<li>The width of each column.</li>\n</ul>\n<p>And so I would move all the constants outside of the function.\nWe can join these two tables together with <code>zip</code>.</p>\n</li>\n<li><p>In <code>print_table</code>, you can remove the need for the two calls to <code>stdscr.insstr</code> with the value <code>' ' * total_len</code> if you pad the values.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> '{1:<{0}}|{2:^{0}}|{3:>{0}}'.format(5, 1, 2, 3)\n'1 | 2 | 3'\n</code></pre>\n</li>\n<li><p>A lot of <code>print_table</code> is not actually about printing the table it's about colouring it correctly.\nI would build another function that correctly colours everything.</p>\n<ul>\n<li>If we change each item to a tuple of the item's string and the item's colour than it is easier to print the entire table.</li>\n<li>If we include the headers in this function we can format everything correctly, and make <code>print_table</code> a very simple nested for loop.</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>def select_colors(values, sel_i, gray_sel, grays):\n for i, row in enumerate(values):\n gray_row = gray_sel(row)\n new_row = []\n for item, gray in zip(row, grays):\n color = Colours.SELECT if sel_i == i else Colours.DEFAULT\n if gray_row and gray:\n color |= Colours.GRAY\n if i == 0:\n color = Colours.HEAD\n new_row.append((item, curses.color_pair(color)))\n yield new_row\n</code></pre>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>import subprocess\nimport re\nimport time\nimport curses\n\n\ndef virsh(command, arg):\n proc = subprocess.Popen(\n ['virsh', command, arg],\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT\n )\n out, _ = proc.communicate()\n return [\n [\n x.strip()\n for x in re.split('\\\\s{2,}', line)\n ]\n for line in re.split('[\\r\\n]+', out.decode("utf-8"))\n ]\n\n\ndef print_table(stdscr, head_color, sel_color, sel_i, x, y, cols, gray_sel, items):\n total_len = sum(col[1] + 1 for col in cols)\n stdscr.insstr(y, x, ' ' * total_len, head_color)\n if sel_i > -1:\n stdscr.addstr(y + sel_i + 1, x, ' ' * total_len, sel_color)\n\n for c, (name, minsize, gray) in enumerate(cols):\n stdscr.addstr(y, x, name, head_color)\n for i, item in enumerate(items, 1):\n color = curses.color_pair(\n sel_i == (i - 1)\n + (3 if gray and gray_sel(item) else 0)\n )\n stdscr.addstr(y + i, x, item[c], color)\n x += minsize + 1\n\n\ndef print_help(stdscr, help_color, helps):\n height, width = stdscr.getmaxyx()\n stdscr.insstr(height - 1, 0, ' ' * width, help_color)\n max_len = max(len(h[1]) for h in helps) + 1\n offset = 0\n for key, name in helps:\n stdscr.insstr(height - 1, offset, key)\n stdscr.insstr(height - 1, offset + len(key), name, help_color)\n offset += len(key) + max_len\n\n\ndef set_x_for_yes(x):\n return 'X' if x == 'yes' else ' '\n\n\ndef render(stdscr, vms, nets, pools, sel, sel_i):\n pool_diff = 2\n longest_net = max(len(net[0]) for net in nets)\n longest_pool = max(len(pool[0]) for pool in pools)\n longest_net = max(longest_net, longest_pool - pool_diff)\n height, width = stdscr.getmaxyx()\n net_offset = width - longest_net - 9 - pool_diff - 3\n vm_width = net_offset - 3 - 9 - 1 - 2\n\n vm_table = [("ID", 3, False), ("VM", vm_width - 1, True), ("STATUS", 9, False)]\n net_table = [("NET", longest_net, True), ("STATUS", 8, False), ("A", 1, False), ("P", 1, False)]\n pool_table = [("POOL", longest_net + pool_diff, True), ("STATUS", 8, False), ("A", 1, False)]\n nets = [\n [net[0], net[1], set_x_for_yes(net[2]), set_x_for_yes(net[3])]\n for net in nets\n ]\n pools = [\n [pool[0], pool[1], set_x_for_yes(pool[2])]\n for pool in pools\n ]\n\n tables = [\n (0, 0, 0, vm_table, lambda vm: vm[2] != "running", vms),\n (1, net_offset, 0, net_table, lambda net: net[1] != "active", nets),\n (2, net_offset, len(nets) + 2, pool_table, lambda pool: pool[1] != "active", pools)\n ]\n\n head_color = curses.color_pair(2)\n sel_color = curses.color_pair(1)\n for (sel_c, x, y, table, sel_test, items) in tables:\n print_table(stdscr, head_color, sel_color, sel_i if sel == sel_c else -1, x, y, table, sel_test, items)\n\n print_help(\n stdscr,\n curses.color_pair(1),\n [("TAB", "Next"), ("F1", "Start"), ("F2", "Stop"), ("F10", "Quit")]\n )\n\n\ndef main(stdscr):\n curses.curs_set(0)\n curses.halfdelay(20)\n curses.start_color()\n curses.use_default_colors()\n curses.init_pair(1, 0, 6)\n curses.init_pair(2, 0, 2)\n curses.init_pair(3, 8, -1)\n curses.init_pair(4, 8, 6)\n sel = 0\n sel_i = 0\n\n start_commands = ['start', 'net-start', 'pool-start']\n stop_commands = ['destroy', 'net-destroy', 'pool-destroy']\n\n while True:\n vms = virsh('list', '--all')[2:][:-1]\n nets = virsh('net-list', '--all')[2:][:-1]\n pools = virsh('pool-list', '--all')[2:][:-1]\n\n args = [vms, nets, pools]\n arg_indexes = [1, 0, 0]\n\n stdscr.clear()\n render(stdscr, vms, nets, pools, sel, sel_i)\n stdscr.refresh()\n c = stdscr.getch()\n\n if c == curses.KEY_F10:\n exit()\n elif c == ord('\\t'):\n sel = 0 if sel == 2 else sel + 1\n elif c == curses.KEY_DOWN or c == curses.KEY_UP:\n sel_i += -1 if c == curses.KEY_UP else 1\n elif (c == curses.KEY_F1 or c == curses.KEY_F2) and sel_i < len(args[sel]):\n commands = stop_commands if c == curses.KEY_F2 else start_commands\n virsh(commands[sel], args[sel][sel_i][arg_indexes[sel]])\n\n if sel_i == -1:\n sel_i += 1\n if sel_i >= len(args[sel]):\n sel_i = len(args[sel]) - 1\n\n\nif __name__ == '__main__':\n curses.wrapper(main)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T18:14:10.790",
"Id": "479782",
"Score": "0",
"body": "_Potential religious war_ - Based on the (infamous?) relegation of `reduce` to `functools` and the reasoning for that change, I think you, most of the Python community and I are on the right side of history when it comes to discouraging `map`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T18:18:56.737",
"Id": "479783",
"Score": "1",
"body": "@Reinderien Indeed. I am trying to to start to mark 'problematic' suggestions. I'm hoping that acknowledging that it's a source for confrontation will help reduce the amount of confrontation I get when a user disregards the advice :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T19:58:06.807",
"Id": "479901",
"Score": "0",
"body": "At least on my machine this fails to highlight the correct 'machine' (see https://asciinema.org/a/jOrs6moLiwB2Vf2QI6pFaPLWh?t=7). I found the faulty code and reverted it in my answer below."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T20:01:22.560",
"Id": "479903",
"Score": "1",
"body": "@larkey Yeah I noticed that after posting but during changing to `string.Formatter`. I thought I'd added it here, but I didn't. The fix is quite simple really `(sel_i == (i - 1))` because I got the precedence wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T22:36:18.163",
"Id": "479925",
"Score": "0",
"body": "@Peilonrayz Ah, I guessed something like that but was too tired and don't have enough python skill to dig deeper :) I'll update my answer then!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T17:20:11.643",
"Id": "244398",
"ParentId": "244390",
"Score": "10"
}
},
{
"body": "<h1>Custom Formatter</h1>\n<p>Half way through <a href=\"https://codereview.stackexchange.com/a/244398\">my previous answer</a> I decided to integrate Python's <a href=\"https://docs.python.org/3/library/string.html#formatspec\" rel=\"noreferrer\">Format Specification Mini-Language</a>. I had originally thought there was a lot more formatting going on, but this was not the case. It has a few benefits, but also a few deficits.</p>\n<p>Pros:</p>\n<ul>\n<li>It's using syntax that should be in every Python programmers toolbox.</li>\n<li>It forced me to split <code>print_table</code> into two functions. Because the formatting was moved inside the class. And then later I moved it out into <code>select_colors</code>.</li>\n<li>If you are building more tables it's really quite powerful.</li>\n</ul>\n<p>Cons:</p>\n<ul>\n<li>You are unlikely to know this mini-language.</li>\n<li>You're not really using any of the power it brings.</li>\n<li>The method <code>_cformat</code> is long and filled with boilerplate.</li>\n<li>You can definitely write the code in fewer lines of code without it.</li>\n</ul>\n<p>Whilst it is probably not the best solution for this code it's at least interesting. And can help if you need more advanced formats.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import curses\nimport enum\nimport re\nimport string\nimport subprocess\nimport time\n\n\nclass Colours(enum.IntFlag):\n DEFAULT = 0\n GRAY = 1\n SELECT = 2\n HEAD = 4\n\n\nclass CursedFormatter(string.Formatter):\n def __init__(self, stdscr, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._stdscr = stdscr\n \n def _cformat(self, format_string, args, kwargs, index=0):\n result = []\n for pre, name, spec, conversion in self.parse(format_string):\n if name is None:\n result.append((pre,))\n else:\n if name == '':\n if index is False:\n raise ValueError('cannot switch from manual field specification to automatic field numbering')\n name = str(index)\n index += 1\n elif name.isdigit():\n if index:\n raise ValueError('cannot switch from manual field specification to automatic field numbering')\n index = False\n obj, _ = self.get_field(name, args, kwargs)\n if isinstance(obj, tuple):\n obj, *a = obj\n else:\n a = ()\n obj = self.convert_field(obj, conversion)\n spec, index = super()._vformat(spec, args, kwargs, set(), 1, auto_arg_index=index)\n result.append((self.format_field(obj, spec),) + tuple(a))\n return result, index\n\n def vformat(self, fmt, args, kwargs):\n return ''.join(\n value\n for value, *_ in self._cformat(fmt, args, kwargs)[0]\n )\n\n def _makestr(self, fn, fmt, args, kwargs):\n values, _ = self._cformat(fmt, args, kwargs)\n x = kwargs.get('x', 0)\n y = kwargs.get('y', 0)\n result = []\n for value in values:\n self._stdscr.insstr(y, x, *value)\n x += len(value[0])\n result.append(value[0])\n return ''.join(result)\n\n def insstr(self, fmt, *args, **kwargs):\n return self._makestr(self._stdscr.insstr, fmt, args, kwargs)\n \n def addstr(self, fmt, *args, **kwargs):\n return self._makestr(self._stdscr.addstr, fmt, args, kwargs)\n\n\ndef virsh(command, arg):\n proc = subprocess.Popen(\n ['virsh', command, arg],\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT\n )\n out, _ = proc.communicate()\n return [\n [\n x.strip()\n for x in re.split('\\\\s{2,}', line)\n ]\n for line in re.split('[\\r\\n]+', out.decode("utf-8"))\n ]\n\n\ndef select_colors(values, sel_i, gray_sel, grays):\n for i, row in enumerate(values):\n gray_row = gray_sel(row)\n new_row = []\n for item, gray in zip(row, grays):\n color = Colours.SELECT if sel_i == i else Colours.DEFAULT\n if gray_row and gray:\n color |= Colours.GRAY\n if i == 0:\n color = Colours.HEAD\n new_row.append((item, curses.color_pair(color)))\n yield new_row\n\n\ndef print_table(stdscr, fmt, values, x, y):\n for i, row in enumerate(values):\n CursedFormatter(stdscr).addstr(fmt, *row, x=x, y=y + i)\n\n\ndef print_help(stdscr, helps):\n height, width = stdscr.getmaxyx()\n help_color = curses.color_pair(Colours.SELECT)\n CF = CursedFormatter(stdscr)\n CF.insstr('{}', (' ' * width, help_color), x=0, y=height - 1)\n max_len = max(len(h[1]) for h in helps) + 1\n offset = 0\n for key, name in helps:\n CF.insstr('{}{:<{}}', key, (name, help_color), max_len, x=offset, y=height - 1)\n offset += len(key) + max_len\n\n\ndef set_x_for_yes(x):\n return 'X' if x == 'yes' else ' '\n\n\ndef echo(x):\n return x\n\n\nTABLES = [\n (\n ['ID', 'VM', 'STATUS'],\n [False, True, False],\n [echo, echo, echo],\n lambda vm: vm[2] != 'running',\n ),\n (\n ['NET', 'STATUS', 'A', 'P'],\n [True, False, False, False],\n [echo, echo, set_x_for_yes, set_x_for_yes],\n lambda net: net[1] != "active",\n ),\n (\n ['POOL', 'STATUS', 'A'],\n [True, False, False],\n [echo, echo, set_x_for_yes],\n lambda pool: pool[1] != "active",\n ),\n]\n\n\ndef render(stdscr, vms, nets, pools, sel, sel_i):\n pool_diff = 2\n longest_net = max(len(net[0]) for net in nets)\n longest_pool = max(len(pool[0]) for pool in pools)\n longest_net = max(longest_net, longest_pool - pool_diff)\n height, width = stdscr.getmaxyx()\n net_offset = width - longest_net - 9 - pool_diff - 3\n vm_width = net_offset - 3 - 9 - 1 - 2\n\n tables = [\n (\n 0,\n 0,\n vms,\n (4, vm_width, 10)\n ),\n (\n net_offset,\n 0,\n nets,\n (longest_net + 1, 9, 2, 2)\n ),\n (\n net_offset,\n len(nets) + 2,\n pools,\n (longest_net + pool_diff + 1, 9, 2)\n ),\n ]\n for (\n i,\n (\n (x, y, items, widths),\n (header, grays, maps, gray_test)\n ),\n ) in enumerate(zip(tables, TABLES)):\n values = (\n [header]\n + [\n [tran(item) for tran, item in zip(maps, row)]\n for row in items\n ]\n )\n selected = sel_i + 1 if sel == i else -1\n values = select_colors(values, selected, gray_test, grays)\n fmt = ''.join(f'{{:<{width}}}' for width in widths)\n print_table(stdscr, fmt, values, x, y)\n\n print_help(\n stdscr,\n [("TAB", "Next"), ("F1", "Start"), ("F2", "Stop"), ("F10", "Quit")]\n )\n\n\ndef main(stdscr):\n curses.curs_set(0)\n curses.halfdelay(20)\n curses.start_color()\n curses.use_default_colors()\n curses.init_pair(Colours.GRAY, 8, -1)\n curses.init_pair(Colours.SELECT, 0, 6)\n curses.init_pair(Colours.SELECT | Colours.GRAY, 8, 6)\n curses.init_pair(Colours.HEAD, 0, 2)\n curses.init_pair(Colours.HEAD | Colours.GRAY, 8, 2)\n sel = 0\n sel_i = 0\n\n start_commands = ['start', 'net-start', 'pool-start']\n stop_commands = ['destroy', 'net-destroy', 'pool-destroy']\n\n while True:\n vms = virsh('list', '--all')[2:][:-1]\n nets = virsh('net-list', '--all')[2:][:-1]\n pools = virsh('pool-list', '--all')[2:][:-1]\n\n args = [vms, nets, pools]\n arg_indexes = [1, 0, 0]\n\n stdscr.clear()\n render(stdscr, vms, nets, pools, sel, sel_i)\n stdscr.refresh()\n c = stdscr.getch()\n\n if c == curses.KEY_F10:\n exit()\n elif c == ord('\\t'):\n sel = 0 if sel == 2 else sel + 1\n elif c == curses.KEY_DOWN or c == curses.KEY_UP:\n sel_i += -1 if c == curses.KEY_UP else 1\n elif (c == curses.KEY_F1 or c == curses.KEY_F2) and sel_i < len(args[sel]):\n commands = stop_commands if c == curses.KEY_F2 else start_commands\n virsh(commands[sel], args[sel][sel_i][arg_indexes[sel]])\n\n if sel_i == -1:\n sel_i += 1\n if sel_i >= len(args[sel]):\n sel_i = len(args[sel]) - 1\n\n\nif __name__ == '__main__':\n curses.wrapper(main)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T12:13:29.197",
"Id": "479846",
"Score": "0",
"body": "I don't think I would use the formatter, but it's interesting to see the approach here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T12:19:48.737",
"Id": "479847",
"Score": "0",
"body": "@DerKommissar Understandable, you should be able to replace it with a very simple function since the format segments, values and colours are all well formed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T00:14:42.777",
"Id": "244416",
"ParentId": "244390",
"Score": "5"
}
},
{
"body": "<h1>Bugs</h1>\n<p>There was one bug if no networks or pools existed, then calculation of <code>longest_net</code> and <code>longest_pool</code> respectively would fail, since <code>max()</code> would be called on an empty list. The solution is to add a <code>default</code> kw-arg</p>\n<pre class=\"lang-none prettyprint-override\"><code>- longest_net = max(len(net.name()) for net in nets)\n- longest_pool = max(len(pool.name()) for pool in pools)\n+ longest_net = max((len(net.name()) for net in nets), default=0)\n+ longest_pool = max((len(pool.name()) for pool in pools), default=0)\n</code></pre>\n<h1>Use libvirt API</h1>\n<p>Based on @MichaelHampton's advice I moved the code to the libvirt API, basing off of the changes made in <a href=\"https://codereview.stackexchange.com/a/244398/85095\">the answer by @Peilonrayz</a>.</p>\n<p>The crucial difference is to make a connection to libvirt in <code>__main__</code> (otherwise we'd run into problems with interactive authentication on the console if curses already initialised):</p>\n<pre class=\"lang-none prettyprint-override\"><code> if __name__ == '__main__':\n- curses.wrapper(main)\n+ conn = libvirt.open(None)\n+ curses.wrapper(main, conn)\n</code></pre>\n<p>Then in <code>main(stdscr, conn)</code>:</p>\n<pre class=\"lang-none prettyprint-override\"><code> while True:\n- vms = virsh('list', '--all')[2:][:-1]\n- nets = virsh('net-list', '--all')[2:][:-1]\n- pools = virsh('pool-list', '--all')[2:][:-1]\n+ vms = conn.listAllDomains()\n+ nets = conn.listAllNetworks()\n+ pools = conn.listAllStoragePools()\n</code></pre>\n<p>Other than that it's just moving away from array-of-strings to method calls on libvirt objects, e.g.:</p>\n<pre class=\"lang-none prettyprint-override\"><code>- longest_net = max(len(net[0]) for net in nets)\n- longest_pool = max(len(pool[0]) for pool in pools)\n+ longest_net = max((len(net.name()) for net in nets))\n+ longest_pool = max((len(pool.name()) for pool in pools))\n</code></pre>\n<p>I also needed to create a 'vms' array just like the 'pools' and 'nets' array for <code>print_table</code> now. As this function however operates much on strings while the API returns integer constants, the least-effort approach taken by me was to convert all integers to strings via dictionaries and not touch <code>print_table</code> itself. Particularly <code>virDomain.state()</code> returns <code>[state, reason]</code> with both being integers; in order to pretty-print this I created a dictionary which then can be used like this:</p>\n<pre class=\"lang-python prettyprint-override\"><code>state_string = {\n libvirt.VIR_DOMAIN_NOSTATE: 'nostate',\n libvirt.VIR_DOMAIN_RUNNING: 'running',\n libvirt.VIR_DOMAIN_BLOCKED: 'blocked',\n libvirt.VIR_DOMAIN_PAUSED: 'paused',\n libvirt.VIR_DOMAIN_SHUTDOWN: 'shutdown',\n libvirt.VIR_DOMAIN_SHUTOFF: 'shutoff',\n libvirt.VIR_DOMAIN_CRASHED: 'crashed',\n libvirt.VIR_DOMAIN_PMSUSPENDED: 'pmsuspended',\n}\nprint(state_string[vm.state()[0]])\n</code></pre>\n<p>Similarly, the start/stop is handled via objects which reads much better:</p>\n<pre class=\"lang-none prettyprint-override\"><code>- commands = stop_commands if c == curses.KEY_F2 else start_commands\n- virsh(commands[sel], args[sel][sel_i][arg_indexes[sel]])\n+ if c == curses.KEY_F2:\n+ args[sel][sel_i].destroy()\n+ else:\n+ args[sel][sel_i].create()\n</code></pre>\n<h1>Add other hypervisors</h1>\n<p>As we are now using the libvirt API, it's quite easy to add support for accessing other hypervisors via URI. I used <code>getopt</code> to parse a <code>-c URI</code> CLI argument:</p>\n<pre class=\"lang-none prettyprint-override\"><code> if __name__ == '__main__':\n- conn = libvirt.open(None)\n+ import sys\n+ import getopt\n+ try:\n+ opts, args = getopt.getopt(sys.argv[1:], 'c:')\n+ except getopt.GetoptError as err:\n+ print(err)\n+ sys.exit(1)\n+\n+ uri = None\n+ for o, a in opts:\n+ if o == '-c':\n+ uri = a\n+\n+ try:\n+ conn = libvirt.open(uri)\n+ except libvirt.libvirtError:\n+ print('Failed to open connection to the hypervisor')\n+ sys.exit(1)\n+\n curses.wrapper(main, conn)\n</code></pre>\n<p>This allows to monitor remote hypervisor instances or the system one, e.g.:</p>\n<pre class=\"lang-none prettyprint-override\"><code>$ ./virtop.py -c 'qemu+ssh://username@ip.of.vm.host/system' \n</code></pre>\n<h1>Final code</h1>\n<pre><code>#! /usr/bin/env python3\n\nimport libvirt\nimport curses\n\nstate_string = {\n libvirt.VIR_DOMAIN_NOSTATE: 'nostate',\n libvirt.VIR_DOMAIN_RUNNING: 'running',\n libvirt.VIR_DOMAIN_BLOCKED: 'blocked',\n libvirt.VIR_DOMAIN_PAUSED: 'paused',\n libvirt.VIR_DOMAIN_SHUTDOWN: 'shutdown',\n libvirt.VIR_DOMAIN_SHUTOFF: 'shutoff',\n libvirt.VIR_DOMAIN_CRASHED: 'crashed',\n libvirt.VIR_DOMAIN_PMSUSPENDED: 'pmsuspended',\n}\n\nactive_string = {\n 0: 'inactive',\n 1: 'active',\n}\n\n\ndef print_table(stdscr, head_color, sel_color, sel_i, x, y, cols, gray_sel, items):\n total_len = sum(col[1] + 1 for col in cols)\n stdscr.insstr(y, x, ' ' * total_len, head_color)\n if sel_i > -1:\n stdscr.addstr(y + sel_i + 1, x, ' ' * total_len, sel_color)\n\n for c, (name, minsize, gray) in enumerate(cols):\n stdscr.addstr(y, x, name, head_color)\n for i, item in enumerate(items, 1):\n color = curses.color_pair(\n (sel_i == (i - 1))\n + (3 if gray and gray_sel(item) else 0)\n )\n stdscr.addstr(y + i, x, item[c], color)\n x += minsize + 1\n\n\ndef print_help(stdscr, help_color, helps):\n height, width = stdscr.getmaxyx()\n stdscr.insstr(height - 1, 0, ' ' * width, help_color)\n max_len = max(len(h[1]) for h in helps) + 1\n offset = 0\n for key, name in helps:\n stdscr.insstr(height - 1, offset, key)\n stdscr.insstr(height - 1, offset + len(key), name, help_color)\n offset += len(key) + max_len\n\n\ndef set_x_if_true(x):\n return 'X' if x else ' '\n\n\ndef render(stdscr, vms, nets, pools, sel, sel_i):\n pool_diff = 2\n longest_net = max((len(net.name()) for net in nets), default=0)\n longest_pool = max((len(pool.name()) for pool in pools), default=0)\n longest_net = max(longest_net, longest_pool - pool_diff)\n height, width = stdscr.getmaxyx()\n net_offset = width - longest_net - 9 - pool_diff - 3\n vm_width = net_offset - 3 - 9 - 1 - 2\n\n vm_table = [("ID", 3, False), ("VM", vm_width - 1, True), ("STATUS", 9, False)]\n net_table = [("NET", longest_net, True), ("STATUS", 8, False), ("A", 1, False), ("P", 1, False)]\n pool_table = [("POOL", longest_net + pool_diff, True), ("STATUS", 8, False), ("A", 1, False)]\n vms = [\n ['-' if vm.ID() == -1 else str(vm.ID()), vm.name(), state_string[vm.state()[0]]]\n for vm in vms\n ]\n nets = [\n [net.name(), active_string[net.isActive()], set_x_if_true(net.autostart()), set_x_if_true(net.isPersistent())]\n for net in nets\n ]\n pools = [\n [pool.name(), active_string[pool.isActive()], set_x_if_true(pool.autostart())]\n for pool in pools\n ]\n\n tables = [\n (0, 0, 0, vm_table, lambda vm: vm[2] != state_string[libvirt.VIR_DOMAIN_RUNNING], vms),\n (1, net_offset, 0, net_table, lambda net: net[1] != active_string[1], nets),\n (2, net_offset, len(nets) + 2, pool_table, lambda pool: pool[1] != active_string[1], pools)\n ]\n\n head_color = curses.color_pair(2)\n sel_color = curses.color_pair(1)\n for (sel_c, x, y, table, sel_test, items) in tables:\n print_table(stdscr, head_color, sel_color, sel_i if sel == sel_c else -1, x, y, table, sel_test, items)\n\n print_help(\n stdscr,\n curses.color_pair(1),\n [("TAB", "Next"), ("F1", "Start"), ("F2", "Stop"), ("F10", "Quit")]\n )\n\n\ndef main(stdscr, conn):\n curses.curs_set(0)\n curses.halfdelay(20)\n curses.start_color()\n curses.use_default_colors()\n curses.init_pair(1, 0, 6)\n curses.init_pair(2, 0, 2)\n curses.init_pair(3, 8, -1)\n curses.init_pair(4, 8, 6)\n sel = 0\n sel_i = 0\n\n while True:\n vms = conn.listAllDomains()\n nets = conn.listAllNetworks()\n pools = conn.listAllStoragePools()\n\n args = [vms, nets, pools]\n arg_indexes = [1, 0, 0]\n\n stdscr.clear()\n render(stdscr, vms, nets, pools, sel, sel_i)\n stdscr.refresh()\n c = stdscr.getch()\n\n if c == curses.KEY_F10:\n exit()\n elif c == ord('\\t'):\n sel = 0 if sel == 2 else sel + 1\n elif c == curses.KEY_DOWN or c == curses.KEY_UP:\n sel_i += -1 if c == curses.KEY_UP else 1\n elif (c == curses.KEY_F1 or c == curses.KEY_F2) and sel_i < len(args[sel]):\n if c == curses.KEY_F2:\n args[sel][sel_i].destroy()\n else:\n args[sel][sel_i].create()\n\n if sel_i == -1:\n sel_i += 1\n if sel_i >= len(args[sel]):\n sel_i = len(args[sel]) - 1\n\n\nif __name__ == '__main__':\n import sys\n import getopt\n try:\n opts, args = getopt.getopt(sys.argv[1:], 'c:')\n except getopt.GetoptError as err:\n print(err)\n sys.exit(1)\n\n uri = None\n for o, a in opts:\n if o == '-c':\n uri = a\n\n try:\n conn = libvirt.open(uri)\n except libvirt.libvirtError:\n print('Failed to open connection to the hypervisor')\n sys.exit(1)\n\n curses.wrapper(main, conn)\n</code></pre>\n<h1>Remarks</h1>\n<p>This code is now with almost no error handling and since the libvirt functions may throw exceptions quite often (e.g. when starting if it's already started), this needs to be addressed. Also a <code>usage()</code> function documenting the <code>-c</code> option would be nice, I was too lazy for that. :-)</p>\n<p>I'm personally not so proficient with python and more a C person, so the code might not be the most pythonic.</p>\n<p>Also I can only recommend you looking into virt-manager which is basically what you did here. While it's a GUI solution it allows connecting to remote instances, so your server does not need to run X or Wayland, although a virt-manager-tui would be cool as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T23:08:13.640",
"Id": "479929",
"Score": "1",
"body": "There's also virt-top, which is much less colorful but displays some more information. I tried this code and found that it was slow to respond visually to keyboard input when connected to a remote hypervisor (on another continent). I expect you're loading information about whatever is being selected before updating the display. Other than that it looks really good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T10:37:24.840",
"Id": "479971",
"Score": "0",
"body": "@MichaelHampton Oh, I didn't know about virt-top, but it's not packaged for my distribution (as some dependencies such as libvirt-ocaml aren't either) and seems to be unmaintained anyhow. Ideally one should split input-handling from the model/information a bit better, right now it's difficult to fix that issue. Perhaps __someone__ eventually will pickup on this again. virt-top for reference: http://git.annexia.org/?p=virt-top.git;a=summary"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T12:28:52.043",
"Id": "479985",
"Score": "0",
"body": "@MichaelHampton That issue is because I use `curses.halfdelay(20)` as my timing loop (it waits until 2 seconds or keypress on every `.getch()` call), and my `stdscr.getch()` is only called once, then regardless of whether a use typed a key or not it reloads all the VMs, Networks, and Storage Pools. Going to play with that today, see if I can't speed the rendering up."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T19:52:13.420",
"Id": "244464",
"ParentId": "244390",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "244464",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T15:57:38.183",
"Id": "244390",
"Score": "15",
"Tags": [
"python",
"python-3.x",
"console",
"curses"
],
"Title": "A top-like live monitor for virsh/kvm/qemu VM's"
}
|
244390
|
<p>I'm posting my code for a LeetCode problem copied here. If you have time and would like to review, please do so. Thank you!</p>
<h2>Problem</h2>
<blockquote>
<p>Given a positive integer n, return the number of all possible
attendance records with length n, which will be regarded as
rewardable. The answer may be very large, return it after mod 109 + 7.</p>
<p>A student attendance record is a string that only contains the
following three characters:</p>
<ul>
<li>'A' : Absent.</li>
<li>'L' : Late.</li>
<li>'P' : Present.</li>
</ul>
<p>A record is regarded as rewardable if it doesn't contain more than one
'A' (absent) or more than two continuous 'L' (late).</p>
<h3>Example 1:</h3>
<ul>
<li>Input: n = 2</li>
<li>Output: 8</li>
</ul>
<h3>Explanation:</h3>
<p>There are 8 records with length 2 will be regarded as rewardable:</p>
<ul>
<li><p>"PP" , "AP", "PA", "LP", "PL", "AL", "LA", "LL"</p>
</li>
<li><p>Only "AA" won't be regarded as rewardable owing to more than one absent times.</p>
</li>
<li><p>Note: The value of n won't exceed 100,000.</p>
</li>
</ul>
</blockquote>
<h3>Accepted Code</h3>
<pre><code>class Solution {
public:
static int checkRecord(int edges) {
if (edges == 0) {
return 1;
}
// possible candidates
uint32_t adj_matrix[MATRIX_WIDTH_SQUARED] = {
1, 1, 1, 0, 0, 0,
1, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1,
0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 1, 0,
};
uint32_t a[MATRIX_WIDTH_SQUARED];
uint32_t b[MATRIX_WIDTH_SQUARED];
uint32_t* accumulated = a;
uint32_t* temp = b;
uint32_t* adj_matrix_pointer = adj_matrix;
std::memset(a, 0, sizeof(a));
for (unsigned int node_x = 0; node_x < MATRIX_WIDTH_SQUARED; node_x += MATRIX_WIDTH + 1) {
a[node_x] = 1;
}
// Square
while (edges > 1) {
if (edges & 1) {
matrix_multiply(accumulated, adj_matrix_pointer, temp);
std::swap(temp, accumulated);
}
matrix_multiply(adj_matrix_pointer, adj_matrix_pointer, temp);
std::swap(temp, adj_matrix_pointer);
edges >>= 1;
}
matrix_multiply(adj_matrix_pointer, accumulated, temp);
uint64_t first_col_sum = 0;
// Sum up
for (int node_y = 0; node_y < MATRIX_WIDTH_SQUARED; node_y += MATRIX_WIDTH) {
first_col_sum += temp[node_y];
}
return (uint32_t) (first_col_sum % MODE);
}
private:
static constexpr int MATRIX_WIDTH = 6;
static constexpr int MATRIX_WIDTH_SQUARED = MATRIX_WIDTH * MATRIX_WIDTH;
static constexpr uint64_t MODE = 1000000007UL;
static void matrix_multiply(uint32_t* a, uint32_t* b, uint32_t* c) {
for (unsigned int node_y = 0; node_y < MATRIX_WIDTH; node_y++) {
for (unsigned int node_x = 0; node_x < MATRIX_WIDTH; node_x++) {
uint64_t matrix_multi = 0;
for (unsigned int k = 0; k < MATRIX_WIDTH; k++) {
matrix_multi += (uint64_t) (a[node_y * MATRIX_WIDTH + k]) * (uint64_t) (b[k * MATRIX_WIDTH + node_x]);
matrix_multi %= MODE;
}
c[node_y * MATRIX_WIDTH + node_x] = matrix_multi;
}
}
}
};
</code></pre>
<h3>Reference</h3>
<p>In LeetCode's answer template, there is a class usually named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename.</p>
<ul>
<li><p><a href="https://leetcode.com/problems/student-attendance-record-ii/" rel="nofollow noreferrer">Problem</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/student-attendance-record-ii/discuss/" rel="nofollow noreferrer">Discuss</a></p>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T04:07:52.100",
"Id": "479809",
"Score": "2",
"body": "I suggest you try some of the problems on https://www.hackerrank.com/ to get a little more attention to your questions."
}
] |
[
{
"body": "<p><strong>Use C++ Container Classes</strong><br />\nThis code looks too much like C code and not enough like C++ Code.</p>\n<p>In the modern day C++, the use of raw pointers such as <code>uint32_t* accumulated = a;</code> are frowned upon, and container classes such as <code>std::array</code> and iterators were developed to reduce the use of raw pointers.</p>\n<p>The C style array <code>b</code> is never initialized, and the C style array <code>a</code> is initialized twice.</p>\n<pre><code> std::memset(a, 0, sizeof(a));\n\n for (unsigned int node_x = 0; node_x < MATRIX_WIDTH_SQUARED; node_x += MATRIX_WIDTH + 1) {\n a[node_x] = 1;\n }\n</code></pre>\n<p>The first initialization can be accomplished by:</p>\n<pre><code> uint32_t a[MATRIX_WIDTH_SQUARED] = {0};\n</code></pre>\n<p>and I would prefer to see an iterator used in the second initialization.</p>\n<p><strong>Use Proper Casting</strong><br />\nCurrently the code is implementing C style casting (<code>(uint32_t) (first_col_sum % MODE)</code>) which is not as type safe as either <a href=\"https://en.cppreference.com/w/cpp/language/static_cast\" rel=\"nofollow noreferrer\">static_cast(VALUE_TO_BE_CAST)</a> or <a href=\"https://en.cppreference.com/w/cpp/language/dynamic_cast\" rel=\"nofollow noreferrer\">dynamic_cast<NEW_TYPE>(EXPRESSION)</a>. In this case I recommend <code>static_cast</code>.</p>\n<p><strong>Static Functions</strong><br />\nIt is not clear why the <code>checkRecord()</code> function was changed to a <a href=\"https://en.cppreference.com/w/cpp/language/static\" rel=\"nofollow noreferrer\">static member function</a> since the original prototype was <code>int checkRecord(int n)</code> in the question. There really is no need for it to be static.</p>\n<blockquote>\n<p>By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator.</p>\n</blockquote>\n<p><strong>Variable Names</strong><br />\nThe symbolic constant names are clear as are the variable names <code>adj_matrix</code> (adjacency would be clearer), <code>accumulated</code> and <code>adj_matrix_pointer</code>, but the variable names <code>a</code>, <code>b</code> and <code>temp</code> are not clear and leave someone who has to read or maintain the code guessing.</p>\n<p><strong>Complexity</strong><br />\nThe function <code>checkRecord()</code> is too complex (does too much). After the if statement there should be a call to a function to execute the rest of the code, and that function might cal sub functions. Remember that it is much easier to write correct code when you limit what a function is responsible for.</p>\n<p>There is also a 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",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T20:29:36.090",
"Id": "244408",
"ParentId": "244391",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244408",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T16:36:52.007",
"Id": "244391",
"Score": "2",
"Tags": [
"c++",
"beginner",
"algorithm",
"programming-challenge",
"c++17"
],
"Title": "LeetCode 552: Student Attendance Record II"
}
|
244391
|
<p>This is a beginner's class. I just need help verifying if this code is correct, or edit the parts that need fixing.</p>
<pre><code>n = int(input("Enter a number"))
sum = 0
for i in range(1,n+1):
sum = sum + i
print("The sum is:", sum)
</code></pre>
|
[] |
[
{
"body": "<h2>Bug?</h2>\n<p>Do you want to display a cumulative sum every time the loop executes? That's what you do now. If not - if you want to only display the final sum - you need to de-indent your <code>print</code>.</p>\n<h2>Sum</h2>\n<p>You can do the whole sum using the actual <code>sum</code> function, like this:</p>\n<pre><code>total = sum(range(1, n + 1))\n</code></pre>\n<p>Note that you should not call a variable <code>sum</code>, because that shadows the built-in <code>sum</code> function.</p>\n<h2>Calculating the sum</h2>\n<p>This doesn't actually need a loop or a call to <code>sum</code> at all. Math will tell you that the entire sum will evaluate to <span class=\"math-container\">\\$n(n + 1)/2\\$</span>; an example of equivalence:</p>\n<p><span class=\"math-container\">$$\n\\begin{align}\n1 + 2 &= 3\\\\\n\\frac{2 * 3}{2} &= 3\n\\end{align}\n$$</span></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T14:22:51.833",
"Id": "479870",
"Score": "1",
"body": "The generator expression is unnecessary. Simply sum the range: `total = sum(range(1, n + 1))`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T14:23:38.917",
"Id": "479871",
"Score": "0",
"body": "@AJNeufeld nice!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T20:01:22.333",
"Id": "479902",
"Score": "1",
"body": "A '[graphical proof](https://de.wikipedia.org/wiki/Gau%C3%9Fsche_Summenformel#/media/Datei:Gau%C3%9Fsche_Summenformel_geometrisch.svg)' of sum(1 to n) = n(n+1)/2"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T17:00:15.507",
"Id": "244396",
"ParentId": "244394",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T16:50:36.877",
"Id": "244394",
"Score": "3",
"Tags": [
"python",
"beginner"
],
"Title": "Calculate and displays the sum of all numbers from 1 to 20"
}
|
244394
|
<p>This is an implementation of a 2D peak finder from MIT's Intro to Algos.</p>
<p>I'm a C beginner and I would really like some feedback on coding style, documentation and any other general C bad practices.
Additionally have I correctly freed the memory of the recursive calls?</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
typedef struct max_vector {
unsigned int col_index;
unsigned int row_index;
int index_value;
} max_vector;
max_vector * find_col_peak(int *arr, int rows, int col){
/* Find the peak of a column.
This function treats a 2D array like a 1D array and
traverses using some basic pointer arithmetic.
next item = *((i * row + arr) + j)
where:
- i == current row number (the y axis in matrix i.e. up and down)
- j == column number in column space (the x axis i.e left to right)
- row == the number of items in each row
- *arr == the first item in the array
*/
// we want a vector to save the max number and its index
max_vector *vector = malloc(sizeof(max_vector));
if (vector) {
// set max to the first item of the column
vector->col_index = 0;
vector->index_value = *(col + arr);
// loop through the rest of the column
for (int i=1; i < rows; i++){
int next_number = *((i * rows + arr) + col);
if (next_number > vector->index_value){
vector->col_index = i;
vector->index_value = next_number;
}
}
printf("the max value is %d and it is at index %d\n",
vector->index_value, vector->col_index);
return vector;
}
return NULL;
}
max_vector * peak_finder(int *matrix, int rows, int first, int last){
/* Find a local 2D peak.
NOTE: Expects a matrix of size row x col
A peak is defined as:
(i, j) >= (i, j + 1), (i, j - 1), (i + 1, j) (i - 1, j)
*/
max_vector *vector;
int middle = last / 2;
vector = find_col_peak(matrix, rows, middle);
if (vector){
if (middle == first || middle == last){
vector->row_index = middle;
return vector;
}
if (last > first) {
int current = *((vector->col_index * rows) + matrix + middle);
int one_less = *((vector->col_index * rows) + matrix + middle - 1);
int one_more = *((vector->col_index * rows) + matrix + middle + 1);
if (one_less <= current >= one_more) {
vector->row_index = middle;
return vector;
}
// if current is not a peak we can free the vector
if (one_less > current){
free(vector);
return peak_finder(matrix, rows, first, middle - 1);
} else {
free(vector);
return peak_finder(matrix, rows, middle + 1, last);
}
}
vector->row_index = middle;
return vector;
}
return NULL;
}
int main(void) {
int arr [5][5] = {
{10, 8, 11, 10, 16},
{14, 13, 12, 11, 24},
{15, 9, 11, 21, 6},
{16, 21, 19, 20, 12},
{100, 6, 13, 19, 9},
};
max_vector *ptr = peak_finder(*arr, 5, 0, 5);
printf("the local peak is at %d, %d", ptr->row_index, ptr->col_index);
free(ptr);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<h1>Use standard array notation</h1>\n<p>When you are accessing array elements, the idiomatic way in C is to write <code>foo[bar]</code> instead of <code>*(foo + bar)</code>. So instead of:</p>\n<pre><code>int next_number = *((i * rows + arr) + col);\n</code></pre>\n<p>Write:</p>\n<pre><code>int next_number = arr[i * rows + col];\n</code></pre>\n<p>It is both shorted, and now it is clear what part the array pointer is and what part the index is.</p>\n<h1>Avoid unnecessary memory allocations</h1>\n<p>It's perfectly possible in C to return a <code>struct</code> by value. This avoids having to call <code>malloc()</code> and <code>free()</code>, and you no longer have to worry about its memory leaking, nor have to check whether <code>malloc()</code> succeeded. You do it like so:</p>\n<pre><code>max_vector find_col_peak(int *arr, int rows, int col) {\n max_vector vector;\n\n // set max to the first item of the column\n vector.col_index = 0;\n vector.index_value = *(col + arr);\n\n ...\n\n return vector;\n}\n</code></pre>\n<h1>About recursion</h1>\n<p>With the above you don't have to worry about freeing memory for <code>vector</code> anymore. However, recursive calls themselves could have some memory overhead, since each call needs some amount of space on the stack. With this algorithm, you only need <code>log2(cols)</code> recursion levels, so that won't be an issue even for huge inputs. Also, the compiler can turn these recursive calls into <a href=\"https://en.wikipedia.org/wiki/Tail_call\" rel=\"nofollow noreferrer\">tail calls</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T15:46:20.397",
"Id": "244451",
"ParentId": "244397",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T17:07:09.447",
"Id": "244397",
"Score": "1",
"Tags": [
"beginner",
"algorithm",
"c"
],
"Title": "C - 2D peak finder in"
}
|
244397
|
<p>I am studying and practicing Python; this is my Rock-Paper-Scissors game I've built from scratch.
I saw this task is for beginners. When writing this in all the examples I saw dozens of lines of code with <code>if</code> <code>elif</code> <code>else</code> statements.
I decided to write the shortest program for this game.</p>
<p>I'm just looking for any comments, improvements or bad habits. Any comments at all are welcome!</p>
<pre><code>import random
my_win = 0
my_loss = 0
my_tie = 0
def game():
global my_tie, my_loss, my_win
var = {'scissors':(0,1,0),
'paper':(0,0,1),
'rock':(1,0,0)}
user = input("Please choice scissors, paper or rock: ")
while user not in ['scissors', 'paper', 'rock']:
user = input("Please choice scissors, paper or rock: ")
computer = random.choice(['scissors','paper','rock'])
print(f"USER - {user} \nCOMPUTER - {computer}")
for k, v in var.items():
if k == user:
one = int(v.index(1))
if k == computer:
two = int(v.index(1))
if one < two:
print(f"USER with {user} - WIN!")
my_win += 1
elif one == two:
print("==TIE==")
my_tie += 1
else:
print(f"COMPUTER with {computer} - WIN!")
my_loss += 1
def results():
print ("You win %d times!" % my_win)
print ("You lose %d times!" % my_loss)
print ("You tie %d times!" % my_tie)
if __name__ == "__main__":
game()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T19:26:19.167",
"Id": "479788",
"Score": "2",
"body": "Are you sure your code is functionally correct? I might be wrong but it looks to me like if the user selects rock and the computer selects paper the user will win since `0<2`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T20:43:39.033",
"Id": "479906",
"Score": "0",
"body": "Thank you!) It's really my fail with rules :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T22:22:47.507",
"Id": "479924",
"Score": "0",
"body": "Welcome to Code Review! I have rolled back Rev 4 → 3 Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)."
}
] |
[
{
"body": "<p>I'll just go over some small improvements I noticed you can make.</p>\n<pre><code>my_win = 0\nmy_loss = 0\nmy_tie = 0\n\n\ndef game():\n\n global my_tie, my_loss, my_win\n</code></pre>\n<p>Global variables should be avoided whenever possible. The only reason I can see that these are globals is because of <code>results()</code> but you never actually call <code>results()</code>. It's probably better to just leave these as local variables.</p>\n<pre><code>var = {'scissors':(0,1,0),\n 'paper':(0,0,1),\n 'rock':(1,0,0)}\n\nfor k, v in var.items():\n if k == user:\n one = int(v.index(1))\n if k == computer:\n two = int(v.index(1))\n</code></pre>\n<p>A couple of comments here. First, you don't make use of the fact that your values in your dictionary are tuples instead of just ints. You can just use 0, 1, and 2 as values. Second, you're not taking advantage of the thing that dictionaries are best at: indexing. An improvement here would be:</p>\n<pre><code>var = {'scissors':1,\n 'paper':2,\n 'rock':0}\n\none = var[user]\ntwo = var[computer]\n</code></pre>\n<p>Next:</p>\n<pre><code>if one < two:\n print(f"USER with {user} - WIN!")\n my_win += 1\nelif one == two:\n print("==TIE==")\n my_tie += 1\nelse:\n print(f"COMPUTER with {computer} - WIN!")\n my_loss += 1\n</code></pre>\n<p>As I said in the comments, I don't think this is functionally correct. Either combination of the user and the computer choosing paper and rock will cause the rock to win. One of many fixes you could do is to add <code>and abs(one - two) == 1</code> as a condition to your first <code>if</code> statement.</p>\n<pre><code>def results():\n\n print ("You win %d times!" % my_win)\n print ("You lose %d times!" % my_loss)\n print ("You tie %d times!" % my_tie)\n</code></pre>\n<p>This function is defined inside your <code>game()</code> function and is never called. Because your variables are local (as I suggested), you might want to put wins, losses, and ties as arguments for this function. You also don't have a way to play the game more than once, making this function pretty unhelpful. I'll leave adding a way to play multiple games to you since that's more of a code upgrade than a code review.</p>\n<p>Here is the complete code with all my proposed changes:</p>\n<pre><code>import random\n\ndef game():\n my_win = 0\n my_loss = 0\n my_tie = 0\n\n var = {'scissors':1,\n 'paper':2,\n 'rock':0}\n\n user = input("Please choice scissors, paper or rock: ")\n while user not in ['scissors', 'paper', 'rock']:\n user = input("Please choice scissors, paper or rock: ")\n computer = random.choice(['scissors','paper','rock'])\n\n print(f"USER - {user} \\nCOMPUTER - {computer}")\n\n one = var[user]\n two = var[computer]\n\n if one < two and abs(one - two) == 1:\n print(f"USER with {user} - WIN!")\n my_win += 1\n elif one == two:\n print("==TIE==")\n my_tie += 1\n else:\n print(f"COMPUTER with {computer} - WIN!")\n my_loss += 1\n \n results(my_win, my_loss, my_tie)\n\ndef results(win, loss, tie):\n\n print ("You win %d times!" % win)\n print ("You lose %d times!" % loss)\n print ("You tie %d times!" % tie)\n\n\nif __name__ == "__main__":\n game()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T20:59:45.880",
"Id": "479912",
"Score": "0",
"body": "Thank you for your answer and support. This is really helping and important for me. But I'm have a questions - I am understand that using global variables is not good way and I'm read about avoiding global, but if this counters will be local variables - I'm cant play n-times and will see results after it. Because of that I'm use this simple counter. And I'm have mistake when copy-paste code here - results() not in game() function - thank you. After your comment I'm rewrite code to add multiple games. THANK YOU! I'm hope this my code is not very ugly and scary professionals :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T12:00:49.257",
"Id": "479977",
"Score": "1",
"body": "@edrrujqg There's a few ways you can get around global variables. You could have your loop that allows you to play the game multiple times inside your `game()` method. You could also have your `game()` method return something that represents what happened in the round like a string or an int or a tuple. The best way I think would be to make a class that handles playing the game, but I don't know if you've learned about classes yet. Glad I could help!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T19:33:00.450",
"Id": "480715",
"Score": "0",
"body": "yes. I'm read about classes and I'll try except global variables with using classes. Thank you!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T19:53:07.230",
"Id": "244405",
"ParentId": "244401",
"Score": "5"
}
},
{
"body": "<p>There are multiple things you could improve in your code.</p>\n<h2>The name of the game</h2>\n<p>I feel that it'd be better to call your <code>game</code> method <code>run_game</code>. You should also run it multiple times in a while loop, asking the user each time if they want to exit. When they say they want to exit, you can call the <code>results</code> function to display the results.</p>\n<h2>The results</h2>\n<p>Not only do you never use the <code>results</code> function, but you've indented it too far so it's inside the <code>game</code> function. Make sure it's top-level so that other modules can use it. Also, you have spaces before the <code>print</code> statements, but that's a minor thing.</p>\n<p>I assume you're designing this module so that other modules can use it, but if not, make the global variables local and get rid of the <code>if</code> at the end.</p>\n<p>Better names for your result variables would be <code>num_wins</code>, <code>num_losses</code>, and <code>num_ties</code>.</p>\n<p>Your <code>results</code> function would also be better if it were named <code>print_results</code>, since the current name implies that it <em>returns</em> the results.</p>\n<h2>Storing the choices</h2>\n<p>First of all, don't name your variables <code>var</code>. <code>choices</code> is a better name. Also, you can just use a list instead of a dictionary, and use the indices to calculate who won. You could also reuse your <code>choices</code> list while taking user input and while choosing a move for the computer.</p>\n<pre><code>choices = ['paper', 'scissors', 'rock']\n</code></pre>\n<p>Also, rather than using the names <code>user</code> and <code>computer</code>, call the variables where you store the user's and computer's choices something like <code>user_move</code> and <code>comp_move</code></p>\n<pre><code>user_move = input("Please choice scissors, paper or rock: ")\nwhile user_move not in choices:\n user_move = input("Please choice scissors, paper or rock: ")\ncomp_move = random.choice(choices)\n</code></pre>\n<h2><code>one</code> and <code>two</code> and finding the winner</h2>\n<p>To get the value associated with a key in a dictionary, you can simply do <code>my_dict[my_key]</code>. It's not necessary to loop through the entire list and not break even once you've found the necessary key. You could have replaced that for loop with this (note that there's no need to use <code>int()</code> on the value)</p>\n<pre><code>one = choices[user_move].index(1)\ntwo = choices[comp_move].index(1)\n</code></pre>\n<p>However, we have changed the <code>choices</code> variable to be a list of strings, and anyways, your logic won't work in case the user selects "rock" and the computer selects "paper", as @ThisIsAQuestion pointed out.</p>\n<p>This way accounts for that error (I also renamed <code>one</code> and <code>two</code> to <code>user_ind</code> and <code>comp_ind</code>):</p>\n<pre><code>user_ind = choices.index(user_move)\ncomp_ind = choices.index(comp_move)\n\nif user_ind == comp_ind:\n num_ties += 1\nelif user_ind - comp_ind < 2:\n num_wins += 1\nelse:\n num_losses += 1\n</code></pre>\n<p>However, this isn't very clear. A better way to do it would be like this, by checking if the computer's move is one index ahead (after using <code>%</code>, of course)</p>\n<pre><code>if user_move == comp_move:\n num_ties += 1\nelif choices[(choices.index(user) + 1) % len(choices)] == comp_move:\n num_losses += 1\nelse:\n num_wins += 1\n</code></pre>\n<p>This second approach treats <code>choices</code> like a cycle rather than just a linear list. The <code>%</code> is to avoid accessing an index beyond the range of the list - it comes back to <code>0</code> if it's <code>3</code> (You can always hardcode <code>3</code> instead of <code>len(choices)</code>).</p>\n<h2>The resulting code</h2>\n<pre><code>import random\n\nnum_wins = 0\nnum_losses = 0\nnum_ties = 0\n\ndef run_game():\n choices = ['paper', 'scissors', 'rock']\n user_move = input("Please choice scissors, paper or rock: ")\n while user_move not in choices:\n user_move = input("Please choice scissors, paper or rock: ")\n comp_move = random.choice(choices)\n\n if user_move == comp_move:\n num_ties += 1\n print(f"BOTH with {user_move} - TIE")\n elif choices[(choices.index(user) + 1) % len(choices)] == comp_move:\n num_losses += 1\n print(f"COMPUTER with {comp_move} - WIN!")\n else:\n num_wins += 1\n print(f"USER with {user_move} - WIN!")\n\ndef print_results():\n print("You win %d times!" % num_wins)\n print("You lose %d times!" % num_losses)\n print("You tie %d times!" % num_ties)\n\nif __name__ == "main":\n continue = 'y'\n while continue.lower() == 'y':\n run_game()\n continue = input('Enter "y"/"Y" to continue')\n print_results()\n</code></pre>\n<p>Edit: Using the walrus operator, as Aivar Paalberg suggested, would simplify the while loops.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T21:43:53.547",
"Id": "479913",
"Score": "0",
"body": "thank you for your answer and your help. this is important for me. But with your code USER can't win))) `run_game()\nPlease choice scissors, paper or rock: rock\nComputer move is - scissors\nCOMPUTER with scissors - WIN!` Like in real cassino ;) I'm thin mistake here: `elif choices[(choices.index(user) + 1) % len(choices)]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T21:56:02.217",
"Id": "479914",
"Score": "1",
"body": "Sorry, I forgot == comp_move. Good catch there. Can you check again?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T22:09:37.083",
"Id": "479918",
"Score": "1",
"body": "yeah, now it's working right :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T22:11:27.810",
"Id": "479920",
"Score": "0",
"body": "thank you for your answer. Your solution is very helpful and give important experience for me. I'm hope this my code is not very ugly and scary professionals :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T20:01:20.887",
"Id": "480719",
"Score": "0",
"body": "and I'm think \"continue\" - this is not good variable name ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T20:04:42.680",
"Id": "480720",
"Score": "0",
"body": "@edrrujqg I thought of it as \"Continue? Y\". You could change it to `input` or `should_continue`, of course. It's purely objective. However, an even better approach would be to use the walrus operator, which the answer by Aivar Paalberg uses"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T20:15:09.410",
"Id": "480721",
"Score": "0",
"body": "@ user yeah, I'm changed it. Thanks for the new knowledge ;)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T20:20:40.497",
"Id": "244407",
"ParentId": "244401",
"Score": "3"
}
},
{
"body": "<p>Functionally not 100% similar but shorter version of code. Taking advantage of walrus operator and modulo 3 tricks:</p>\n<pre><code>from random import choice\n\nchoices = ['rock', 'paper', 'scissors']\nresults = ['user wins', 'computer wins', 'draw']\ntotals = [0, 0, 0]\n\nwhile True:\n\n while (user_choice := input('Please choose {}, {} or {}: '.format(*choices))) not in choices:\n continue\n\n computer_choice = choice(range(3))\n result_indice = (choices.index(user_choice) - computer_choice) % 3 - 1\n result = results[result_indice]\n totals[result_indice] += 1\n print(f'user: {user_choice}, computer: {choices[computer_choice]}, result: {result}')\n print(*[f'{result}: {total}' for result, total in zip(results, totals)])\n\n if input('Enter y or Y to continue: ').lower() != 'y':\n break\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T18:59:39.850",
"Id": "480160",
"Score": "1",
"body": "Nice job using the walrus operator. As long as the OP doesn't want to run the game from different modules, it's a really good solution. +1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T19:29:17.563",
"Id": "480713",
"Score": "0",
"body": "Thank you for your answer. This is really short example :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T18:52:23.427",
"Id": "244584",
"ParentId": "244401",
"Score": "4"
}
},
{
"body": "<p>Thank's all for yours answers and solutions!\nI'm read every example and teaches myself something new.\nGuys - you are great!\nThis is my solution. And of course I except from this global variables.</p>\n \n<pre><code>import random\n\nclass game():\n\n num_wins = 0\n num_losses = 0\n num_ties = 0\n\n def run_game():\n \n choices = ["paper", "scissors", "rock"]\n \n user_move = input("Please choice scissors, paper or rock: ")\n while user_move not in choices:\n user_move = input("Please choice scissors, paper or rock: ")\n comp_move = random.choice(choices)\n\n if user_move == comp_move:\n game.num_ties += 1\n print(f"BOTH with {user_move} - TIE")\n elif choices[(choices.index(user_move) + 1) % len(choices)] == comp_move:\n game.num_losses += 1\n print(f"COMPUTER with {comp_move} - WIN!")\n else:\n game.num_wins += 1\n print(f"USER with {user_move} - WIN!")\n \n return game.num_wins, game.num_losses, game.num_ties\n\n def print_results():\n print("You win %d times!" % game.num_wins)\n print("You lose %d times!" % game.num_losses)\n print("You tie %d times!" % game.num_ties)\n\nif __name__ == "__main__":\n end = ""\n while end.lower() != "y":\n game.run_game()\n end = input("Enter 'y'/'Y' to continue ")\n game.print_results()\n game.num_wins, game.num_losses, game.num_ties = 0, 0, 0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T19:34:08.260",
"Id": "480716",
"Score": "1",
"body": "By the way, I forgot to add in my answer that you can use f-strings for printing out the results. You might want to try that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T19:41:08.570",
"Id": "480717",
"Score": "0",
"body": "yeah, thank you! I saw that I was using two different options and decided to leave both as a reminder to myself that I'm can do print() in different ways. I think that in real work I'm need to follow in one style of code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T19:28:46.677",
"Id": "244846",
"ParentId": "244401",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244407",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T18:58:25.207",
"Id": "244401",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"game",
"rock-paper-scissors"
],
"Title": "Short code in Python Rock Paper Scissors"
}
|
244401
|
<p>I'm new to sh and I would like to get feedback on how I can improve my code.</p>
<p>The purpose is simple; I want to open the Jenkins JOB related to a service based on its possible aliases. If I map a service with its aliases, <code>READ_JOB="rj readjob read-job"</code>, I want to open it by calling the script <code>opendeploy readjob</code> or <code>opendeploy rj</code>.</p>
<p>The link between aliases and URLS to open was easy; an associative array worked.
But I wanted to link: Service Name, Job URL and Possible Services Aliases.
I Google to see if this can be done. But it looks like <code>sh</code> does not support nested arrays. I have created 2 arrays with the same keys.</p>
<pre><code>#!/bin/bash
__READ_JOB="db-restore"
##Services x Aliases
declare -A SERVICES=(
["${__READ_JOB}"]="rj readjob read-job"
)
#Services x Jobs Links
declare -A JOBS_URL=(
["${__READ_JOB}"]="https://relatedJobUrl.com"
)
function opendeploy(){
build=0
rootJenskinsUrl='https://defaultUrlIfNoParameters.com/'
urlToOpen=$rootJenskinsUrl
while [ "$1" != "" ]; do
__getJobLink "$1"
if [ "$1" = -b ] || [ "$1" = --build ]; then
build=1
fi
if [ "$1" = -h ] || [ "$1" = --help ]; then
##Calling the method that explains how to use if the user use the "-h or -help"
__usage
return
fi
shift
done
##Checking if -b parameter was filled, so we can append a build parameter at the end of the url
if [ "$build" = "1" ] && [ "$urlToOpen" != "$rootJenskinsUrl" ]; then
urlToOpen+='/build?delay=0sec'
fi
open $urlToOpen
}
__usage()
{
##This is why I need the association with the service name to well display: Service - Possible Aliases
echo "usage: opendeploy service [[ [-b]] | [-h]]\n (no parameters opens root Jenkins URL)\n"
echo "Possible Services - Aliases:\n"
for k in "${(@k)SERVICES}"; do
echo "$k -" "$SERVICES[$k]"
done
}
function __getJobLink() {
for k in "${(@k)SERVICES}"; do
for alias in $SERVICES[$k]
do
if [ "$alias" = "$1" ]; then
urlToOpen=${JOBS_URL[$k]}
fi
done
done
}
</code></pre>
<p>I see points of improvements:</p>
<ul>
<li>Not to use global variables at the beginning of the script.</li>
<li>Find a way to not create 2 associative arrays.</li>
</ul>
<p><strong>PS</strong>: This is running in a ZSH profile. I needed to adapt because bash was not recognising some things.</p>
<p>I do not wait to someone 'solve it' for me. I want suggestions on what I could do to improve my code.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T19:05:26.953",
"Id": "244402",
"Score": "2",
"Tags": [
"sh"
],
"Title": "sh script to open related URL based on possible nicknames"
}
|
244402
|
<p>I solved <a href="https://codeforces.com/contest/1369/problem/B" rel="nofollow noreferrer">this</a> problem statement on dear old codeforces.
The Problem Statement wants users to replace occurrences of '10' in the given string with either '1' or '0' until there is no occurrence of '10' left and the string formed is the lexicographically smallest string from the set of all valid answers.</p>
<p>This is my solution (and it has been accepted). However, I would like to know if we can simplify this solution further:</p>
<pre><code>#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main() {
int T = 0;
std::cin >> T;
while (T--) {
int n = 0;
std::cin >> n;
std::string str;
std::cin >> str;
while (str.find("10", 0) != std::string::npos) {
auto it = std::find(str.begin(), str.end(), '1');
auto begin = it;
std::string window;
while (it != str.end() && *it == '1') {
window.push_back(*it);
it++;
}
while (it != str.end() && *it == '0') {
window.push_back(*it);
it++;
}
if (std::count(window.begin(), window.end(), '0') == 0 || std::count(window.begin(), window.end(), '1') == 0) {
std::cout << str << "\n";
break;
}
while (window.size() > 1) {
auto count0 = std::count(window.begin(), window.end(), '0');
auto count1 = std::count(window.begin(), window.end(), '1');
if (count0 > count1) {
window.erase(--window.end());
}
else if (count1 > count0) {
window.erase(window.begin());
}
else {
if (str.find("10", std::distance(str.begin(), it)) == std::string::npos) {
window.erase(window.begin());
}
else {
window.erase(--window.end());
}
}
}
*(--it) = window.front();
str.erase(begin, it);
}
std::cout << str << "\n";
}
return 0;
}
</code></pre>
<p>Please review and suggest :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T21:59:34.397",
"Id": "479797",
"Score": "1",
"body": "Please copy the full problem statement from the source and paste it in the question. Links can break."
}
] |
[
{
"body": "<h1>Add some comments describing your algorithm</h1>\n<p>Your code is a single function which is a bit long, and it's not very obvious what it is doing. There are two ways of dealing with this: either creating functions that implement logical steps of the algorithm individually, or add some comments to describe which steps your algorithm is doing. Don't add comments that just descibre exactly what the code does, but give a higher level description.</p>\n<h1>Unnecessary use of <code>std::count()</code></h1>\n<p>You use <code>std::count()</code> a lot, but you don't need to. You can count the number of zeroes and ones when building <code>window</code>, and when you are calling <code>window.erase()</code> you can decrement your counts.</p>\n<h1>Consider using <code>std::string</code> functions to search for blocks of zeroes and ones</h1>\n<p>Instead of using <code>std::find()</code> and counting manually using <code>while</code>-loops, you can use <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/find\" rel=\"noreferrer\"><code>std::string::find()</code></a>. You can also construct a string directly from a subregion of another string.</p>\n<pre><code>auto first1 = str.find('1');\nauto next0 = str.find('0', first1);\nauto next1 = str.find('1', next0);\n\nstd::string window(str, first1, next1 - first1);\n</code></pre>\n<p>Once you have that, calculating the number of zeores and ones in <code>window</code> is easy:</p>\n<pre><code>auto count1 = next0 - first1;\nauto count0 = window.size() - count1;\n</code></pre>\n<p>However, you might not even need the initial window:</p>\n<h1>Avoid constructing and then partially deconstructing the window</h1>\n<p>Your window consists of a number of ones followed by a number of zeroes. You are then slowly removing from the start and end until some conditions are met. However, while you are doing this, the only thing you really care about is the count of zeroes and ones, not the string <code>window</code> itself! You can reconstruct the final <code>window</code> from the counts left at the end.</p>\n<p>Let's assume we have calculated <code>count0</code> and <code>count1</code> like I've written above. Then:</p>\n<pre><code>while (window.size() > 1) {\n</code></pre>\n<p>Can be replaced with:</p>\n<pre><code>while (count0 + count1 > 1) {\n</code></pre>\n<p>Then you do:</p>\n<pre><code>if (count0 > count1)\n window.erase(--window.end());\nelse if (count1 > count0)\n window.erase(window.begin());\n</code></pre>\n<p>Basically, this removes zeroes or ones until the number of zeroes or ones is equal. This can be replaced with the following:</p>\n<pre><code>count0 = count1 = std::min(count0, count1);\n</code></pre>\n<p>Then the next condition is:</p>\n<pre><code>if (str.find("10", std::distance(str.begin(), it)) == std::string::npos)\n window.erase(window.begin());\nelse\n window.erase(--window.end());\n</code></pre>\n<p>Since <code>str</code> is not modified here, you could move the <code>if</code>-condition outside of the loop. And the <code>window.erase()</code> calls can be replaced by <code>count0--</code> and <code>count1--</code>. So what's left is:</p>\n<pre><code>bool has_second_10 = str.find("10", next0 + count0) != str.npos;\n\nwhile (count0 && count1) {\n if (count0 != count1) {\n count0 = count1 = std::min(count0, count1);\n } else {\n if (has_second_10) {\n count0--;\n } else {\n count1--;\n }\n }\n}\n</code></pre>\n<p>But wait, it gets even better: you always start with a window with both ones and zeroes, and you make the count equal, and then you remove zeroes if the original string had a second occurrence of <code>"10"</code>, otherwise you remove ones. So the single character left in the window is completely determined by <code>has_second_10</code>, and the <code>while</code>-loop can be eliminated entirely. You also don't need to count ones and zeroes anymore.</p>\n<p>Now it's just a matter of updating the original string. Instead of modifying a character and erasing some, you can use the <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/replace\" rel=\"noreferrer\"><code>std::string::replace()</code></a> function to do that in one go:</p>\n<pre><code>str.replace(first1, next1 - first1, 1, has_second_10 ? '1' : '0');\n</code></pre>\n<h1>Summary</h1>\n<p>With the above improvements, the code can be simplified to:</p>\n<pre><code>#include <iostream>\n#include <string>\n \nint main() {\n int T = 0;\n std::cin >> T;\n\n while (T--) {\n int n = 0;\n std::cin >> n;\n std::string str;\n std::cin >> str;\n\n while (str.find("10", 0) != str.npos) {\n auto first1 = str.find('1');\n auto next0 = str.find('0', first1);\n auto next1 = str.find('1', next0); // this might be npos, but that's fine\n auto replacement = str.find("10", next1) == str.npos ? '0' : '1';\n str.replace(first1, next1 - first1, 1, replacement);\n }\n\n std::cout << str << "\\n";\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T22:37:57.103",
"Id": "479799",
"Score": "1",
"body": "And this would have negated part of my possible answer because the code is now short enough not to require sub functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T05:08:45.500",
"Id": "479818",
"Score": "0",
"body": "One of the most detailed explanations I've ever been given. Thanks a lot. I will definitely implement your suggestions :) UV coming up"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T22:14:57.697",
"Id": "244410",
"ParentId": "244403",
"Score": "5"
}
},
{
"body": "<p>The problem statement is much more about logical reasoning than about coding. On a unix/linux terminal, the challenge can be solved with 15 characters!</p>\n<pre><code>sed 's/1.*0/0/'\n</code></pre>\n<p>The equivalent c++ code is also a one-liner when using <code>regex::replace</code>, or a three-liner with <code>string::find</code> and <code>string::replace</code>. If you read the instructions carefully and work through a few examples, you will find two important properties (a formal proof is just as easy):</p>\n<ol>\n<li><p>Any binary string that starts with a one and ends in zero can be reduced to a single digit. You even have the choice whether this digit is zero or one.</p>\n</li>\n<li><p>Leading zeros and trailing ones cannot be reduced.</p>\n</li>\n</ol>\n<p>To solve the challenge, just ignore leading zeros and trailing ones and replace the middle part, if non-empty, with a single zero digit. That's what my <code>sed</code> script does.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T10:50:59.490",
"Id": "244439",
"ParentId": "244403",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244410",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T19:19:52.993",
"Id": "244403",
"Score": "3",
"Tags": [
"c++",
"strings"
],
"Title": "Code to modify string as per instructions"
}
|
244403
|
<p>I created an algorithm to create lists of anagrams</p>
<p>The input is <code>["eat", "tea", "tan", "ate", "nat", "bat"]</code></p>
<p>Then, the output should be:
<code>[["eat","tea","ate"],["tan","nat"],["bat"]]</code></p>
<p>Each array is words that are anagram.</p>
<p>My solution is:</p>
<pre><code>function group(input) {
let result = [];
if(input.length === 0){
return result;
}
for(let i=0; i<input.length; i++){
let check = true;
for(let j=0; j<result.length; j++){
if(result[j].includes(input[i])){
check = false;
}
}
if(check){
result.push(checkAnagrams(input, i));
}
}
return result;
}
function checkAnagrams(aStr, i){
let anagrams = [];
anagrams.push(aStr[i]);
for(let j=0; j<aStr.length; j++){
if(i !== j){
if(isAnagram(aStr[i], aStr[j])){
anagrams.push(aStr[j]);
}
}
}
return anagrams;
}
function isAnagram(str1, str2) {
// split => string into array
// sort => sort the array
// join => string to array
// trim => remove any space
const string1 = str1.split("").sort().join().trim();
const string2 = str2.split("").sort().join().trim();
if(string1 === string2){
return true;
}
return false;
}
</code></pre>
<p>I know it works, but I was wondering if there is a better way to implement it.</p>
<p>Thanks</p>
|
[] |
[
{
"body": "<p>Welcome to Code Review, the complexity of your code can be reduced using a <a href=\"https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\">Map</a> object having as keys sorted lexicographically strings and as values arrays of their anagrams. For example you will have the following couples key - value starting from your input:</p>\n<pre><code>key = "aet" value = ["eat","tea","ate"]\nkey = "ant" value = ["tan","nat"]\nkey = "abt" value = ["bat"]\n</code></pre>\n<p>So you can define a function <code>anagrams</code> like this:</p>\n<pre><code>function anagrams(input) {\n const map = new Map();\n\n for (let i = 0; i < input.length; ++i) {\n const key = [...input[i]].sort().join('');\n const value = map.has(key) ? map.get(key) : [];\n value.push(input[i]);\n map.set(key, value);\n }\n\n return [...map.values()];\n}\n\n/*below it will print the expected result*/\nconsole.log(anagrams(["eat", "tea", "tan", "ate", "nat", "bat"])); \n</code></pre>\n<p>I just used the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">Spread operator</a> to expand the string <code>input[i]</code> to array of characters and after I sort it to obtain the corrisponding key in the map. After I add it to the array of strings associated to the key and finally I return the map values as an array.</p>\n<p>Note: I'm a javascript beginner so every hint or criticism about my answer is highly appreciated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T14:42:03.000",
"Id": "479874",
"Score": "1",
"body": "[Consider not using spread](https://hackernoon.com/3-javascript-performance-mistakes-you-should-stop-doing-ebf84b9de951)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T15:46:29.893",
"Id": "479880",
"Score": "0",
"body": "@KooiInc Thanks for your advice and the link, I will use spread just for simple exercises like this; it is quite surprising to find a 10x difference between one construct and another one applied to the same task."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T21:33:43.470",
"Id": "244409",
"ParentId": "244404",
"Score": "4"
}
},
{
"body": "<p>Based on the code written by <a href=\"https://codereview.stackexchange.com/users/203649/dariosicily\">dariosicily</a> I made a bit of changes to it.</p>\n<p><code>const key</code> could be declared outside with <code>let</code>, it improves a bit the performance. The inside of the loop, could be changed by:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function anagrams(input) {\n const map = new Map();\n let key;\n for (let i = 0; i < input.length; ++i) {\n if (map.has(key = [...input[i]].sort().join(''))) \n map.get(key).push(input[i]);\n else map.set(key, [input[i]]);\n }\n return [...map.values()];\n}\n</code></pre>\n<p>The assignment of variables has a quite notorious performance impact (when the input is great enough).</p>\n<p>Note: I thought of writing it as a comment to dario but it was big.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T06:38:02.250",
"Id": "479820",
"Score": "0",
"body": "Thanks for your hints."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T09:12:18.110",
"Id": "479836",
"Score": "0",
"body": "Could you provide sources to this claim? Conceptionally a `const` should be preferred here over `let` because its a different key in each loop and not a single key that is changing. Considering the complexity of the logic inside the loop, I doubt that \"reusing\" a variable changes the performance noticeably."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T02:35:01.033",
"Id": "244419",
"ParentId": "244404",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244419",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T19:33:41.873",
"Id": "244404",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "JavaScript group anagram performance"
}
|
244404
|
<p>I have small question. I don't know much about JavaScript (jQuery) or AJAX and I don't know whether I'm doing it safe from XSS Attacks, SQL injection and that stuff. I think the PHP with MySQL would be written right. The code works, I have added it below.</p>
<p>This is PHP with database call which is called by AJAX</p>
<pre><code> if(isset($_POST["userLoginSubmit"]) == true){
if(!isset($_SESSION["userID"])){
userLogin(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL), $_POST["password"]);
}
}
function userLogin($email, $password){
$return = [
"email" => "",
"password" => "",
"error" => false
];
if(empty($email)){
$return["email"] = "empty";
$return["error"] = true;
}
if(empty($password)){
$return["password"] = "empty";
$return["error"] = true;
}
if($return["error"] == true){
echo(json_encode($return));
return false;
}
$dbConnect = new DbConnect;
$dbDoConnect = $dbConnect->doConnectFromOutside();
$selectCommand = "SELECT *
FROM users
WHERE email = :email LIMIT 1";
$data = $dbDoConnect->prepare($selectCommand);
$data->bindValue(":email", $email, PDO::PARAM_STR);
if(!$data->execute()){
$return['error'] = "connection";
echo(json_encode($return));
return false;
}
if($data->rowCount() > 0){
$selectedData = $data->fetch(PDO::FETCH_ASSOC);
} else{
$return["email"] = "free";
echo(json_encode($return));
return false;
}
if(!password_verify($password, $selectedData["password"])){
$return["password"] = "badPassword";
echo(json_encode($return));
return false;
}
$_SESSION["userID"] = $selectedData["userID"];
$_SESSION["firstName"] = $selectedData["firstName"];
$_SESSION["lastName"] = $selectedData["lastName"];
$_SESSION["email"] = $selectedData["email"];
$return["error"] = "success";
echo(json_encode($return));
return true;
}
</code></pre>
<p>This is login form</p>
<pre><code><div class='signIn'>
<i class='fas fa-times fa-2x accountPopupSwitch'></i>
<h1>přihlášení</h1>
<p>NEMÁM ŮČET A&nbsp;<a href='#' class='changeForm preventDefault'>CHCI HO VYTVOŘIT</a></p>
<form method='POST' name='userLogin' id='userLogin'>
<input type='email' id='userLoginEmail' name='email' placeholder='Váš email' class='removableVal'>
<label for='userLoginEmail' id='userLoginEmailLabel' class='removableVal'></label>
<input type='password' id='userLoginPassword' name='password' placeholder='Heslo' class='removableVal'>
<label for='userLoginPassword' id='userLoginPasswordLabel' class='removableVal'></label>
<p id='userLoginMessage'></p>
<button type='submit' id='userLoginSubmit'>PŘIHLÁSIT SE</button>
</form>
<p>NEMÁM ŮČET A&nbsp;<a href='#' class='changeForm preventDefault'>CHCI HO VYTVOŘIT</a></p>
</div>
</code></pre>
<p>And this is AJAX which is submitted when user try to log in</p>
<pre><code>$("#userLogin").submit(function(event){
event.preventDefault();
var email = $("#userLoginEmail").val(),
password = $("#userLoginPassword").val();
$("#userLoginSubmit").html("<i class='fas fa-sync'></i>");
$.ajax({
method: "POST",
url: "accountPopupFunctions.php",
data: {
email: email,
password: password,
userLoginSubmit: true
},
dataType: "json",
success: function(loginResults){
$("#userLoginPasswordLabel, #userLoginEmailLabel, #userLoginMessage").removeClass("error").html("");
$("#userLoginPassword").val("");
$("#userLoginSubmit").html("PŘIHLÁSIT SE");
if(loginResults["email"] == "empty") $("#userLoginEmailLabel").addClass("error").html("nevyplněný email");
if(loginResults["email"] == "free") $("#userLoginEmailLabel").addClass("error").html("neexistující email");
if(loginResults["password"] == "empty") $("#userLoginPasswordLabel").addClass("error").html("nevyplněné heslo");
if(loginResults["password"] == "badPassword") $("#userLoginPasswordLabel").addClass("error").html("špatné heslo");
if(loginResults["error"] == "connection") $("#userLoginMessage").addClass("error").html("Chyba v připojení (#003).");
if(loginResults["error"] == "success"){
localStorage.setItem('logged', true);
localStorage.removeItem('loggedOut');
localStorage.removeItem('loggedPopup');
localStorage.removeItem('unlogedPopup');
$(location).attr("href", "index.php");
}
},
error: function(){
$("#userLoginMessage").addClass("error").html("Něco se pokazilo (#003).");
$("#userLoginSubmit").html("PŘIHLÁSIT SE");
}
});
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T04:27:03.317",
"Id": "479814",
"Score": "0",
"body": "Dont sanitize user input. Validate it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T06:43:22.607",
"Id": "479822",
"Score": "0",
"body": "@slepic Both. Both is good. Not either, both."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T08:23:52.897",
"Id": "479829",
"Score": "4",
"body": "Mixing `\"firstName\"` with `\"fistName\"` is doomed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T08:58:13.210",
"Id": "479834",
"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-24T10:16:10.617",
"Id": "479841",
"Score": "0",
"body": "Ah, I messed it up. edited"
}
] |
[
{
"body": "<ol>\n<li><p><s>First and foremost, I don't really like the idea of an ajax login because imagine the user is on a public device and logs in then steps away from the computer and someone else pulls up to the browser, opens up the Developer tools > Network > XHR > Headers and gets an eyeful of the login credentials that were sent off for logging in. Is it a bit "tinfoil hat"? Is it the user's responsibility? Yeah, maybe, but there will be users that will be blissfully unaware of this vulnerability. Once a bad actor can infiltrate the parts of your system that are password protected, they may be able to cause more significant trouble in the application. </s> See @Kazz's argument against my claim which I find correct and invalidates my concern.</p>\n</li>\n<li><p>I agree with @slepic, don't bother sanitizing user input. If they are fouling up their submitted data and you "fix" it for them, then you may be damaging their UX because what they typed is not being entered into your system as they expected.</p>\n</li>\n<li><p>I prefer to write my file assets (includes / function declarations) at the top of my file unless there is a logical reason to postpone the deed. Perhaps you don't want to load/declare certain assets until the user's submission has passed qualifying checkpoints. In doing so, the "flow" of your script will be uninterrupted visually (to the human developer).</p>\n</li>\n<li><p>In all places where you are writing <code>== true</code>, just omit it. The loose comparison on true is the same as the expression with the last 7 characters.</p>\n</li>\n<li><p>Combine <code>if(isset($_POST["userLoginSubmit"]) == true){ if(!isset($_SESSION["userID"])){</code><br>to become <code>if (isset($_POST["userLoginSubmit"]) && !isset($_SESSION["userID"])) {</code>.</p>\n</li>\n<li><p>I don't see any reason to <code>return true|false</code> from your function call. I mean, the return value from <code>userLogin()</code> is never used for anything. It probably makes better sense to <code>exit(json_encode($return));</code></p>\n</li>\n<li><p>I certainly hope that the <code>email</code> column in your table is a UNIQUE KEY because you wouldn't want multiple people sharing an identity. Assuming so, there is reason to explicitly write <code>LIMIT 1</code>.</p>\n</li>\n<li><p>Your prepared statement looks okay. I'd probably not bother declaring the single-use variable -- I'd just write the sql string directly into the <code>prepare()</code> call.</p>\n</li>\n<li><p><code>connection</code> is a somewhat inappropriate description of the error. It might not be a connection error. But either way, it is good that you are not sending the raw error to the user.</p>\n</li>\n<li><p>I don't think that I would bother with <code>rowCount()</code>, I'd just check if the fetched result set was <code>null</code>.</p>\n</li>\n<li><p>Simplify the <code>SESSION</code> declaration block like this:</p>\n<pre><code>$_SESSION = [\n "userID" => $selectedData["userID"],\n "firstName" => $selectedData["firstName"],\n "lastName" => $selectedData["lastName"],\n "email" => $selectedData["email"],\n];\n</code></pre>\n</li>\n<li><p><code>$return["error"] = "success";</code> is an oxymoron. I think it would be more sensible to set the value to <code>0</code> or <code>""</code> or <code>false</code>. A falsey value will also make checking the value simpler in the javascript.</p>\n</li>\n<li><p>I don't see it in your question, but I hope you are calling <code>start_session()</code> somewhere.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T02:20:55.347",
"Id": "479945",
"Score": "0",
"body": "Hrmm, now I am second guessing myself about struckthough point 1. I ran a test in my local environment where `location.href` is used after a successful login. The login credentials remained in the developer tools after the new page was loaded and even after I navigated to additional pages. Am I testing this incorrectly @Kazz?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T02:27:18.383",
"Id": "479946",
"Score": "0",
"body": "Ah I guess the Network tab would need to have been left open while logging in. That's not something that the average user would do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T07:10:49.390",
"Id": "479962",
"Score": "0",
"body": "there is an option to record network requests, which is by default enabled, once you open the network tab in developer tools, you can see even classic form submit there, which persist through requests. As you said that's not what regular users do."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T13:27:11.733",
"Id": "244445",
"ParentId": "244413",
"Score": "3"
}
},
{
"body": "<p>Just in my opinion, take this with grain of salt.\nYou don't need that at all:</p>\n<pre><code>$return = [\n "email" => "",\n "password" => "",\n "error" => false\n];\n</code></pre>\n<p>Ajax response data type could be just a text, one of these: [bad credentials, error, success], you should validate if email or password is empty before even sending a request, on server side simply check if either of them is empty and if so just print "error" (because if that happen, someone is bypassing your script and sending custom data, therefore you don't have to bother to sending back appropriate error). It's a good practice to not show if an email is registered on your website, so email not present in your database or bad password should be merged to "bad credentials".</p>\n<p>Ad to mickmackusa 1) Ajax login is good if you redirect page after successfully login, which you do with: <code>$(location).attr("href", "index.php");</code> that clear the xhr from developer tools.</p>\n<p>So your code could look like this:</p>\n<pre><code>if(isset($_POST["userLoginSubmit"]) && !isset($_SESSION["userID"])){\n userLogin($_POST["email"], $_POST["password"]);\n}\n\nfunction userLogin($email, $password){\n if(empty($email) || empty($password)\n || !filter_var($email, FILTER_VALIDATE_EMAIL) // server side email validation\n ){\n exit("error"); // custom data, script bypass\n }\n\n $dbConnect = new DbConnect;\n $dbDoConnect = $dbConnect->doConnectFromOutside();\n // if(!$dbDoConnect) { exit("connection") } // if you wanna check for connection should be something like that\n $data = $dbDoConnect->prepare("SELECT * FROM users WHERE email = :email"); // LIMIT 1 not needed because email is unique key \n $data->bindValue(":email", $email, PDO::PARAM_STR);\n if(!$data->execute()){\n exit("error"); // internal error (bad query)\n }\n \n $selectedData = $data->fetch(PDO::FETCH_ASSOC);\n if(!$selectedData || !password_verify($password, $selectedData["password"])){\n exit("bad-credentials");\n }\n\n $_SESSION = [\n "userID" => $selectedData["userID"],\n "firstName" => $selectedData["firstName"],\n "lastName" => $selectedData["lastName"],\n "email" => $selectedData["email"],\n ];\n\n exit("success");\n}\n\n\n$("#userLogin").submit(function(event){\n event.preventDefault();\n var email = $("#userLoginEmail").val(),\n password = $("#userLoginPassword").val();\n if(!email){ // if it's actually email is done by: input type='email'\n $("#userLoginEmailLabel").addClass("error").html("nevyplněný email");\n }\n if(!password){\n $("#userLoginPasswordLabel").addClass("error").html("nevyplněné heslo");\n }\n if(!email || !password) return;\n $("#userLoginSubmit").html("<i class='fas fa-sync'></i>");\n\n $.ajax({\n method: "POST",\n url: "accountPopupFunctions.php",\n data: {\n email: email,\n password: password,\n userLoginSubmit: true\n },\n dataType: "text",\n success: function(loginResult){\n $("#userLoginPasswordLabel, #userLoginEmailLabel, #userLoginMessage").removeClass("error").html("");\n $("#userLoginPassword").val(""); // btw you don't have to clear password, that's advantage of using ajax login\n $("#userLoginSubmit").html("PŘIHLÁSIT SE");\n\n if(loginResult == "error") $("#userLoginMessage").addClass("error").html("Něco se pokazilo (#003).");\n if(loginResult == "bad-credentials") $("#userLoginMessage").addClass("error").html("Spatný email nebo heslo.");\n if(loginResult == "success"){\n localStorage.setItem('logged', true);\n localStorage.removeItem('loggedOut'); // these seem not necessary, check for the above instead\n localStorage.removeItem('loggedPopup');\n localStorage.removeItem('unlogedPopup');\n $(location).attr("href", "index.php");\n }\n\n },\n error: function(){\n $("#userLoginMessage").addClass("error").html("Něco se pokazilo (#003).");\n $("#userLoginSubmit").html("PŘIHLÁSIT SE");\n }\n\n });\n});\n</code></pre>\n<p>Much simpler isn't it ?</p>\n<p>You can do it without ajax if you want to, by just printing script that shows the popup on page load (with the error messages).</p>\n<p>Use sanitizing whenever you printing user input on your pages (XSS attack), you don't have to sanitize the inputs from post because that's done already by prepared statement (only for SQL !).</p>\n<p>By the way, instead: <code><a href='#' class='changeForm preventDefault'>CHCI HO VYTVOŘIT</a></code> you can do this: <code><a href='javascript:;' class='changeForm'>CHCI HO VYTVOŘIT</a></code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T01:10:55.277",
"Id": "479941",
"Score": "1",
"body": "I think a deliberate amount of sanitizing/validating is important prior to adding data to the database to prevent second order attacks. https://medium.com/@fiddlycookie/the-wrath-of-second-order-sql-injection-c9338a51c6d"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T06:56:10.807",
"Id": "479961",
"Score": "0",
"body": "You are right @mickmackusa, I hope he use prepared statements across whole application, not just on registration/login, which do avoid this kind of attack without sanitizing input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T13:18:20.893",
"Id": "479988",
"Score": "0",
"body": "And what if someone write <script> or <?php and saves it into the database with recensions and after that he will load recensions and that code will be there? I tried it and it did not do nothing, but maybe it is because these recensions printing prepend function. Script was cloced after recension text and some divs and php commented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T13:28:00.357",
"Id": "479989",
"Score": "0",
"body": "And if I write <script>alert('Hello! I am an alert box!');</script> it will do it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T14:35:31.980",
"Id": "479998",
"Score": "0",
"body": "@TomášKretek As I wroted above \"Use sanitizing whenever you printing user input on your pages (XSS attack)\", that means that if you print for example the script with alert you wroted above you do it as: `htmlspecialchars($userinput)` and then it become harmless text. If you do sanitizing before inserting to the db, you may end up doing it more times (edit for example) and `<` will end up beeing `&lt;` so just before printing is good enough, if you use some templates for example latte its done automatically. The `<?php` do nothing to your app because you would have to `eval()` it ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T14:52:47.143",
"Id": "480000",
"Score": "0",
"body": "note that `htmlspecialchars` is enough if you print user input to the html area but if you print it to the tag attribute you need `ENT_QUOTES` flag, for javascript area you need additional escaping `addslashes`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T23:04:35.760",
"Id": "244473",
"ParentId": "244413",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T23:12:25.683",
"Id": "244413",
"Score": "1",
"Tags": [
"javascript",
"php",
"security",
"ajax",
"pdo"
],
"Title": "Is this code written safe from attacks?"
}
|
244413
|
<p><strong>The task:</strong></p>
<blockquote>
<p>Determine if a word or phrase is an isogram.
An isogram (also known as a "nonpattern word") is a word or phrase without a repeating letter, however spaces and hyphens are allowed to appear multiple times.</p>
</blockquote>
<p><strong>Examples of isograms:</strong></p>
<ul>
<li>lumberjacks</li>
<li>background</li>
<li>downstream</li>
<li>six-year-old</li>
</ul>
<p><em>The word isograms, however, is not an isogram, because the s repeats.</em></p>
<p>Even though I'm aware that questions about isograms have already been posted, in this variation of the problem spaces and hyphens are allowed to appear multiple times so that you can not use a solution such as <code>len(string) == len(set(string))</code></p>
<p>What bothers me about my solution is hardcoding bounds of <code>ascii</code> character ranges and using <code>collections</code> library for such a small problem. I'm wondering if there is a better way to do it.</p>
<p>Here is my code:</p>
<pre><code>from collections import Counter
ASCII_LOWER_BOUND = 97
ASCII_UPPER_BOUND = 123
def is_isogram(string):
char_counts = Counter(string.lower())
return all(
char_counts[char] == 1
for char in char_counts
if ord(char) in range(ASCII_LOWER_BOUND, ASCII_UPPER_BOUND + 1)
)
</code></pre>
<p>And a test suite provided by exercism:</p>
<pre><code>import unittest
from isogram import is_isogram
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.7.0
class IsogramTest(unittest.TestCase):
def test_empty_string(self):
self.assertIs(is_isogram(""), True)
def test_isogram_with_only_lower_case_characters(self):
self.assertIs(is_isogram("isogram"), True)
def test_word_with_one_duplicated_character(self):
self.assertIs(is_isogram("eleven"), False)
def test_word_with_one_duplicated_character_from_the_end_of_the_alphabet(self):
self.assertIs(is_isogram("zzyzx"), False)
def test_longest_reported_english_isogram(self):
self.assertIs(is_isogram("subdermatoglyphic"), True)
def test_word_with_duplicated_character_in_mixed_case(self):
self.assertIs(is_isogram("Alphabet"), False)
def test_word_with_duplicated_character_in_mixed_case_lowercase_first(self):
self.assertIs(is_isogram("alphAbet"), False)
def test_hypothetical_isogrammic_word_with_hyphen(self):
self.assertIs(is_isogram("thumbscrew-japingly"), True)
def test_hypothetical_word_with_duplicated_character_following_hyphen(self):
self.assertIs(is_isogram("thumbscrew-jappingly"), False)
def test_isogram_with_duplicated_hyphen(self):
self.assertIs(is_isogram("six-year-old"), True)
def test_made_up_name_that_is_an_isogram(self):
self.assertIs(is_isogram("Emily Jung Schwartzkopf"), True)
def test_duplicated_character_in_the_middle(self):
self.assertIs(is_isogram("accentor"), False)
def test_same_first_and_last_characters(self):
self.assertIs(is_isogram("angola"), False)
if __name__ == "__main__":
unittest.main()
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h1>ord()</h1>\n<p>Do not define constants like <code>ASCII_LOWER_BOUND</code>, use <code>ord('a')</code>. Easy to read, no uncertainty about the value.</p>\n<h1>character range/set</h1>\n<p>Do not use an integer range and ord(). It is error prone and hard to review.</p>\n<pre><code>if ord(char) in range(ASCII_LOWER_BOUND, ASCII_UPPER_BOUND + 1)\n</code></pre>\n<p>rewrites to</p>\n<pre><code>import string\nif char in string.ascii_lowercase\n</code></pre>\n<p>No off by one, easy to read. If the test has to be very fast prepare a set.</p>\n<h1>generator expression</h1>\n<p><code>Counter</code> is derived from <code>dict</code>. So instead of</p>\n<pre><code>(char_counts[char] == 1 for char in char_counts if char in string.ascii_lowercase)\n</code></pre>\n<p>we do use <code>dict().items()</code></p>\n<pre><code>(count == 1 for char, count in char_counts.items() if char in string.ascii_lowercase)\n</code></pre>\n<h1>Naming</h1>\n<p>In general you should try to avoid names that hide common python names. As we want to import string we need a different name for the parameter.</p>\n<pre><code>from collections import Counter\nimport string\n\ndef is_isogram(word):\n char_counts = Counter(word.lower())\n return all(count == 1 for char, count in char_counts.items() if char in string.ascii_lowercase)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T01:13:33.490",
"Id": "479805",
"Score": "0",
"body": "Actually ```string``` paramater name is used by Exercism. Don't understand why you loop through ```char_counts.items()``` instead of original ```char_counts```."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T16:51:59.080",
"Id": "479889",
"Score": "2",
"body": "looping - By iterating over `char_counts` I get the keys only. By iterating over `char_counts.items()` I get key/value pairs. I can use `count` directly without having to dereference `char_counts[char]`. This is more efficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T06:44:29.970",
"Id": "479960",
"Score": "0",
"body": "a `set` is better for a containment check than a `str`, so I would do `lower_cases = set(string.ascii_lowercase)` and then later `if char in lower_cases`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T07:14:45.970",
"Id": "479963",
"Score": "0",
"body": "@Maarten. My words above :-)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T00:56:04.303",
"Id": "244417",
"ParentId": "244414",
"Score": "2"
}
},
{
"body": "<p>You can iterate once over text and short-circuit right away if any character is not unique.</p>\n<pre><code>import string\n\n\ndef is_isogram(text):\n seen = set()\n for char in text:\n if (lower := char.lower()) in string.ascii_lowercase:\n if lower in seen:\n return False\n else: \n seen.add(lower)\n return True\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T16:14:03.547",
"Id": "480014",
"Score": "0",
"body": "What does ```:=``` mean in Python?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T06:09:44.337",
"Id": "480084",
"Score": "0",
"body": "This is [assignment expression](https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions) also known as 'walrus operator' available starting from Python 3.8"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T05:47:22.673",
"Id": "244486",
"ParentId": "244414",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244417",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T00:02:45.223",
"Id": "244414",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"strings"
],
"Title": "Exercism: determine if a word or phrase is an isogram"
}
|
244414
|
<p>In a game of <em>Tic-TacToe</em> given a gamestate:</p>
<pre><code>game_board = [ [1, 0, 1],
[0, 1, 0],
[0, 1, 0] ]
</code></pre>
<p>I have written the following piece of code to display the output of the gamestate in regards to wins:</p>
<pre><code>game_board = [ [1, 1, 1],
[0, 1, 0],
[0, 1, 0] ]
# Horizontals
h = [str(i+1) + ' Row' for i, v in enumerate(game_board) if sum(v) == 3]
# Verticals
v = [str(i+1) + ' Col' for i in range(3) if sum([j[i] for j in game_board]) == 3]
# Diagonals
d = [['Left Diag', '','Right Diag'][i+1] for i in [-1, 1] if sum([game_board[0][1+i], game_board[1][1]], game_board[2][1-i]) == 3]
if any([h,v,d]):
print('You won on:', h, v, d)
else:
print('No win yet')
</code></pre>
<p>The output of this is:</p>
<pre class="lang-none prettyprint-override"><code>You won on: ['1 Row'] ['2 Col'] []
</code></pre>
<p>I would like to know how my solution could be written in a more Pythonic manner?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T04:18:49.930",
"Id": "479810",
"Score": "1",
"body": "I would do `['Row 1'], ['Col 2'], []` but that's just me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T05:17:20.323",
"Id": "479819",
"Score": "0",
"body": "@Linny - good suggestion!"
}
] |
[
{
"body": "<p>Not sure about whether a solution could be more <code>Pythonic</code>, but I think it can be more efficient. At present your code is iterating over each cell twice, before anything is printed.</p>\n<p>I would suggest using a collection of possible winning strings. You only need to iterate over the cells once and each time you encounter a <code>0</code> that row, col and if applicable, diagonal become invalid as a winning line.</p>\n<p>After that, it's a simple matter of iterating over the strings and printing the ones that are valid.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T06:41:54.307",
"Id": "479821",
"Score": "0",
"body": "I like that approach and it makes sense -- I'll have a try with that idea"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T06:45:42.553",
"Id": "479823",
"Score": "0",
"body": "So a `0` in the center eliminates the possibility of a win in the diagonals and crosses, then a `0` in a corner will eliminate the corresponding row-column - thanks for the valuable answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T15:22:55.013",
"Id": "479878",
"Score": "1",
"body": "@leopardxpreload - Just an fyi for you. If row == col the cell belongs to left diag. If row + col == 2 it belongs to the right diag."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T05:59:01.000",
"Id": "244424",
"ParentId": "244420",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T03:17:08.983",
"Id": "244420",
"Score": "1",
"Tags": [
"python",
"game",
"tic-tac-toe"
],
"Title": "Given a Tic-Tac-Toe gamestate return all wins as text"
}
|
244420
|
<p>I'm working on a solution to the <a href="https://www.hackerrank.com/challenges/between-two-sets/problem" rel="noreferrer">Following</a> problem on Hackerrank, and I seem to have found a function that works for the purpose.
However, I feel as though this is a very overdesigned solution to a problem that appears, at first glance, to be simple. This is what I've come up with so far:</p>
<p>This code takes in two arrays, finds every pair of numbers from 1 to 100, multiplies them together, and tests if the product is a factor of all elements in the first array. If so, it appends the product to the fact array. Then, it tests every element in the fact array and checks if the element evenly divides every element in the second array. If so, it loads that element into a new list. Finally, it returns the length of the new list</p>
<p>I've run the code through a few static analyzers but they became unhelpful after a point. I'm looking for ways to cut this code down and reduce its complexity and depth. Any comments or criticisms are welcome!</p>
<p>Apologies if I've made any mistakes in my question-asking etiquette here, feel free to let me know if this needs more context and thanks in advance!</p>
<pre><code>def get_total_x(input_factors: int, test_numbers: int) -> int:
fact = list()
output = list()
for mult1 in range(100):
for mult2 in range(100):
# find all multiples of mult1 and mult2 that can be factored
# into all numbers in a, while ignoring zero.
if all(v == 0 for v in [(mult1 * mult2) % factor for factor in input_factors]) and (mult1 * mult2 != 0):
fact.append(mult1 * mult2)
seen = set()
seen_add = seen.add
# remove duplicates, may be able to cut out?
fact = [x for x in fact if not (x in seen or seen_add(x))]
for test in fact:
# check for all numbers from the previous loop that divide b cleanly.
if all(w == 0 for w in [factor2 % test for factor2 in test_numbers]):
output.append(test)
return len(output)
if __name__ == '__main__':
arr = (2, 4)
brr = (16, 32, 96)
total = get_total_x(arr, brr)
print(total)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T08:13:07.640",
"Id": "479828",
"Score": "1",
"body": "You've done quite well, I guess you have digested [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T18:16:50.573",
"Id": "479896",
"Score": "0",
"body": "@greybeard of course! Thanks!"
}
] |
[
{
"body": "<h1>Redundant calculations</h1>\n<p>You calculate <code>mult1 * mult2</code> three times. Instead, do this once, assign it to a variable, and use that.</p>\n<hr>\n<p>Since you want to never want to calculate when a value is <code>0</code>, you can set the start of <code>range</code> to <code>1</code>.</p>\n<pre><code>range(1, 101) # 1 -> 100, since (inclusive, exclusive)\n</code></pre>\n<p>Now you can remove that <code>(product != 0)</code> check.</p>\n<h1>Type hints</h1>\n<p>At first, it looks like the function accepts two integers. In reality, it accepts two <em>tuples</em> of integers. Consider doing the following:</p>\n<pre><code>from typing import Tuple\n\ndef get_total_x(input_factors: Tuple[int], test_numbers: Tuple[int]) -> int:\n</code></pre>\n<p>This makes it clear that you want tuples of integers as parameters, instead of a single integer.</p>\n<h1>Using sets</h1>\n<p>You use a set, but you don't actually <em>use</em> the set. You're trying to add values to the set that aren't already there, or that you can add to the set. Instead of having that list comprehension, simply cast <code>fact</code> into a set. Does the exact same thing.</p>\n<pre><code>fact = set(fact)\n</code></pre>\n<h1>Magic numbers</h1>\n<p>What is the significance of <code>100</code>? I see in your question you explain, but not in the code. I would assign this to a variable to make it more clear.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T06:17:51.123",
"Id": "244425",
"ParentId": "244422",
"Score": "6"
}
},
{
"body": "<p>Instead of writing a nested <code>for</code> loop, directly write it as a list comprehension. In addition, you can start the second loop at the value of the outer variable in order to remove some double counting. This reduces the numbers to iterate over from 9801 to 4950, by a factor two, since you don't have both e.g. 2 * 6 and 6 * 2. However, some values still appear more than once (since e.g. 12 is 2 * 6, but also 3 * 4 and 1 * 12), so you still need a set comprehension:</p>\n<pre><code>limit = 100\nfact = {a * b for a in range(1, limit) for b in range(a, limit)\n if all(i % factor == 0 for factor in input_factors)}\n</code></pre>\n<p>Note that I directly used <code>i % factor</code> in the loop in <code>all</code>. No need to involve an addition list comprehension to iterate over.</p>\n<p>You should also just count the results, don't append them to a list if you only care about its length:</p>\n<pre><code>return sum(1 for f in fact if all(test % f == 0 for test in test_numbers))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T07:38:34.777",
"Id": "244428",
"ParentId": "244422",
"Score": "2"
}
},
{
"body": "<h1>Algorithm</h1>\n<p>You do a nested loop which is completely without reason</p>\n<pre><code>for mult1 in range(100):\n for mult2 in range(100):\n # find all multiples of mult1 and mult2 that can be factored\n # into all numbers in a, while ignoring zero.\n if all(v == 0 for v in [(mult1 * mult2) % factor for factor in input_factors]) and (mult1 * mult2 != 0):\n fact.append(mult1 * mult2)\n</code></pre>\n<p>In the loop you use the counters only in a way <code>mult1 * mult2</code>. This results in</p>\n<ul>\n<li>199 element of the value <code>0</code> which you remove in a special clause</li>\n<li>the biggest value being tested to be <code>99*99</code> which is <code>9801</code> which is far bigger than the maximum number to factor</li>\n<li>typical realistic numbers being duplicated (e. g. <code>16</code> is generated 5 times)</li>\n<li>10000 tests for less than 100 realistic candidates</li>\n</ul>\n<p>For the zeros you have a special clause and a comment for clarification. You should not generate the zeros beforehand, loop over <code>range(1, ...)</code></p>\n<p>If wee look at the problem we see that a and b are in <code>range(1, 101)</code>. Any solution must be greater or equal to <code>max(a)</code>.\nIt also must be less or equal to <code>min(b)</code>. So it is completely sufficient to search <code>range(max(a), min(b)+1)</code>. We can improve the efficiency even a little more and step by <code>max(a)</code>.</p>\n<h1>Removing duplicates</h1>\n<p>If the looping is done right we do not need to remove duplicates any more. However, if you have to do de-duplication decide whether you need to preserve the order. In your code you do de-duplication while maintaining order. As maintaining order is not needed in this problem, you can simply create a set from the list. Depending on the application you may want to create a list from the set again.</p>\n<pre><code>fact = set(fact)\n</code></pre>\n<h1>Names</h1>\n<p>It is helpful to stick to the names given in the problem. That maintains readability.</p>\n<p>We end up in a function like</p>\n<pre><code>def get_total_x(a: Tuple[int], b: Tuple[int]) -> int:\n numbers = []\n for i in range(max(a), min(b) + 1, max(a)):\n if all(i % a_i == 0 for a_i in a) and all(b_i % i == 0 for b_i in b):\n numbers.append(i)\n return len(numbers)\n</code></pre>\n<p>The function still misses documentation (and a better name). Type hints see @Linnys answer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T08:15:55.757",
"Id": "244431",
"ParentId": "244422",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244425",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T05:13:22.020",
"Id": "244422",
"Score": "5",
"Tags": [
"python",
"beginner",
"algorithm",
"python-3.x"
],
"Title": "Find all numbers that are factors of one array and factor into the second array, then print their count"
}
|
244422
|
<p>I am creating Monopoly using react hooks. I am using cypress for testing it. The first test I have to create is to check about dice rolls. I have three tests in which I am repeating the same kind of code. How can I refactor this?</p>
<pre><code>//A funcction to get the rolls of dice in number
function getDiceRolls() {
const dices = Cypress.$(".dice");
return [dices[0].children.length, dices[1].children.length];
}
//Get the player who has the current turn
function getActiveTurn() {
const playerTabHeads = Cypress.$(".player-tab-head");
return playerTabHeads
.toArray()
.findIndex((head) => head.classList.contains("active"));
}
//Get the total number of players
function getNoOfPlayers() {
return Cypress.$(".player-tab-head").toArray().length;
}
//Get the 'piece' element of the required player
function getPiece(id: number) {
return Cypress.$(".piece.small.piece-" + id);
}
//Get the tile no in which a player is standing
function getTileNoOfPiece(id: number) {
return +((getPiece(id).toArray()[0].parentNode!.parentNode as HTMLElement)
.dataset.tileno as string);
}
//Get owner of specific tile
function getOwnerOfTile(tile: ITile) {
const playerTabBodies = Cypress.$(".player-tab-body").toArray();
return playerTabBodies.findIndex((playerTabBody) => {
const propCards = Array.from(
playerTabBody.querySelectorAll(".prop-card")
);
return propCards.some((propCard) => propCard.innerHTML === tile.name);
});
}
//Get the money of specified player
function getMoneyOfPlayer(playerNo: number) {
return Number(
Cypress.$(".player-tab-head")
.toArray()
[playerNo].querySelector(".player-money")
?.innerHTML.replace("$", "")
);
}
//Get all the 40 objects
let allTiles: ITile[];
before(() => {
cy.fixture("allTiles").then((data) => {
allTiles = data;
});
});
describe("Rolling System", function () {
beforeEach(() => {
cy.visit("localhost:3000");
});
//TO CHECK BUTTON DISABLING
it("disables button correctly", function () {
//To keep track of roll button
let isRollDisabled = false;
for (let i = 0; i < 100; i++) {
cy.wait(100).then(() => {
//End turn if roll button is disabled(means can't roll)
if (isRollDisabled) {
if (Cypress.$(".btn-buy-prop").length > 0) {
cy.get(".btn-buy-prop").click();
}
cy.wait(100).then((x) => {
cy.get(".btn-end-turn").click();
isRollDisabled = false;
});
}
//Roll the die
else {
let roll1: number;
let roll2: number;
cy.get(".btn-roll")
.click()
.then(() => {
[roll1, roll2] = getDiceRolls();
//If doubles are not rolled disable roll btn
if (roll1 !== roll2) {
cy.get(".btn-roll").should("be.disabled");
isRollDisabled = true;
}
//Otherwise it should be disabled
else {
cy.get(".btn-roll").should("not.be.disabled");
}
});
}
});
}
});
//Check the movement
it("Moves correctly", function () {
let isRollDisabled = false;
//To keep track of previous position of each piece
let oldPositions: number[] = [];
for (let i = 0; i < 20; i++) {
cy.wait(100).then(() => {
let activeTurn: number;
let totalRoll: number;
//End turn
if (isRollDisabled) {
if (Cypress.$(".btn-buy-prop").length > 0) {
cy.get(".btn-buy-prop").click();
}
cy.get(".btn-end-turn").click();
isRollDisabled = false;
}
//Roll die
else {
let roll1: number;
let roll2: number;
cy.get(".btn-roll")
.click()
.then((x) => {
//Get the total roll
[roll1, roll2] = getDiceRolls();
totalRoll = roll1 + roll2;
//Disable button if no doubles are rolled
if (roll1 !== roll2) {
cy.log("Roll is disabled");
isRollDisabled = true;
}
})
.then(() => {
//Fill old positions is empty fill it with 0's
if (oldPositions.length === 0) {
oldPositions = Array(getNoOfPlayers()).fill(0);
}
//Get current Tile no
activeTurn = getActiveTurn();
let tileNoOfActivePiece = getTileNoOfPiece(activeTurn);
let newPosition = oldPositions[activeTurn] + totalRoll;
if (newPosition > 39) {
newPosition -= 40;
}
//Calculate the new expected position
oldPositions[activeTurn] = newPosition;
expect(tileNoOfActivePiece).to.be.equal(newPosition);
});
}
});
}
});
//Test the result of landing on tile.
it("Give tile landing response", function () {
let isRollDisabled = false;
for (let i = 0; i < 100; i++) {
cy.wait(100).then(() => {
let activeTurn: number = getActiveTurn();
let totalRoll: number;
let money: number = getMoneyOfPlayer(activeTurn);
//End turn
if (isRollDisabled) {
if (Cypress.$(".btn-buy-prop").length > 0) {
cy.get(".btn-buy-prop").click();
}
cy.get(".btn-end-turn").click();
isRollDisabled = false;
}
//Roll die
else {
let roll1: number;
let roll2: number;
cy.get(".btn-roll")
.click()
.then((x) => {
//Get the total roll
[roll1, roll2] = getDiceRolls();
totalRoll = roll1 + roll2;
//Disable button if no doubles are rolled
if (roll1 !== roll2) {
cy.log("Roll is disabled");
isRollDisabled = true;
}
})
.then(() => {
//Fill old positions is empty fill it with 0's
//Get current Tile no
console.log(money.toString());
let tileNoOfActivePiece = getTileNoOfPiece(activeTurn);
let tile = allTiles[tileNoOfActivePiece];
let ownerOfTile = getOwnerOfTile(tile);
//Normal Properties
if (ownerOfTile === -1 && tile.price) {
//Shows the big prop card
cy.log("Shows the prop card");
cy.get(".big-prop-card")
.should("be.visible")
.should("contain", tile.name);
//Buying the property
cy.get(".btn-buy-prop")
.click()
.then(() => {
//Change the owner
const newOwnerOfTile = getOwnerOfTile(tile);
expect(newOwnerOfTile).to.be.eq(activeTurn);
//Decreases money
const newMoneyOfPlayer =
money - (tile.price as number);
expect(newMoneyOfPlayer).to.be.eq(
getMoneyOfPlayer(activeTurn)
);
});
}
//Income taxes
else if (tile.type === "income-tax") {
console.log(money);
cy.log(money.toString());
expect(money - (tile.taxValue as number)).to.be.eq(
getMoneyOfPlayer(activeTurn)
);
}
});
}
});
}
});
</code></pre>
<p>In the above code I have to use <code>isRollDisabled</code> in each even when it's not required in the test. Kindly tell me the way to refactor the code.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T07:08:17.683",
"Id": "244427",
"Score": "1",
"Tags": [
"javascript",
"unit-testing",
"integration-testing"
],
"Title": "Cypress tests for Monopoly"
}
|
244427
|
<p>This is part of my code.</p>
<ol>
<li>List all files and read them into the list <code>files</code>.</li>
<li>Now I have a dictionary <code>my_dict</code>. The values are the parquet files. all files must have <strong>same schema</strong>.</li>
<li>I have more than 2000 files is my folder, so <code>files</code> is large.</li>
<li>For each file I firstly <code>gunzip</code> all of them.</li>
<li>Next I find all the JSON files.</li>
<li>Problem is here. My file <code>tick_calculated_2_2020-05-27T01-02-58.json</code> will be read and converted to dateframe and appended to <code>'tick-2.parquet'</code>.</li>
</ol>
<p>My code works but the execution time is very low. How do I get rid of one or more loops?</p>
<pre><code>def gunzip(file_path, output_path):
with gzip.open(file_path, "rb") as f_in:
with open(output_path, "wb") as f_out:
shutil.copyfileobj(f_in, f_out)
if __name__ == '__main__':
files = os.listdir('/Users/milenko/mario/Json_gzips')
files = [fi for fi in files if fi.endswith(".gz")]
my_dict = {'ticr_calculated_2': 'ticr-2.parquet', 'ticr_calculated_3': 'ticr-3.parquet', \
'ticr_calculated_4': 'ticr-4.parquet', 'tick_calculated_2': 'tick-2.parquet', \
'tick_calculated_3': 'tick-3.parquet', 'tick_calculated_4': 'tick-4.parquet'}
basic = '/Users/milenko/mario/Json_gzips/'
for file in files:
gunzip(file, file.replace(".gz", ""))
json_fi = glob.glob("*.json")
for key, value in my_dict.items():
filepath = basic + value
for f in json_fi:
if key in f:
result_df = pd.DataFrame()
with open(f, encoding='utf-8', mode='r') as i:
data = pd.read_json(i, lines=True)
result_df = result_df.append(data)
table_from_pandas = pa.Table.from_pandas(result_df)
pq.write_table(table_from_pandas, filepath)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T11:47:12.223",
"Id": "479843",
"Score": "0",
"body": "The `file` variable is only used on the first line of the outer loop. Why is the rest of the code also in the loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T14:05:34.153",
"Id": "479864",
"Score": "0",
"body": "Indentation error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T14:45:21.527",
"Id": "479875",
"Score": "0",
"body": "@JanneKarila Take a look now. How should I initialize my result_df? something is wrong. I want to read files into pd.dataframe and save them to respective parquet files."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T07:53:10.023",
"Id": "244429",
"Score": "2",
"Tags": [
"python"
],
"Title": "Building DataFrames from gz and json files"
}
|
244429
|
<p>For game AI development, I am currently using a slight modification on the DFS <a href="https://www.geeksforgeeks.org/find-number-of-islands/" rel="nofollow noreferrer">"count the islands"</a> problem (specification below) as a solution to the <code>One Hive Rule</code> for the game of <a href="https://en.wikipedia.org/wiki/Hive_(game)" rel="nofollow noreferrer">Hive</a>. This may not be the ideal solution so I am open to any other ideas if you note DFS is not the best approach. Thank you.</p>
<blockquote>
<p>Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.</p>
</blockquote>
<p>My version utilises a 2D map (matrix) which represents a <strong>hexagonal</strong> board for the game.</p>
<p>The differences are:</p>
<ul>
<li>My implementation uses hexagons so each cell has 6 neighbours, not 8</li>
<li><code>Blank</code>s represent 0s and anything else are 1s</li>
<li>My implementation <em>purposely stops</em> if/when it finds more than one island/hive</li>
</ul>
<p>My question is can the code be improved with regards to <em><strong>time complexity</strong></em>?</p>
<pre><code>from insects import Blank
class HiveGraph:
def __init__(self, board):
self.row = board.height
self.col = board.width
self.visited = [[False for _ in range(self.col)] for _ in range(self.row)]
self.graph = board.board
# A function to check if a given hexagon can be included in DFS
def is_safe(self, row, col):
# row number is in range,
# column number is in range,
# and hexagon is Blank and not yet visited
return (0 <= row < self.row and
0 <= col < self.col and
not self.visited[row][col] and
type(self.graph[row][col]) is not Blank)
# DFS for a 2D matrix. It only considers
# the 6 neighbours as adjacent pieces
def dfs(self, row, col):
print(row, col)
# These arrays are used to get row and
# column numbers of 6 neighbours
# of a given hexagon
if col % 2 == 1:
row_nbr = [-1, 0, 0, 1, 1, 1]
col_nbr = [ 0, -1, 1, -1, 0, 1]
else:
row_nbr = [-1, -1, -1, 0, 0, 1]
col_nbr = [-1, 0, 1, -1, 1, 0]
# Mark this hexagon as visited
self.visited[row][col] = True
# Recur for all connected neighbours
for k in range(6):
if self.is_safe(row + row_nbr[k], col + col_nbr[k]):
self.dfs(row + row_nbr[k], col + col_nbr[k])
def one_hive(self):
# Initialize count as 0 and traverse
# through the all hexagons of given matrix
count = 0
for row in range(self.row):
for col in range(self.col):
# If a hexagon not Blank and is not visited yet,
# then new hive found
if not self.visited[row][col] and type(self.graph[row][col]) is not Blank:
# Visit all hexagons in this hive
# and increment hive count
count += 1
if count > 1:
return False
self.dfs(row, col)
return True
</code></pre>
<p>Refer to this image for row, col matrix values for the layout of hexagons:
<a href="https://i.stack.imgur.com/MeKsG.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MeKsG.gif" alt="Hexagon encoding for matrix" /></a></p>
|
[] |
[
{
"body": "<p>Given there are only 22-28 tiles in a Hive game, the time complexity of the check probably doesn't matter much. Nevertheless, a modified scanline fill algorithm might be faster than a DFS. This <a href=\"https://stackoverflow.com/questions/12186729/adapting-scanline-fill-to-detect-discrete-objects\">answer</a> explains the algorithm fairly well. In this use case it might be easier to scan down the columns instead of across the rows.</p>\n<p>From the rules of the Hive game, it seems the "one hive rule" would need to be checked when a tile is put down on the playing field and when it is picked up from the playing field (e.g., to move it). When a tile is put down, it is sufficient to make sure it touches another tile (beside or on top).</p>\n<p>When a tile is picked up, it is necessary to make sure it's former neighbor tiles are still connected via another path. This may be trivial such as when the neighbors are adjacent, or may require searching for a path using a DFS, BFS, spanning tree, or fill/paint algorithm.</p>\n<p>In any case, the AI should know which tile is being moved, so it shouldn't be necessary to scan the hex grid. Just start from one of the tiles neighbors.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T05:53:20.027",
"Id": "244487",
"ParentId": "244430",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T08:10:20.467",
"Id": "244430",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"complexity"
],
"Title": "Improving time complexity for Count the Islands DFS"
}
|
244430
|
<p>I'm an experienced Java developer, however I don't have experience with reflection or Annotation classes. For fun, I tried to develop a CSV Reader class which can parse each row into a particular type.</p>
<p>Here is my code:</p>
<pre class="lang-java prettyprint-override"><code>package com.richardrobinson;
import java.io.BufferedReader;
import java.lang.annotation.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static java.util.Map.*;
/**
* This class allows CSV text files to conveniently be parsed into a stream objects of the specified type.
* <p>
* By default, CSVReader supports {@code Integer, Double, Character, String,} and {@code Boolean} types. Other types may be added via {@link CSVReader#registerParser(Class, Function)}
* <p>
* For example, given a class {@code Foo}:
* <pre>{@code
* class Foo {
* final Integer i;
* final String s;
*
* @CSVConstructor public Foo(Integer i, String s) {
* this.i = i;
* this.s = s;
* }
* }
* }</pre>
*
* and a {@link BufferedReader} {@code reader} whose contents are
* <pre>
* num,str
* 1;hello
* 2;world
* </pre>
*
* then the reader may be parsed via
* <pre>
* var csv = CSVReader.of(reader, Foo.class)
* .ignoringHeader()
* .withDelimiter(";")
* </pre>
*
* @param <T> the type of the objects. The class of {@code T} must have a constructor which satisfies the following properties:
* <ul>
* <li>It is annotated with {@link CSVConstructor}</li>
* <li>The number of parameters is no more than the number of fields per CSV line</li>
* <li>The types of the parameters must be a supported type.</li>
* </ul>
*
* @author Richard I. Robinson
*/
public class CSVReader<T> {
/**
* An annotation which may be applied to a constructor to indicate that such constructor should be used when being instantiated via {@link CSVReader}
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR})
public @interface CSVConstructor {}
private final BufferedReader reader;
private final Class<T> clazz;
private String delimiter = ",";
private boolean ignoreHeader = false;
private static final Map<Class<?>, Function<String, ?>> PARSERS = new HashMap<>(ofEntries(
entry(Integer.class, Integer::parseInt),
entry(Double.class, Double::parseDouble),
entry(Character.class, s -> s.charAt(0)),
entry(String.class, s -> s),
entry(Boolean.class, Boolean::parseBoolean)
));
/**
* Enables support for a type {@code T} for CSVReader instances in addition to the types supported by default
*
* @param cls the Class to add support for (for example, {@code Foo.class})
* @param parser a Function mapping a {@link String} to a {@code T}
* @param <T> the type corresponding to {@code cls}
*/
public static <T> void registerParser(Class<T> cls, Function<String, T> parser) {
PARSERS.put(cls, parser);
}
private CSVReader(BufferedReader reader, Class<T> clazz) {
this.reader = reader;
this.clazz = clazz;
}
/**
* Creates a new CSVReader instance from the specified {@code reader}, whose lines may be parsed into instances of type {@code clazz}. By default, the delimiter used is {@code ","}, and it is assumed there is no header line. These options may be configured via their respective builder methods.
*
* @param reader a {@link BufferedReader} containing {@code n} lines of text, with each line containing {@code m} fields separated by a delimiter.
* @param clazz the class of the type of object that each row is parsed into. For example, {@code Foo.class}
* @param <T> the type corresponding to {@code clazz}
* @return a new CSVReader instance, which may be further configured with the builder options
* @see #withDelimiter(String)
* @see #ignoringHeader()
*/
public static <T> CSVReader<T> of(BufferedReader reader, Class<T> clazz) {
return new CSVReader<>(reader, clazz);
}
/**
* Sets a custom delimiter to be used
* @param delimiter the delimiter to use to separate fields of each row
* @return {@code this} CSVReader with the specified delimiter
*/
public CSVReader<T> withDelimiter(String delimiter) {
this.delimiter = delimiter;
return this;
}
/**
* If a header line is present, this method should be invoked so that this CSVReader ignores the first line
* @return {@code this} CSVReader with the header line ignored
*/
public CSVReader<T> ignoringHeader() {
this.ignoreHeader = true;
return this;
}
/**
* Maps each line of the reader to a parsed instance of type {@code T}. The number of fields per line must be no less than the number of fields of class {@code T}.
* @return a Stream of instances of type {@code T} corresponding to each line
*/
public Stream<T> rows() {
return reader.lines().skip(ignoreHeader ? 1 : 0).map(this::parseRow);
}
@SuppressWarnings("unchecked")
private T parseRow(String row) {
final var split = row.split(delimiter);
final var annotatedCtor = Arrays.stream(clazz.getConstructors())
.filter(ctor -> ctor.isAnnotationPresent(CSVConstructor.class))
.findFirst()
.orElseThrow();
final var ctorParams = annotatedCtor.getParameterTypes();
final var args = IntStream.range(0, ctorParams.length)
.mapToObj(i -> PARSERS.get(ctorParams[i]).apply(split[i]))
.toArray();
try {
return (T) annotatedCtor.newInstance(args);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
</code></pre>
<p>It works perfectly as designed, however I was wondering if there are any best practices with regards to reflection and annotations which I am not using and should be using, or if there's edge case problems in my code. I'm also super open to advice on the class design overall! Thanks!</p>
<p>For an example of the class usage, check out the JavaDoc comment above the class declaration.</p>
|
[] |
[
{
"body": "<p>I have some suggestions for your code.</p>\n<h2>Use a conventional name for the static factory method name</h2>\n<p>In my opinion, the <code>of</code> name generally aggregate a given set of data into a container; this can cause confusion in this case. I suggest to rename the method to <code>create</code> or <code>newInstance</code>.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static <T> CSVReader<T> of(BufferedReader reader, Class<T> clazz) {\n return new CSVReader<>(reader, clazz);\n}\n</code></pre>\n<h2>Use the given class to cast the return object</h2>\n<p>Use the <code>java.lang.Class#cast</code> method to cast your object, this will make the annotation useless, since the class knows the type while the static cast doesn’t (<a href=\"https://docs.oracle.com/javase/tutorial/java/generics/erasure.html\" rel=\"nofollow noreferrer\">type erasure</a>).</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>return (T) annotatedCtor.newInstance(args);\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>return clazz.cast(args);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T00:15:32.447",
"Id": "244478",
"ParentId": "244432",
"Score": "2"
}
},
{
"body": "<p>First of all, to get that out of the way, I despise <code>var</code> and static imports. For me, it makes the code an unreadeable mess that looks like javascript. You would not be allowed to do that on my team.</p>\n<p>Now regarding the concrete code:</p>\n<ul>\n<li>It is not a CSV reader. For real csv, you'd need a quote character and a way to escape the quote. Usually this is done via doubling the quote character in a quoted sequence. (This is so silly, that csv is a traditional example of how-not-to-design-a-file-format.)</li>\n<li>Using an annotated constructor is severely limited. The csv-reader should rather expect a class adhering to the java bean standard (i.e. default constructer and getters/setters) to be of practical use. (OK, this invalidates the idea to practice working with annotations, but all of a sudden, you could use it for classes which have not specifically crafted for this csv-reader.) Maybe you could implement alternatives?</li>\n<li>The delimiter char should be settable.</li>\n<li>Instead of <code>s -> s</code>, use <code>Function.identity()</code></li>\n<li>I would recommend to extract the reflection-based analysis to some preparation stage, so that you don't have to repeat it for every single line in your data file. Take a few measurements, I wager that this is the second slowest part in the program right after file I/O.</li>\n<li><code>e.printStackTrace()</code> - come on, there must be a better way to handle errors.</li>\n<li>Making local variables <code>final</code> serves no purpose at all. We can plainly see that you don't set the values a second time, and even if you did, the reader would not care. Sometimes you need this for use in a lambda or inner class, but usually this is just noise.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T04:44:44.243",
"Id": "244485",
"ParentId": "244432",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T08:43:08.563",
"Id": "244432",
"Score": "3",
"Tags": [
"java",
"object-oriented",
"parsing",
"csv",
"reflection"
],
"Title": "Java Reflection-based CSV Parser"
}
|
244432
|
<p>I'm building a dead simple CLI app that parses a RSS feed and prints it to <code>stdout</code>. I needed a simple word wrapping function to, well, wrap lines to an arbitrary length (say 80 or 120 chars).</p>
<p>I ended up using this, as it gets the job done. However, as I'm still new to Go, I was wondering if this can be improved?</p>
<pre><code>func wordWrap(text string, lineWidth int) (wrapped string) {
words := strings.Fields(strings.TrimSpace(text))
if len(words) == 0 {
return text
}
wrapped = words[0]
spaceLeft := lineWidth - len(wrapped)
for _, word := range words[1:] {
if len(word)+1 > spaceLeft {
wrapped += "\n" + word
spaceLeft = lineWidth - len(word)
} else {
wrapped += " " + word
spaceLeft -= 1 + len(word)
}
}
return
}
</code></pre>
<p>Here's a working sample code - <a href="https://play.golang.org/p/i24iSnpTjtP" rel="nofollow noreferrer">https://play.golang.org/p/i24iSnpTjtP</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T15:30:58.937",
"Id": "480009",
"Score": "0",
"body": "Seems fine to me. But remember that if your text has any leading or trailing `'\\t', '\\n', '\\v', '\\f', '\\r', ' ', U+0085 (NEL), U+00A0 (NBSP)`, etc., then they would be trimmed by `strings.TrimSpace`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T23:48:01.000",
"Id": "480059",
"Score": "0",
"body": "@shmsr: `strings.Fields` removes all `unicode.IsSpace` characters."
}
] |
[
{
"body": "<blockquote>\n<p>working sample code - <a href=\"https://play.golang.org/p/i24iSnpTjtP\" rel=\"nofollow noreferrer\">https://play.golang.org/p/i24iSnpTjtP</a></p>\n</blockquote>\n<hr />\n<p>Really!</p>\n<pre><code>sample := "This is a rather long line that needs word wrapping to an arbirtary line lenght so it's easier to read it."\n</code></pre>\n<p>Check your spelling.</p>\n<pre><code>sample := "This is a rather long line that needs word wrapping to an arbitrary line length so it's easier to read it."\n</code></pre>\n<hr />\n<p>UTF-8 is a variable-length encoding. <code>len(word)</code> is the length of <code>word</code> in bytes, not characters (except for ASCII). For example, test using Greek and Russian (Google Translate) samples:</p>\n<pre><code>sample := `Αυτή είναι μια μάλλον μεγάλη γραμμή που χρειάζεται αναδίπλωση λέξεων σε αυθαίρετη γραμμή μήκος, ώστε να είναι πιο εύκολο να το διαβάσετε.`\n\nsample := `Это довольно длинная линия, которая нуждается в перенос слов в произвольную строку длина, так что это легче читать.`\n</code></pre>\n<hr />\n<pre><code>words := strings.Fields(strings.TrimSpace(text)))\n</code></pre>\n<p>Since <code>strings.Fields</code> removes <code>uinicode.IsSpace</code> characters, isn't <code>strings.TrimSpace</code> superfluous?</p>\n<hr />\n<p>Why do you make multiple passes (directly and indirectly) of <code>text</code> when one will do?</p>\n<p>Why do you make so many allocations when one or two will do?</p>\n<pre><code>BenchmarkBaduker-4 455914 2738 ns/op 1632 B/op 21 allocs/op\nBenchmarkPeterSO-4 592740 1760 ns/op 224 B/op 2 allocs/op\n</code></pre>\n<p><code>peterso.go</code> <a href=\"https://play.golang.org/p/F1qyJRKurpq\" rel=\"nofollow noreferrer\">https://play.golang.org/p/F1qyJRKurpq</a> :</p>\n<pre><code>package main\n\nimport (\n "fmt"\n "unicode"\n "unicode/utf8"\n)\n\nfunc wordWrap(text string, lineWidth int) string {\n wrap := make([]byte, 0, len(text)+2*len(text)/lineWidth)\n eoLine := lineWidth\n inWord := false\n for i, j := 0, 0; ; {\n r, size := utf8.DecodeRuneInString(text[i:])\n if size == 0 && r == utf8.RuneError {\n r = ' '\n }\n if unicode.IsSpace(r) {\n if inWord {\n if i >= eoLine {\n wrap = append(wrap, '\\n')\n eoLine = len(wrap) + lineWidth\n } else if len(wrap) > 0 {\n wrap = append(wrap, ' ')\n }\n wrap = append(wrap, text[j:i]...)\n }\n inWord = false\n } else if !inWord {\n inWord = true\n j = i\n }\n if size == 0 && r == ' ' {\n break\n }\n i += size\n }\n return string(wrap)\n}\n\nfunc main() {\n sample := "This is a rather long line that needs word wrapping to an arbitrary line length so it's easier to read it."\n fmt.Printf("%s\\n\\n", wordWrap(sample, 40))\n greek := `Αυτή είναι μια μάλλον μεγάλη γραμμή που χρειάζεται αναδίπλωση λέξεων σε αυθαίρετη γραμμή μήκος, ώστε να είναι πιο εύκολο να το διαβάσετε.`\n fmt.Printf("%s\\n\\n", wordWrap(greek, 40))\n russian := `Это довольно длинная линия, которая нуждается в перенос слов в произвольную строку длина, так что это легче читать.`\n fmt.Printf("%s\\n\\n", wordWrap(russian, 40))\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T07:44:49.990",
"Id": "480090",
"Score": "0",
"body": "your reviews are truly eye-opening. I appreciate your time and effort!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-23T16:55:14.477",
"Id": "483123",
"Score": "0",
"body": "This code may be more efficient, but I found the original code much easier to understand."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T23:31:24.270",
"Id": "244537",
"ParentId": "244435",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "244537",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T09:38:32.910",
"Id": "244435",
"Score": "4",
"Tags": [
"go"
],
"Title": "Word Wrap in Go"
}
|
244435
|
<p>It's the first time a write a non-trivial mongodb query, and I came up with one that does work, but is 123 lines long! Surely there must be a way to write it in a more concise way.</p>
<p>The purpose of the query is to return aggregated (average) values, using groups that are determined by the <code>$interval</code> parameter in seconds. Start and stop time are aligned to a multiple of the interval, so that the boundary values do not depend on the exact timestamp of the limit.</p>
<pre class="lang-py prettyprint-override"><code>data_points_aggr = {
'datasource': {
'source': 'data_points',
'query_objectid_as_string': True,
'aggregation': {
'pipeline': [
{
"$match": {
"$expr": {
"$and": [{
"$gte": [
{
"$toLong": "$time_stamp"
},
{
"$subtract": [
{
"$toLong": "$start",
},
{
"$mod": [
{
"$subtract": [
{
"$toLong":
"$start",
},
1,
],
},
{
"$multiply":
[1000, "$interval"]
},
],
},
],
},
]
}, {
"$lte": [
{
"$toLong": "$time_stamp"
},
{
"$subtract": [
{
"$toLong": "$end",
},
{
"$mod": [
{
"$add": [
{
"$toLong":
"$end",
},
0,
],
},
{
"$multiply":
[1000, "$interval"]
},
],
},
],
},
]
}],
},
"prosumer_id": {
"$in": "$prosumer"
}
},
},
{
"$group": {
"_id": {
"prosumer_id": "$prosumer_id",
"date": {
"$toDate": {
"$add": [{
"$subtract": [
{
"$toLong": "$time_stamp"
},
{
"$mod": [
{
"$subtract": [{
"$toLong":
"$time_stamp"
}, 1]
},
{
"$multiply":
[1000, "$interval"]
},
],
},
],
}, {
"$subtract": [{
"$multiply": [1000, "$interval"]
}, 1]
}],
},
},
},
"consumption": {
"$avg": "$grid_consumption_w"
},
},
},
{
"$sort": {
"_id.date": 1
}
},
]
}
},
}
</code></pre>
<p>Here is a sample of the data in the table:</p>
<pre><code>{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a2c"), "time_stamp" : ISODate("2015-07-08T22:15:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 0, "grid_consumption_w" : 0, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a2d"), "time_stamp" : ISODate("2015-07-08T22:30:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 0, "grid_consumption_w" : 0, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a2e"), "time_stamp" : ISODate("2015-07-08T22:45:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 0, "grid_consumption_w" : 0, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a2f"), "time_stamp" : ISODate("2015-07-08T23:00:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 0, "grid_consumption_w" : 0, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a30"), "time_stamp" : ISODate("2015-07-08T23:15:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 1, "grid_consumption_w" : 2, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a31"), "time_stamp" : ISODate("2015-07-08T23:30:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 1, "grid_consumption_w" : 0, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a32"), "time_stamp" : ISODate("2015-07-08T23:45:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 0, "grid_consumption_w" : 0, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a33"), "time_stamp" : ISODate("2015-07-09T00:00:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 0, "grid_consumption_w" : 0, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a34"), "time_stamp" : ISODate("2015-07-09T00:15:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 0, "grid_consumption_w" : 0, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a35"), "time_stamp" : ISODate("2015-07-09T00:30:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 0, "grid_consumption_w" : 0, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a36"), "time_stamp" : ISODate("2015-07-09T00:45:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 0, "grid_consumption_w" : 0, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a37"), "time_stamp" : ISODate("2015-07-09T01:00:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 0, "grid_consumption_w" : 0, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a38"), "time_stamp" : ISODate("2015-07-09T01:15:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 2, "grid_consumption_w" : 2, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a39"), "time_stamp" : ISODate("2015-07-09T01:30:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 0, "grid_consumption_w" : 0, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a3a"), "time_stamp" : ISODate("2015-07-09T01:45:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 1, "grid_consumption_w" : 0, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a3b"), "time_stamp" : ISODate("2015-07-09T02:00:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 0, "grid_consumption_w" : 0, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a3c"), "time_stamp" : ISODate("2015-07-09T02:15:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 0, "grid_consumption_w" : 0, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a3d"), "time_stamp" : ISODate("2015-07-09T02:30:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 0, "grid_consumption_w" : 0, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a3e"), "time_stamp" : ISODate("2015-07-09T02:45:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 0, "grid_consumption_w" : 0, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
{ "_id" : ObjectId("5ee8e0f3aa9b673194b18a3f"), "time_stamp" : ISODate("2015-07-09T03:00:00Z"), "acpower_w" : 0, "grid_feed_in_w" : 2, "grid_consumption_w" : 2, "acpower2_w" : 0, "prosumer_id" : ObjectId("5ee8e0b100871cbb09d9fda0") }
</code></pre>
<p>Here is a request:</p>
<pre class="lang-bsh prettyprint-override"><code>curl --location --request GET 'https://db.flexgrid-project.eu/data_points_aggr?aggregate={%22$start%22:%20%222017-07-11T19:05:00%22,%22$end%22:%222017-07-11T22:00:01%22,%20%22$prosumer%22:%20[%225ee8e1fc00871cbb09d9fdf8%22,%20%225ee8e0fa00871cbb09d9fdc0%22],%20%22$interval%22:%203600}' \
--header 'Authorization: Bearer lep0E....'
</code></pre>
<p>And here is the output:</p>
<pre><code>{
"_items": [
{
"_id": {
"prosumer_id": "5ee8e1fc00871cbb09d9fdf8",
"date": "2017-07-11T20:00:00"
},
"consumption": 3.25
},
{
"_id": {
"prosumer_id": "5ee8e0fa00871cbb09d9fdc0",
"date": "2017-07-11T20:00:00"
},
"consumption": 7.25
},
{
"_id": {
"prosumer_id": "5ee8e0fa00871cbb09d9fdc0",
"date": "2017-07-11T21:00:00"
},
"consumption": 7.75
},
{
"_id": {
"prosumer_id": "5ee8e1fc00871cbb09d9fdf8",
"date": "2017-07-11T21:00:00"
},
"consumption": 2.75
},
{
"_id": {
"prosumer_id": "5ee8e0fa00871cbb09d9fdc0",
"date": "2017-07-11T22:00:00"
},
"consumption": 7.75
},
{
"_id": {
"prosumer_id": "5ee8e1fc00871cbb09d9fdf8",
"date": "2017-07-11T22:00:00"
},
"consumption": 2.25
}
],
"_meta": {
"page": 1,
"max_results": 25,
"total": 6
},
"_links": {
"parent": {
"title": "home",
"href": "/"
},
"self": {
"title": "data_points_aggr",
"href": "data_points_aggr?aggregate={\"$start\": \"2017-07-11T19:05:00\",\"$end\":\"2017-07-11T22:00:01\", \"$prosumer\": [\"5ee8e1fc00871cbb09d9fdf8\", \"5ee8e0fa00871cbb09d9fdc0\"], \"$interval\": 3600}"
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T00:48:35.760",
"Id": "479937",
"Score": "1",
"body": "Perhaps this use case fits https://docs.mongodb.com/manual/core/server-side-javascript/ and https://docs.mongodb.com/manual/tutorial/store-javascript-function-on-server/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T10:45:25.007",
"Id": "479972",
"Score": "0",
"body": "@DimaTisnek: Thanks, this looks like a good approach for reducing the line count, since JS code will be much shorter. My only concern is the big warning on the top of the page that says `Do not store application logic in the database. There are performance limitations to running JavaScript inside of MongoDB. Application code also is typically most effective when it shares version control with the application itself.`, so there seems to be a tradeoff between code clarity and efficiency."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T10:21:29.643",
"Id": "244437",
"Score": "2",
"Tags": [
"python",
"mongodb",
"flask",
"mongodb-query"
],
"Title": "Return aggregated values"
}
|
244437
|
<p>I am currently learning Java; I could really use some help from more experienced programmers.</p>
<p>How can I clean up my Tic-Tac-Toe code? What mistakes have I made? Can I use more exception handling? I tried to use exception handling, in <code>isValidStepCheck</code> and <code>takenFieldCheck</code>, but I don't think I used it efficiently.</p>
<pre><code>public class TicTacToe {
public static String[] bpos = {" 1 ", " 2 ", " 3 ", " 4 ", " 5 ", " 6 ", " 7 ", " 8 ", " 9 "};
public static int turn = 0;
public static int num;
public static String numS;
public static String winner = "n";
public static int r = 0;
public static void main(String[] args) {
System.out.println("Welcome to the Tic-Tac-Toe game.");
Board();
System.out.println("X has the first step, enter a number.");
try{TicTacToeGame();}
catch (Exception e){
System.out.println("Something went wrong. Are you sure you entered a number?");
}
}
static boolean isValidStepCheck() {
while (true) {
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
numToString();
if (num < 1 || num > 9) {
System.out.println("You have to enter a number between 1 and 9!");
} else {
return true;
}
}
}
static void isValidMove() {
while (true) {
if (isValidStepCheck() && !takenFieldCheck()) {
if (turn % 2 == 0) {
turn++;
bpos[num - 1] = " x ";
Board();
break;
} else if (turn % 2 == 1) {
turn++;
bpos[num - 1] = " o ";
Board();
break;
}
} else if (takenFieldCheck()) {
System.out.println("This field is already taken!");
}
}
}
static void Board() {
System.out.println(" ___________ ");
System.out.println("|" + bpos[0] + "|" + bpos[1] + "|" + bpos[2] + "|");
System.out.println("|-----------|");
System.out.println("|" + bpos[3] + "|" + bpos[4] + "|" + bpos[5] + "|");
System.out.println("|-----------|");
System.out.println("|" + bpos[6] + "|" + bpos[7] + "|" + bpos[8] + "|");
System.out.println(" ----------- ");
}
static boolean takenFieldCheck() {
if (bpos[num - 1].equals(numS)) {
return false;
} else {
return true;
}
}
static void numToString() {
switch (num) {
case 1:
numS = " 1 ";
break;
case 2:
numS = " 2 ";
break;
case 3:
numS = " 3 ";
break;
case 4:
numS = " 4 ";
break;
case 5:
numS = " 5 ";
break;
case 6:
numS = " 6 ";
break;
case 7:
numS = " 7 ";
break;
case 8:
numS = " 8 ";
break;
case 9:
numS = " 9 ";
break;
}
}
static void isWon() {
String line = null;
if (winner.equals("n")) {
for (int i = 0; i < 8; i++) {
switch (i) {
case 0:
line = bpos[0] + bpos[1] + bpos[2];
break;
case 1:
line = bpos[3] + bpos[4] + bpos[5];
break;
case 2:
line = bpos[6] + bpos[7] + bpos[8];
break;
case 3:
line = bpos[0] + bpos[3] + bpos[6];
break;
case 4:
line = bpos[1] + bpos[4] + bpos[7];
break;
case 5:
line = bpos[2] + bpos[5] + bpos[8];
break;
case 6:
line = bpos[0] + bpos[4] + bpos[8];
break;
case 7:
line = bpos[2] + bpos[4] + bpos[6];
break;
}
if (line.equals(" x x x ")) {
winner = "x";
} else if (line.equals(" o o o ")) {
winner = "o";
}
}
} else {
winner = "n";
}
}
static void TicTacToeGame() {
while (true) {
isValidMove();
isWon();
r++;
if (winner.equals("x")) {
System.out.println("Congrats to X, you won!");
break;
} else if (winner.equals("o")) {
System.out.println("Congrats to O, you won!");
break;
}
else {
if(r==9){
System.out.println("Its a draw!");
break;
}
}
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Just a few quick things that jump out at me (I didn't go over all of it):</p>\n<p>Using <code>static</code> for everything is awkward. Usually you want to avoid storing state in statics. I know this is a simple app without multiple classes so you can get away with it here. But following more typical rules of thumb, you would make all these variables and methods non-static.</p>\n<p>If you see yourself using if/else to simply return true or false, you can almost always remove the if/else.</p>\n<pre><code>static boolean takenFieldCheck() {\n return !bpos[num - 1].equals(numS);\n}\n</code></pre>\n<p>This method could be made much shorter like this:</p>\n<pre><code>static void numToString() {\n numS = " " + num + " ";\n}\n</code></pre>\n<p>However, you only use <code>numS</code> in one spot. It's error prone to keep a copy of your game state in two different forms, because then you have to be absolutely sure you always keep them in sync. I would remove <code>numS</code> and change the method to this:</p>\n<pre><code>static String numAsString() {\n return " " + num + " ";\n}\n</code></pre>\n<p>And use it in the one place you were comparing something to <code>numS</code>.</p>\n<p>It would be better practice to catch your Exceptions from Scanner right from where they are thrown because then you can show the proper error message right there and let the user recover. Your top-level catch-all block doesn't really know what kind of exception was thrown, so it could be showing the wrong message. Not really in the case of this very simple game, though.</p>\n<p>You're checking for a number out of range and let the user recover from that. Why not let them recover from anything, like this? Also, there's no reason for this method to return a Boolean, since it cannot possibly return false. I would rename it to describe what it actually does.</p>\n<pre><code>static void receiveValidMove() { // was isValidStepCheck\n Scanner sc = new Scanner(System.in);\n while (true) {\n int newNumber;\n try {\n newNumber = sc.nextInt();\n } catch (Exception e) {\n newNumber = -1; // input was invalid\n }\n if (number >= 1 && number <= 9){\n num = newNumber;\n numToString(); // omit if following above advice\n return;\n }\n System.out.println("You have to enter a number between 1 and 9!");\n }\n \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T13:25:42.920",
"Id": "244444",
"ParentId": "244440",
"Score": "2"
}
},
{
"body": "<h1>Naming is important</h1>\n<p>When you're in the flow and writing code you'll typically remember what variables refer to and you'll often be able to hold the whole code context in your head, particularly with relatively small examples like this. However, as the code gets bigger / after you've stepped away from it for a while having good names really makes the code more approachable. <code>bpos</code> isn't really a meaningful name. It looks like some kind of abbreviation / acronym, possibly <code>boardPosition</code>? From the way you are using it, it looks like it's actually the state of the game. Perhaps <code>gameBoard</code> might be more descriptive. <code>r</code> is even less descriptive. One letter variables, if you want to use them, should really be confined to local variables, in code that fits on a typical screen. This reduced the impact of lost context. It's also a lot easier to search your codebase for something like <code>roundNumber</code> than <code>r</code>.</p>\n<h1>No, really, naming is important...</h1>\n<p>When developers approach your code, they bring expectations from other code that they've previously seen. You can obviously introduce your own approaches, but consider if they're actually adding anything. When I see methods that start with 'is' or 'has', I'm expecting them to return booleans. When you read code that's been written like this, it helps readability because it often comes out closer to natural language. So you might have something like:</p>\n<pre><code>if(isValidMove(position)) {\n makeMove(position);\n} else {...}\n</code></pre>\n<p>Your <code>isValidMove</code> and <code>isWon</code> methods break this expectation. As has been pointed out by @Tenfour04 your other method <code>isValidStepCheck</code> kind of satisfies this, however it always returns <code>true</code>.</p>\n<p>Generally methods in Java should follow camelCase and describe what they do, so instead of <code>Board</code>, consider <code>printBoard</code>.</p>\n<h1>Keep an eye out for redundancy</h1>\n<p>You <code>isWon</code> method contains:</p>\n<pre><code>if (winner.equals("n")) {\n // ...\n} else {\n winner = "n";\n}\n</code></pre>\n<p>If the <code>if</code> fails, then it's because <code>winner</code> is already "n", so there's no need to assign it in the <code>else</code>. In the same area, consider if you need to check if all three positions are 'x', or all three positions are 'y'. Would it simply be enough to consider if all three positions are the same?</p>\n<p>There's a similar issue in <code>isValidMove</code>:</p>\n<pre><code>if (turn % 2 == 0) {\n turn++;\n bpos[num - 1] = " x ";\n Board();\n break;\n} else if (turn % 2 == 1) {\n turn++;\n bpos[num - 1] = " o ";\n Board();\n break;\n}\n</code></pre>\n<p>There's a couple of issue... the only difference between the two <code>if</code> clauses is that one is assigning " o " and the other " x ". If who was moving was worked out first, then you could simplify the code. You also don't need the second <code>if</code> condition. If <code>turn % 2</code> isn't '0', then it has to be '1', you don't need to check for it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T22:35:15.950",
"Id": "244471",
"ParentId": "244440",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T11:11:21.460",
"Id": "244440",
"Score": "3",
"Tags": [
"java",
"beginner",
"game",
"error-handling",
"tic-tac-toe"
],
"Title": "Tic-Tac-Toe in Java"
}
|
244440
|
<p>I have a simple class to ensure the date entered into a form is a valid date. Where can I improve it, have I missed anything?</p>
<pre><code>public class ValidDate : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var dateToParse = value.ToString();
var parsedDate = new DateTime();
if (DateTime.TryParseExact(dateToParse, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out parsedDate))
return ValidationResult.Success;
return new ValidationResult("Invalid date, please try again with a valid date in the format of DD/MM/YYYY.");
}
}
</code></pre>
<p>Thanks,</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T13:41:19.487",
"Id": "479854",
"Score": "2",
"body": "I would consider to include the malformed input data into the error message. It can help a lot during investigation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T07:33:15.983",
"Id": "479965",
"Score": "1",
"body": "@PeterCsala that's a good shout, thanks, I'll add that in."
}
] |
[
{
"body": "<p>You could easily turn your method into a one-liner <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members#methods\" rel=\"nofollow noreferrer\">expression-bodied method</a> with a few tricks:</p>\n<ul>\n<li>use the <code>_</code> <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/discards\" rel=\"nofollow noreferrer\">discard</a> variable instead of the explicit <code>parsedDate</code> variable (also, it doesn't need initializing to <code>new DateTime()</code>).</li>\n<li>use the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator\" rel=\"nofollow noreferrer\">conditional operator</a> since you're returning one of two <code>ValidationResult</code>s.</li>\n<li><code>value.ToString()</code> can be passed directly into <code>TryParseExact</code> without the extra local variable <code>dateToParse</code>.</li>\n</ul>\n<p>Giving:</p>\n<pre><code>protected override ValidationResult IsValid(object value, ValidationContext validationContext) =>\n DateTime.TryParseExact(value.ToString(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out _)\n ? ValidationResult.Success\n : new ValidationResult("Invalid date, please try again with a valid date in the format of DD/MM/YYYY.");\n</code></pre>\n<p>Couple more items:</p>\n<ul>\n<li>Recommend -- for ease of reading -- adding a <code>using System.Globalization;</code> to your namespace so you don't have to type that long prefix out twice.</li>\n<li>As this is an attribute, add the suffix <code>Attribute</code> to your class name.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T12:46:01.373",
"Id": "479849",
"Score": "1",
"body": "Great stuff, thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T12:43:54.917",
"Id": "244442",
"ParentId": "244441",
"Score": "4"
}
},
{
"body": "<p>I think other answer had some great points, also I would use fluent validation instead so your model does not need to have dependencies on validation attributes.</p>\n<p><a href=\"https://docs.fluentvalidation.net/\" rel=\"nofollow noreferrer\">https://docs.fluentvalidation.net/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T07:36:16.587",
"Id": "479967",
"Score": "0",
"body": "I'll check that out, thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T15:06:47.287",
"Id": "244448",
"ParentId": "244441",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244442",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T12:07:48.800",
"Id": "244441",
"Score": "3",
"Tags": [
"c#",
"asp.net",
"asp.net-core"
],
"Title": "Validating a date with C# and ASP.NET Core 3.1"
}
|
244441
|
<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>// variables
// arr has elements to be sorted
var arr = []
// temp is to store the intermediate results after merging
var temp = []
// seen is for marking visited i.e. sorted half as green
var seen = []
// length of array
var len = 50
// canvas initialisations
var canvas = document.getElementById("myCanvas")
canvas.width = canvas.height = 1000
var canvaswidth = canvas.width
var canvasheight = canvas.height
var ctx = canvas.getContext("2d")
// random array
for (let i = 0; i < len; i++) {
arr.push(parseInt(Math.random() * 500))
temp.push(parseInt(0))
seen.push(parseInt(0))
}
// initial contents of array to be sorted
// console.log(arr)
// draw the bars
draw = (s, e) => {
ctx.clearRect(0, 0, 1000, 1000)
// this loop will make unvisited bars in the upper half as black
// and visited bars in the upper half as green
for (let i = 0; i < len; i++) {
ctx.fillStyle = "#000000"
ctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])
if (seen[i]) {
ctx.fillStyle = "#00ff00"
ctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])
}
}
// the part that was merged is made blue in the lower half
// also its equivalent in the uper half is made white
for (let i = s; i <= e; i++) {
ctx.fillStyle = "#ffffff"
ctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])
ctx.fillStyle = "#0000ff"
ctx.fillRect(15 * i, 500, 10, arr[i])
seen[i] = 1
}
}
// merge
merge = (s, e) => {
let m = parseInt((s + e) / 2)
let p1 = s
let p2 = m + 1
let n1 = m
let n2 = e
let idx = s
while (p1 <= n1 && p2 <= n2) {
if (arr[p1] <= arr[p2]) {
temp[idx++] = arr[p1++]
}
else {
temp[idx++] = arr[p2++]
}
}
while (p1 <= n1) {
temp[idx++] = arr[p1++]
}
while (p2 <= n2) {
temp[idx++] = arr[p2++]
}
idx = s
while (idx <= e) {
arr[idx] = temp[idx++]
}
}
// delay
function mytimeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// mergesort
const mergesort = async (s, e) => {
if (s < e) {
let m = parseInt((s + e) / 2)
await mergesort(s, m)
await mergesort(m + 1, e)
await merge(s, e)
// await console.log(`merged ${s} to ${e} now draw...`)
await draw(s, e)
await mytimeout(500)
}
}
// calls merge sort and at last
// makes all bars become green in upper half
const performer = async () => {
await mergesort(0, len - 1)
// await console.log(arr)
await draw()
}
performer()</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas">
Your browser does not support the canvas element.
</canvas>
<script src="testmerge.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>Now if i change the len variable in JS to above 50 i.e. 75 or 100 the code behaves oddly..why is it so?
Are there any optimisations possible??</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T13:45:38.467",
"Id": "479857",
"Score": "0",
"body": "Greetings, the downvote and vote to close comes from 1. not all code being right in the question 2. the admission that the code doesn't work at a certain point. Other than that, welcome to CodeReview ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T14:22:14.863",
"Id": "479869",
"Score": "0",
"body": "@konijn perhaps you could help me now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T14:23:56.770",
"Id": "479872",
"Score": "0",
"body": "You have helped yourself by putting the code in this question which fixes the first part, however fixing code that not works is really something for StackOverflow, by all means come back after/if they fix your code for a codereview of your working code. Upvoted your question as a show of appreciation for your efforts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T16:02:25.107",
"Id": "479884",
"Score": "2",
"body": "Note the OP posted first on https://stackoverflow.com/questions/62555192/merge-sort-visualisation, but apparently did not quite understand the comments that were given there...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T16:04:28.940",
"Id": "479885",
"Score": "2",
"body": "@keemahs, the question about the malfunctioning does not belong here, but on Stack Overflow. A question about optimisation could be on topic here, but only once you are certain the code works as intended."
}
] |
[
{
"body": "<p>There is nothing wrong with your code when changing the data size to a larger number, except that the <code>draw()</code> method doesn't adjust the width of the columns by the ratio between the canvas size and the number of columns to be drawn.</p>\n<p>You'll have to do some math like:</p>\n<pre><code> let offset = Math.round(canvaswidth / len);\n let rectWidth = Math.round(offset * 0.9);\n</code></pre>\n<p>The rounding is because you want integer values (pixels).</p>\n<hr />\n<blockquote>\n<pre><code>ctx.fillStyle = "#000000"\nctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])\nif (seen[i]) {\n ctx.fillStyle = "#00ff00"\n ctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])\n}\n</code></pre>\n</blockquote>\n<p>This seems inefficient as you draw more and more columns twice through the sorting. A better solution would be something like:</p>\n<pre><code>ctx.fillStyle = seen[i] ? "#00ff00" : "#000000";\nctx.fillRect(offset * i, 500 - arr[i], rectWidth, arr[i]);\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>for (let i = s; i <= e; i++) {\n ctx.fillStyle = "#ffffff"\n ctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])\n ctx.fillStyle = "#0000ff"\n ctx.fillRect(15 * i, 500, 10, arr[i])\n seen[i] = 1\n}\n</code></pre>\n</blockquote>\n<p>You shouldn't "undraw" a column by drawing a white column over it. Instead you could use <code>clearRect</code> with the same dimensions.</p>\n<hr />\n<blockquote>\n<p><code>let m = parseInt((s + e) / 2)</code></p>\n</blockquote>\n<p>You can integer divide by two by right shifting by one:</p>\n<pre><code>(s + e) >> 1\n</code></pre>\n<hr />\n<p>You should really be careful to end each statement with a ';' (<a href=\"https://en.wikipedia.org/wiki/JavaScript_syntax#Whitespace_and_semicolons\" rel=\"nofollow noreferrer\">see here</a>)</p>\n<hr />\n<blockquote>\n<pre><code>await merge(s, e)\n// await console.log(`merged ${s} to ${e} now draw...`)\nawait draw(s, e)\n</code></pre>\n</blockquote>\n<p>You call these with <code>await</code> but they are not defined as <code>async</code>?</p>\n<hr />\n<p>Your algorithm seems to works like a merge sort - as I recall it. I think I would encapsulate the parts into a class instead of having the functions in the global scope.</p>\n<hr />\n<p>Besides that, I find you graphics very illustrative.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T22:10:59.753",
"Id": "479919",
"Score": "0",
"body": "Note the text in the description: \"_Now if i change the len variable in JS to above 50 i.e. 75 or 100 the code behaves oddly..why is it so?_\" Questions involving code that's not working as intended, are off-topic. If OP edits their post to address the problem and make their post on-topic, they make your answer moot. [It is advised not to answer such questions](https://codereview.meta.stackexchange.com/a/6389/120114). Protip: There are tons of on-topic questions to answer; you'll make more reputation faster if you review code in questions that will get higher view counts for being on-topic."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T19:29:02.527",
"Id": "244462",
"ParentId": "244443",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T13:25:16.237",
"Id": "244443",
"Score": "1",
"Tags": [
"javascript",
"html",
"mergesort"
],
"Title": "Merge Sort Visualisation JS"
}
|
244443
|
<p>I'm a solo developer and a friend told me that my code is not very readable. I always write code trying to keep it DRY while not taking longer than it would take doing it in an "easier" way.</p>
<p>Here is the skeleton for <code>My Profile</code> feature which will initially have read-only values. When the user wants to update it, it turns into an input when clicking on edit.</p>
<p>Is there anything wrong with this way of going about it?</p>
<pre><code>class MyProfileEdit extends React.Component {
constructor(props){
super(props);
this.state = {
data: {},
onEdit: ""
}
this.displayKey = {
"first_name": "First name",
"last_name": "Last name",
"zipCode": "Zip"
}
}
handleOnChange = key => e => e.persist() || this.setState(prevState => {
prevState.data[key] = e.target.value;
return prevState;
})
getInputValue = key => this.state.data[key] || this.props.currentUser[key]
getKeyDisplay = key => this.displayKey[key] || key[0].toUpperCase() + key.slice(1)
getStatic = key => (
<label style={{display: "flex"}}>
{this.getKeyDisplay(key)}: {this.getInputValue(key)} &nbsp;&nbsp;&nbsp;
<div onClick={() => this.setState({onEdit: key})}>Edit</div>
</label>
)
getInput = key => (
<label style={{ display: "flex" }}>
{this.getKeyDisplay(key)}:
<input value={this.getInputValue(key)} onChange={this.handleOnChange(key)} />
<div onClick={() => this.setState({ onEdit: "" })}>Done</div>
</label>
)
getStaticOrInput = key => this.state.onEdit != key ? this.getStatic(key) : this.getInput(key);
render(){
return (
<React.Fragment>
My profile:<br /><br />
{ this.getStaticOrInput("first_name") }
{ this.getStaticOrInput("last_name") }
<label>
Notification option:
<select
value={this.getInputValue("notification_option")}
onChange={this.handleOnChange("notification_option")}
>
<option value="SMS">SMS</option>
<option value="EMAIL">Email</option>
</select>
</label>
{ this.getStaticOrInput("city") }
{ this.getStaticOrInput("address") }
{ this.getStaticOrInput("zipCode") }
</React.Fragment>
)
}
}
</code></pre>
|
[] |
[
{
"body": "<p>In regards to readability, I agree that there is room for improvement. It seems like you're trying to cram as much code in as you can in fewer lines.</p>\n<p>Use the conventional style for Javascript class methods where you have `</p>\n<pre><code>name_of_method(arg1, arg2) {\n return ... \n}\n</code></pre>\n<p>instead of setting them like you are now, like you would a local variable. Additionally, include a line of whitespace between each method definition.</p>\n<p>Yes, you will have to write more this way because you're putting a <code>return</code> statement and curly braces for each method now, but this will make your code much cleaner.</p>\n<hr>\n<p>I like this idea you have going here, but I think you should take better advantage of the design that React tries to push. You've got several elements that are very similar: they display some sort of data, and when they are clicked, they become editable. There are about 5 instances of that here. Why not make a React component that does just that?</p>\n<p>Create a new react component that has all that functionality built in, but just for a single element. Then, in this <code>My Profile</code> element, you could set it up something like this:</p>\n<pre><code><Editable name="first_name"/>\n<Editable name="last_name"/>\n...\n</code></pre>\n<p>(note: you don't have to use the name attribute; I'm just using it for the sake of example)</p>\n<p>This approach would be much more idiomatic for React and would take better advantage of what the library has to offer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T16:44:04.283",
"Id": "244454",
"ParentId": "244449",
"Score": "0"
}
},
{
"body": "<p>Other than your <code>handleOnChange</code> handler is mutating state, this code seems understandable and readable enough to me, only minor comments about code style.</p>\n<h1>React-ness</h1>\n<p>React's synthetic events' <code>persist</code> function is a void return, so I don't think the logical OR between it and the state update necessary.</p>\n<p>Mutating-state handler with odd event persisting.</p>\n<pre><code>handleOnChange = key => e => e.persist() || this.setState(prevState => {\n prevState.data[key] = e.target.value; // <-- this mutates existing state\n return prevState; // <-- saving previous state object back in state\n})\n</code></pre>\n<p>Non-mutating-state handler. React class-based component state updates are merged in, but nested state needs to have their previous state merged manually. Also, instead of persisting the event for use in the "asynchronous" setState, it is more common to grab the event value and let react do what it needs with the event object (i.e. return back to pool).</p>\n<pre><code>handleOnChange = key => e => {\n const { value } = e.target;\n this.setState(prevState => ({\n data: {\n ...prevState.data,\n [key]: value,\n },\n }));\n}\n</code></pre>\n<h1>Readability</h1>\n<p>All other comments I'd have on the code are more about the readability, i.e. appropriate usage of whitespace, 2-space vs 4-space tabs, etc.. but these are largely dev team driven and tend to be subject to opinion.</p>\n<p>Common practices though are</p>\n<ul>\n<li>Single line space between code blocks (functions and any other logical "chunk" of code</li>\n<li>Using curly brackets for functions that are more than simply an implicit return, i.e. they have more than a single expression</li>\n<li>Using appropriate line breaks when lines of code get too long, usually around 80 chars</li>\n</ul>\n<h1>Maintainability/Reusability</h1>\n<p>The one remaining comment I'd have would be to try and abstract the <code>this.getStaticOrInput</code> logic and utilities into a separate react component, something like <code>EditableInput</code> that handles its toggling state internally.</p>\n<pre><code><EditableInput name="first_name" value={...} etc.. />\n<EditableInput name="last_name" value={...} etc.. />\n...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T16:45:47.360",
"Id": "244455",
"ParentId": "244449",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244455",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T15:42:02.010",
"Id": "244449",
"Score": "2",
"Tags": [
"react.js",
"jsx"
],
"Title": "Profile with static and input modes (View and Update)"
}
|
244449
|
<p>The code below works as intended but I'm not sure the way I'm passing it to a component is correct. Also, I don't think the way I wrote this function is recommended. It's not a pure function and probably should be split into two functions where one needs the output of the other.</p>
<p>'books' and 'authors' are 'state' objects in this functional component. The author list is dynamic based on the users choices (author list checkboxes). As I said, it works fine but it's probably not written the way it should:</p>
<pre><code>const selectedBooks = (books, authors) => {
// get the list of the currently selected authors and save it in a list.
const authorList = authors.filter(author => author.active).map(item => item.name);
// filter the list of books for the currently selected authors
const bookList = books.filter(book => authorList.includes(book.source.name));
return bookList;
}
</code></pre>
<p>And then it's passed:</p>
<pre><code><BookList books={selectedBooks(books, authors)} />
</code></pre>
<p>EDIT based on the comment:
That's what I thought. So would I do the following:</p>
<pre><code>const selectedBooks = (books, authors) => {
// get the list of the currently selected authors and save it in a list.
const authorList = authors.filter(author => author.active).map(item => item.name);
// filter the list of books for the currently selected authors
const bookList = books.filter(book => authorList.includes(book.source.name));
return bookList;
}
const booksToPass = selectedBooks(books, authors);
...
<BookList books={booksToPass} />
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T06:06:11.677",
"Id": "479956",
"Score": "1",
"body": "In isolation it appears to be a perfectly valid utility function, and I don't disagree with its usage to compute *a* prop value. I may only suggest it doesn't compute it in-line in the props. If it's just the one component and usage perhaps it's unnecessary, but maybe you have more uses for it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T07:30:46.700",
"Id": "479964",
"Score": "0",
"body": "Thanks. I've added the modification. Have I understood you correctly? Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T07:33:50.710",
"Id": "479966",
"Score": "0",
"body": "Yup, precisely. I believe for readability the JSX should be as tight and concise as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T05:47:57.753",
"Id": "480082",
"Score": "0",
"body": "I'd rather remove the `map()` and use `some()` instead of `includes()`. Saves a function call with another temporary array so might be more performant"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T07:27:49.337",
"Id": "480193",
"Score": "0",
"body": "@SonNguyen Ok, took me a minute to wrap my head around that comment, but basically `bookList = books.filter(book => authorList.some(({ name }) => name === book.source.name);`, is this correct? These are all linear \\$O(n)\\$ operations, i.e. traversing the array to map, filter, or match a criteria; removing a single map just cuts out a constant time factor. I like the suggestion, but don't think it would be more, or less, performant, and likely is more a readability issue, what a dev is more familiar with, though both require about the same level-of-knowledge of array functions to understand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T08:47:27.597",
"Id": "480194",
"Score": "0",
"body": "@SonNguyen Also, could you clarify your map() comment? Would you replace it with forEach? I chose map() because, unlike forEach, it returns a new object, which is needed here. Am I correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T08:52:40.117",
"Id": "480195",
"Score": "0",
"body": "Wasteland, I believe they meant just dropping the mapping in computing the author list, i.e. `const authorList = authors.filter(author => author.active);` then changing the second book list computation to something similar to my previous comment. `authorList` is an array of author objects, thus the object destructuring of `name` property in the array::some callback."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T17:31:40.747",
"Id": "244458",
"Score": "1",
"Tags": [
"javascript",
"react.js"
],
"Title": "React - passing the return of a function as prop"
}
|
244458
|
<p>I am a beginner in programming with Python. I am going to start my first job in this specialization. Can I use this code for presenting my skills at an interview?</p>
<pre><code>import os
import time
import datetime
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
class MainForm(QtWidgets.QMainWindow):
# atribute to save variable from time-edit widget, which is passed to the second window.
saved_time = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
# settings of size and title
self.setWindowTitle("TurnOff Aplikace")
self.setGeometry(500, 300, 404, 280)
self.setFixedSize(404, 280)
# create stacked widget
self.Qtstack = QtWidgets.QStackedWidget()
self.setCentralWidget(self.Qtstack)
# create two widget to stacked-widget
self.stack1 = QtWidgets.QWidget()
self.stack2 = QtWidgets.QWidget()
# add widget to stacked widget
self.Qtstack.addWidget(self.stack1)
self.Qtstack.addWidget(self.stack2)
# setting of layout to first stack
self.layout_stack1 = QtWidgets.QVBoxLayout()
self.stack1.setLayout(self.layout_stack1)
# setting of layout to second stack
self.layout_stack2 = QtWidgets.QVBoxLayout()
self.stack2.setLayout(self.layout_stack2)
# launch both windows
self.show()
self.front_window()
self.back_window()
def front_window(self):
# layout with text
self.text = QtWidgets.QWidget()
self.layout_text = QtWidgets.QHBoxLayout()
self.text.setLayout(self.layout_text)
self.layout_stack1.addWidget(self.text)
self.layout_stack1.addStretch()
# Layout to edit a checkboxs
layout_edit = QtWidgets.QHBoxLayout()
self.layout_stack1.addLayout(layout_edit)
self.layout_stack1.addStretch()
# Layout to error issue
layout_error = QtWidgets.QHBoxLayout()
self.layout_stack1.addLayout(layout_error)
# Layout to pushbutton
layout_button = QtWidgets.QHBoxLayout()
self.layout_stack1.addLayout(layout_button)
# widget with text
self.text = QtWidgets.QLabel("Here you set how long it takes you to turn off the PC\nautomatically. You can also specify which monitor you want\nto switch to immediately. The minimum time is 15 minutes. \n\nNote: \nBefore turning off, the PC will automatically switch to the\nfirst monitor.")
self.text.setFont(QtGui.QFont('Arial', 10))
self.layout_text.addWidget(self.text)
# Widget with time-edite
layout_edit.addStretch()
self.time_edit = QtWidgets.QTimeEdit(self)
self.time_edit.setFont(QtGui.QFont('Arial', 16))
layout_edit.addWidget(self.time_edit)
# save time from edit-time to class variables
self.saved_time = self.time_edit
# Widget s checkboxes
layout_edit.addStretch()
self.checkbox1 = QtWidgets.QCheckBox("1. monitor", self)
self.checkbox1.setFont(QtGui.QFont('Arial', 10))
layout_edit.addWidget(self.checkbox1)
layout_edit.addStretch()
self.checkbox2 = QtWidgets.QCheckBox("2. monitor", self)
self.checkbox2.setFont(QtGui.QFont('Arial', 10))
layout_edit.addWidget(self.checkbox2)
layout_edit.addStretch()
#widget s error issue
self.error = QtWidgets.QLabel(self)
self.error.setText("<font color='red'>minimum time is 15 minutes</font>")
self.error.setFont(QtGui.QFont('Arial', 14))
layout_error.addWidget(self.error)
self.error.hide()
# Widget with pushbutton
self.Push_button_FW = QtWidgets.QPushButton("Enter", self)
layout_button.addWidget(self.Push_button_FW)
# logic with pushbutton
self.Push_button_FW.clicked.connect(self.check_minimum_edit_time)
# logic with checkboxs
self.checkbox1.clicked.connect(self.checkbox_1_clicked)
self.checkbox2.clicked.connect(self.checkbox_2_clicked)
def back_window(self):
# layout with text and countdown timer
self.text_countdown = QtWidgets.QWidget()
layout_text_countdown = QtWidgets.QHBoxLayout()
self.text_countdown.setLayout(layout_text_countdown)
self.layout_stack2.addWidget(self.text_countdown)
# Layout with pushbutton
button_layout = QtWidgets.QHBoxLayout()
self.layout_stack2.addLayout(button_layout)
# widget with text
layout_text_countdown.addStretch()
self.text = QtWidgets.QLabel("Automatic turning off the PC !!")
self.text.setFont(QtGui.QFont('Arial', 10))
layout_text_countdown.addWidget(self.text)
layout_text_countdown.addStretch()
# widget with countdown timer
self.countdown = QtWidgets.QLabel(self)
self.countdown.setFont(QtGui.QFont('Arial', 16))
layout_text_countdown.addWidget(self.countdown)
layout_text_countdown.addStretch()
# Widget with pushbutton
self.Push_button_BW = QtWidgets.QPushButton("Stop", self)
button_layout.addWidget(self.Push_button_BW)
# logic with pushbutton
self.Push_button_BW.clicked.connect(self.change_windows)
self.Push_button_BW.clicked.connect(self.stop_countdown)
def check_minimum_edit_time(self):
"""
The function monitors whether the user has entered a minimum value in the countdown time.
"""
given_time = self.time_edit.time()
if given_time >= QtCore.QTime(0, 15):
self.change_windows()
self.start_countdown()
self.change_monitor()
else:
self.error.show()
def change_windows(self):
"""
The function changes windows in the application.
"""
if self.Qtstack.currentIndex() == 0:
self.Qtstack.setCurrentIndex(1)
elif self.Qtstack.currentIndex() == 1:
self.Qtstack.setCurrentIndex(0)
def change_monitor(self):
"""
The function changes the output from the PC to the monitor.
"""
if self.checkbox1.isChecked():
os.system("DisplaySwitch.exe / internal")
elif self.checkbox2.isChecked():
os.system("DisplaySwitch.exe / external")
def checkbox_1_clicked(self):
"""
The function ensures that only one checkbox is unchecked at a time.
"""
if self.checkbox1.isChecked():
self.checkbox1.setChecked(True)
self.checkbox2.setChecked(False)
else:
self.checkbox1.setChecked(False)
def checkbox_2_clicked(self):
"""
The function ensures that only one checkbox is unchecked at a time.
"""
if self.checkbox2.isChecked():
self.checkbox2.setChecked(True)
self.checkbox1.setChecked(False)
else:
self.checkbox2.setChecked(False)
def start_countdown(self):
"""
The function starts the countdown when the ENTER button is clicked.
"""
# create string from time
string_time = self.saved_time.time().toString()
# string pulls the time, but only in seconds, and stores a variable that is inserted into the function: timer_start ()
x = time.strptime(string_time.split(',')[0],'%H:%M:%S')
self.seconds = (datetime.timedelta(hours=x.tm_hour,minutes=x.tm_min,seconds=x.tm_sec).total_seconds())
self.timer_start()
def stop_countdown(self):
"""
The function cancels the time countdown.
"""
self.my_qtimer.stop()
def timer_start(self):
"""
The function sets the countdown.
"""
self.time_left_int = self.seconds
self.my_qtimer = QtCore.QTimer(self)
self.my_qtimer.timeout.connect(self.timer_timeout)
self.my_qtimer.start(1000)
def timer_timeout(self):
"""
The function sets the end of the countdown.
"""
if self.time_left_int > 0:
self.time_left_int -= 1
self.update_number()
else:
self.my_qtimer.stop()
os.system("shutdown / s / t 1")
def update_number(self):
"""
The function resets the number every second so that the user can see the countdown.
"""
self.countdown.setText(str(datetime.timedelta(seconds=self.time_left_int)))
class App(QtWidgets.QApplication):
def __init__(self):
super().__init__(sys.argv)
def build(self):
self.main_window = MainForm()
sys.exit(self.exec_())
root = App()
root.build()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T04:31:34.503",
"Id": "488385",
"Score": "0",
"body": "This is interesting code because I didn't know you could use Python to shut down a computer. But for an interview, it might not be that interesting to watch someone shut down their computer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T10:33:09.033",
"Id": "488503",
"Score": "0",
"body": "My first interview for programming job was successful with this code :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T13:54:04.143",
"Id": "488529",
"Score": "0",
"body": "I stand corrected. Congratulations!"
}
] |
[
{
"body": "<h2>Don't mix locales</h2>\n<p>"Aplikace" seems to be Czech, where everything else is English. Choose one or the other consistently. If you want to switch between the two based on the system's locale that is also an option.</p>\n<h2>Stack switching</h2>\n<pre><code> if self.Qtstack.currentIndex() == 0:\n self.Qtstack.setCurrentIndex(1)\n elif self.Qtstack.currentIndex() == 1:\n self.Qtstack.setCurrentIndex(0)\n</code></pre>\n<p>can be</p>\n<pre><code>self.Qtstack.setCurrentIndex(\n 1 - self.Qtstack.currentIndex()\n)\n</code></pre>\n<h2>No-op check</h2>\n<p>Does this actually have any effect?</p>\n<pre><code> if self.checkbox1.isChecked():\n self.checkbox1.setChecked(True)\n else:\n self.checkbox1.setChecked(False)\n</code></pre>\n<p>I think the only thing that needs to be preserved there is the modification of <code>checkbox2</code>.</p>\n<h2>Time splitting</h2>\n<p>This:</p>\n<pre><code>time.strptime(string_time.split(',')[0],'%H:%M:%S')\n</code></pre>\n<p>is worrisome. Why is there a comma in that string? If it's actually because a comma precedes fractional seconds, then don't discard that section of the string using a <code>split</code>; instead include <code>,%f</code> at the end of your format string.</p>\n<h2>Subprocess</h2>\n<p>Replace calls to <code>os.system</code> with calls to <code>subprocess</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T17:54:08.350",
"Id": "480033",
"Score": "0",
"body": "Thank you for your response. I would like to ask more about classes, because I dont know if what I wrote is good design due to functions which occur time in my app. Should I make a new class for them or is this ok ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T17:56:14.620",
"Id": "480034",
"Score": "0",
"body": "The class layout seems fairly reasonable."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T20:33:06.320",
"Id": "244465",
"ParentId": "244461",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244465",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T18:09:46.363",
"Id": "244461",
"Score": "3",
"Tags": [
"python",
"beginner",
"pyqt"
],
"Title": "Automatically turn off PC with Python and PyQt5"
}
|
244461
|
<p>I had the below problem in a coding test and I got 28/30 tests passes and 2 failed due to a time-out.</p>
<blockquote>
<p><strong>Problem</strong><br> You have created a programming language and now you have decided to add <code>hashmap</code> support to it. It was found that in
common programming languages, it is impossible to add a number to all
<code>hashmap</code> keys/values. So, you have decided to implement your own
<code>hashmap</code> in your new language with following operations.</p>
<ul>
<li><code>insert x y</code> - insert and object with key <code>x</code> and value <code>y</code></li>
<li><code>get x</code> - return the value of an object with key <code>x</code></li>
<li><code>addToKey x</code> - add <code>x</code> to all keys in map</li>
<li><code>addToValue y</code> - add <code>y</code> to all values in map</li>
</ul>
<p>Your task is to implement this <code>hashmap</code>, apply the given queries, and
to find the <strong>sum</strong> of all the results for <code>get</code> operations</p>
</blockquote>
<p><strong>For Example</strong><br></p>
<ul>
<li>For <code>queryType=["insert","insert","addToValue","addToKey","get"]</code> and <code>query=[[1,2],[2,3],[2],[1],[3]]</code>, the output should be <code>hashMap(queryType,query)=5</code>.</li>
</ul>
<p><strong>Explanation</strong><br></p>
<ol>
<li><code>insert 1 2</code> - hashmap will be <code>{1:2}</code></li>
<li><code>insert 2 3</code> - hashmap will be <code>{1:2,2:3}</code></li>
<li><code>addToValue 2</code> - hashmap will be <code>{1:4,2:5}</code></li>
<li><code>addToKey 1</code> - hashmap will be <code>{2:4,3:5}</code></li>
<li><code>get 3</code> - value is 5</li>
</ol>
<blockquote>
<p><strong>Input/Output</strong></p>
<ul>
<li><strong>[execution time limit] 3 seconds (Java)</strong></li>
<li><strong>[input] array.string queryType</strong><br>
Array of query types. its is guaranteed that each <code>queryType[i]</code> any one of the above mentioned operation<br>
1<=queryType.length<=10^5</li>
<li><strong>[input] array.array.integer query</strong><br>
Array of queries, where each query is mentioned by 2 numbers for insert and one number for others
Key values are in range [-10^9,10^9]</li>
</ul>
</blockquote>
<p><strong>Below is my solution in <code>Java</code></strong><br></p>
<pre><code>long hashMap(String[] queryType, int[][] query) {
long sum = 0;
Integer currKey = 0;
Integer currValue = 0;
Map<Integer, Integer> values = new HashMap<>();
for (int i = 0; i < queryType.length; i++) {
String currQuery = queryType[i];
switch (currQuery) {
case "insert":
HashMap<Integer, Integer> copiedValues = new HashMap<>();
if (currKey != 0 || currValue != 0) {
Set<Integer> keys = values.keySet();
for (Integer key : keys) {
copiedValues.put(key + currKey, values.get(key) + currValue);
}
values.clear();
values.putAll(copiedValues);
currValue = 0;
currKey = 0;
}
values.put(query[i][0], query[i][1]);
break;
case "addToValue":
currValue += values.isEmpty() ? 0 : query[i][0];
break;
case "addToKey":
currKey += values.isEmpty() ? 0 : query[i][0];
break;
case "get":
copiedValues = new HashMap<>();
if (currKey != 0 || currValue != 0) {
Set<Integer> keys = values.keySet();
for (Integer key : keys) {
copiedValues.put(key + currKey, values.get(key) + currValue);
}
values.clear();
values.putAll(copiedValues);
currValue = 0;
currKey = 0;
}
sum += values.get(query[i][0]);
}
}
return sum;
}
</code></pre>
<p>Is there any other data structure I can use instead of <code>hashmap</code> or Can I improve my code to be more linear?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T08:38:16.077",
"Id": "479968",
"Score": "0",
"body": "Welcome to Code Review. I don't understand why you creates a new `Map` every time you make `insert` or `get` queries, if you can explain me why I appreciate it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T09:30:02.603",
"Id": "479969",
"Score": "2",
"body": "@dariosicily, Its because I don't want to overwrite the existing value while updating a key or map. Example: For {2:3,3:1}, If you want to add key 1 and value 1. In the first iteration, It will become {3:4}. Here, I will lose the actual 3:1 which is the next key value pair. In short, to avoid overwriting/collision of key value pairs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T11:48:22.930",
"Id": "479975",
"Score": "0",
"body": "Thanks, now I got it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T09:01:52.780",
"Id": "530005",
"Score": "0",
"body": "For such problems: realize that addToKey and addToValue are cummulative+global and can be held outside an internal wrapped map. `get(7)` after `addToKey(4)` and `addToKey(1)` means `internalMap.get(7-(4+1))`. And _than_ create a solution."
}
] |
[
{
"body": "<p>I have some suggestions for you.</p>\n<h2>Extract some of the logic to methods.</h2>\n<p>In your code, when the query is <code>insert</code> and <code>get</code>, you have two big blocks of code that are similar; you can extract to a method and reuse the method in both sections.</p>\n<p>I suggest a method that returns a boolean based on the <code>if</code> condition, so you will be able to set the <code>currValue</code> and <code>currKey</code> variables to zero.</p>\n<pre class=\"lang-java prettyprint-override\"><code>\nlong hashMap(String[] queryType, int[][] query) {\n //[...]\n switch (currQuery) {\n //[...]\n case "insert":\n if (didWeCopiedValuesToMap(currKey, currValue, values)) {\n currValue = 0;\n currKey = 0;\n }\n values.put(query[i][0], query[i][1]);\n break;\n //[...]\n }\n //[...]\n}\n\n\nprivate boolean didWeCopiedValuesToMap(Integer currKey, Integer currValue, Map<Integer, Integer> values, HashMap<Integer, Integer> copiedValues) {\n if (currKey != 0 || currValue != 0) {\n Set<Integer> keys = values.keySet();\n for (Integer key : keys) {\n copiedValues.put(key + currKey, values.get(key) + currValue);\n }\n values.clear();\n values.putAll(copiedValues);\n\n return true;\n }\n\n return false;\n}\n</code></pre>\n<p>Also, to check the current query <code>currQuery</code>, you can extract each of them in a method.</p>\n<pre class=\"lang-java prettyprint-override\"><code>private boolean isGet(String currQuery) {\n return "get".equals(currQuery);\n}\n\nprivate boolean isAddToKey(String currQuery) {\n return "addToKey".equals(currQuery);\n}\n\nprivate boolean isAddToValue(String currQuery) {\n return "addToValue".equals(currQuery);\n}\n\nprivate boolean isInsert(String currQuery) {\n return "insert".equals(currQuery);\n}\n</code></pre>\n<h2>Always use the primitives when possible</h2>\n<p>When you know that it's impossible to get a null value with the number, try to use the primitives; they take less memory and is faster than the wrapper class.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>Integer currKey = 0;\nInteger currValue = 0;\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>int currKey = 0;\nint currValue = 0;\n</code></pre>\n<h2>Try to put less code in <code>switch</code> blocks</h2>\n<p>In my opinion, the code becomes less readable when there are more than 3 lines of codes in a switch block; I suggest that you convert it to a <code>is-else-if</code>. This conversion will make the code shorter and more readable.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>switch (currQuery) {\ncase "insert":\n if (didWeCopiedValuesToMap(currKey, currValue, values)) {\n currValue = 0;\n currKey = 0;\n }\n values.put(query[i][0], query[i][1]);\n break;\ncase "addToValue":\n currValue += values.isEmpty() ? 0 : query[i][0];\n break;\ncase "addToKey":\n currKey += values.isEmpty() ? 0 : query[i][0];\n break;\ncase "get":\n if (didWeCopiedValuesToMap(currKey, currValue, values)) {\n currValue = 0;\n currKey = 0;\n }\n sum += values.get(query[i][0]);\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if ("insert".equals(currQuery)) {\n if (didWeCopiedValuesToMap(currKey, currValue, values)) {\n currValue = 0;\n currKey = 0;\n }\n values.put(query[i][0], query[i][1]);\n} else if ("addToValue".equals(currQuery)) {\n currValue += values.isEmpty() ? 0 : query[i][0];\n} else if ("addToKey".equals(currQuery)) {\n currKey += values.isEmpty() ? 0 : query[i][0];\n} else if ("get".equals(currQuery)) {\n if (didWeCopiedValuesToMap(currKey, currValue, values)) {\n currValue = 0;\n currKey = 0;\n }\n sum += values.get(query[i][0]);\n}\n</code></pre>\n<h1>Refactored code</h1>\n<pre class=\"lang-java prettyprint-override\"><code> long hashMap(String[] queryType, int[][] query) {\n long sum = 0;\n int currKey = 0;\n int currValue = 0;\n\n Map<Integer, Integer> values = new HashMap<>();\n\n for (int i = 0; i < queryType.length; i++) {\n String currQuery = queryType[i];\n if (isInsert(currQuery)) {\n if (didWeCopiedValuesToMap(currKey, currValue, values)) {\n currValue = 0;\n currKey = 0;\n }\n values.put(query[i][0], query[i][1]);\n } else if (isAddToValue(currQuery)) {\n currValue += values.isEmpty() ? 0 : query[i][0];\n } else if (isAddToKey(currQuery)) {\n currKey += values.isEmpty() ? 0 : query[i][0];\n } else if (isGet(currQuery)) {\n if (didWeCopiedValuesToMap(currKey, currValue, values)) {\n currValue = 0;\n currKey = 0;\n }\n sum += values.get(query[i][0]);\n }\n }\n\n return sum;\n }\n\n private boolean isGet(String currQuery) {\n return "get".equals(currQuery);\n }\n\n private boolean isAddToKey(String currQuery) {\n return "addToKey".equals(currQuery);\n }\n\n private boolean isAddToValue(String currQuery) {\n return "addToValue".equals(currQuery);\n }\n\n private boolean isInsert(String currQuery) {\n return "insert".equals(currQuery);\n }\n\n private boolean didWeCopiedValuesToMap(int currKey, int currValue, Map<Integer, Integer> values) {\n HashMap<Integer, Integer> copiedValues = new HashMap<>();\n\n if (currKey != 0 || currValue != 0) {\n Set<Integer> keys = values.keySet();\n\n for (Integer key : keys) {\n copiedValues.put(key + currKey, values.get(key) + currValue);\n }\n\n values.clear();\n values.putAll(copiedValues);\n\n return true;\n }\n\n return false;\n }\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T23:40:02.873",
"Id": "244476",
"ParentId": "244468",
"Score": "3"
}
},
{
"body": "<p>The most expensive operation is the <code>addToKey x</code> that adds x to all keys in map, because substantially you have to create a new entry key, value + x in your <code>hashmap</code> and delete the old entry key, value. To avoid the need of caching the old entry while iterating over the map, you can distinguish two cases:</p>\n<p>x > 0, then if you have iterate over a <code>keyset</code> ordered descending there is no need of caching the old entries</p>\n<p>x < 0, same approach but the <code>keyset</code> is ordered ascending</p>\n<p>Because you are using <code>hashmap</code>, there is no key order guaranteed, so you need a data structure to store keys to be ordered, before iterating over keys like below:</p>\n<pre><code>private static void addtoKey(Map<Integer, Integer> map, int i) {\n if (i != 0) {\n List<Integer> list = new ArrayList<>(map.keySet());\n\n if (i > 0) {\n Collections.sort(list, Collections.reverseOrder());\n } else {\n Collections.sort(list);\n }\n\n for(int key : list) {\n map.put(key + i, map.get(key));\n map.remove(key);\n }\n }\n}\n</code></pre>\n<p>I excluded the case <code>0</code> because <code>map</code> remains untouched.\nOther operations don't need order of the keys and as already suggested it could be better try to isolate every operation in a private method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T08:32:13.497",
"Id": "480096",
"Score": "0",
"body": "Thanks @dariosicily for the answer. Isn't sorting every time while making `addToKey` operation is costly as well?. Or Can I use a `SortedMap` to keep the insertion order descending. Like, `SortedMap<Integer, Integer>values = new TreeMap<Integer, Integer>(Collections.reverseOrder());`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T08:45:55.760",
"Id": "480097",
"Score": "0",
"body": "@Praveen You are welcome. Yes it is sorting every time , but with `ArrayList` after sorting you proceed in a linear way. I was convicted you could use only `HashMap`; if you can use `TreeMap` instead of `HashMap` you can use an iterator and a reverse iterator and iterate over your `TreeMap` in a straight way."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T16:22:23.197",
"Id": "244514",
"ParentId": "244468",
"Score": "4"
}
},
{
"body": "<p>What about just storing an offset value for keys and values and building wrapper methods around the hashmaps get/put methods to account for this offset.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T01:05:24.693",
"Id": "249416",
"ParentId": "244468",
"Score": "1"
}
},
{
"body": "<p>I would suggest you create your own <code>OffsetIntegerMap</code> that can map between integers and handle an offset on the keys and values.</p>\n<p>You don't necessarily have to implement the <code>HashMap</code> from scratch, define your own limited interface and implement it with an existing <code>Map<Integer, Integer></code> through composition.</p>\n<p>By handling the offsets separately from the keys and values the complexity of the offset operations end up O(1) instead of O(n) when doing recalculations and the <code>Map<></code> put and get operations stay at their original O(1).</p>\n<p>An example an "<code>OffsetIntegerMap</code>":</p>\n<pre><code>import java.util.HashMap;\nimport java.util.Map;\n\npublic class OffsetIntegerMap {\n private final Map<Integer, Integer> actualMap;\n private int keyOffset = 0;\n private int valueOffset = 0;\n\n public OffsetIntegerMap() {\n actualMap = new HashMap<>();\n }\n\n public int size() {\n return actualMap.size();\n }\n\n public boolean isEmpty() {\n return actualMap.isEmpty();\n }\n\n public boolean containsKey(int key) {\n var keyWithoutOffset = key - keyOffset;\n return actualMap.containsKey(keyWithoutOffset);\n }\n\n public boolean containsValue(int value) {\n var valueWithoutOffset = value - valueOffset;\n return actualMap.containsValue(valueWithoutOffset);\n }\n\n public Integer get(int key) {\n var keyWithoutOffset = key - keyOffset;\n var value = actualMap.get(keyWithoutOffset);\n if (value == null) return null;\n return value + valueOffset;\n }\n\n public Integer put(int key, int value) {\n var keyWithoutOffset = key - keyOffset;\n var valueWithoutOffset = value - valueOffset;\n var oldValue = actualMap.put(keyWithoutOffset, valueWithoutOffset);\n if (oldValue == null) return null;\n return oldValue + valueOffset;\n }\n\n public Integer remove(int key) {\n var keyWithoutOffset = key - keyOffset;\n var oldValue = actualMap.remove(keyWithoutOffset);\n if (oldValue == null) return null;\n return oldValue + valueOffset;\n }\n\n public void clear() {\n actualMap.clear();\n keyOffset = 0;\n valueOffset = 0;\n }\n\n public int getKeyOffset() {\n return keyOffset;\n }\n\n public void setKeyOffset(int keyOffset) {\n this.keyOffset = keyOffset;\n }\n\n public int getValueOffset() {\n return valueOffset;\n }\n\n public void setValueOffset(int valueOffset) {\n this.valueOffset = valueOffset;\n }\n\n public void addToValues(int toAdd) {\n this.valueOffset += toAdd;\n }\n\n public void addToKeys(int toAdd) {\n this.keyOffset += toAdd;\n }\n}\n</code></pre>\n<p>By encapsulating the offset logic the processing loop also becomes much simpler without refactoring much of anything:</p>\n<pre><code>static long hashMap(String[] queryType, int[][] query) {\n long sum = 0;\n var map = new OffsetIntegerMap();\n for (int i = 0; i < queryType.length; i++) {\n String currQuery = queryType[i];\n switch (currQuery) {\n case "insert":\n map.put(query[i][0], query[i][1]);\n break;\n case "addToValue":\n map.addToValues(query[i][0]);\n break;\n case "addToKey":\n map.addToKeys(query[i][0]);\n break;\n case "get":\n sum += map.get(query[i][0]);\n }\n }\n return sum;\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T08:57:03.733",
"Id": "489092",
"Score": "0",
"body": "Thank you. Looks like a better implementation. I will check on this logic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T08:58:54.327",
"Id": "489093",
"Score": "0",
"body": "I find this answer top. Using a class separate from testing all cases. `keyWithoutOffset` and `valueWithoutOffset` (I think I saw a bug in the original code w.r..t. to that). The clear names (offset). Just the method names are Map centric instead of those in the requirements"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T09:47:04.843",
"Id": "489099",
"Score": "0",
"body": "You can use the example from the question. Just replace `[]` with `{}`. `queryType` is `String[]` and `query` is `int[][]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T11:27:39.313",
"Id": "489110",
"Score": "0",
"body": "Ah, overlooked that. And I'm too spoiled by coding challenge sites just giving me a \"Run\" button :-). Modified this solution into my own answer now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T16:17:26.770",
"Id": "501826",
"Score": "0",
"body": "Offset will not be same for every key in hashmap! \n- start with keyset (1,2,3) \n- add 10 to all keys, now keyset is (10,11,12)\n- insert new key (5), now keyset is (10,11,12,5) \n- add 10 to all keys, now keyset is (20,21,22,15).\n\nSo the first 3 keys effectively had offset 20 added to them, but last key had offset only 10 (i.e. key additions done before this key (5) was inserted will be ignored)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T19:18:01.953",
"Id": "502458",
"Score": "0",
"body": "How does setting the amount of offset determined by the `key` or `value` amount avoid running into collisions with the original HashMap keys?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T19:34:52.027",
"Id": "502462",
"Score": "0",
"body": "This makes more sense after reading *[@superb rain's solution](https://codereview.stackexchange.com/a/249489/220526)*. The offsets are applied uniformly to all operations thus avoiding collisions."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T08:31:18.133",
"Id": "249480",
"ParentId": "244468",
"Score": "10"
}
},
{
"body": "<p>Modified version of <a href=\"https://codereview.stackexchange.com/a/249480/228314\">Johnbot's answer</a> <em>without</em> an extra class. I think the extra class is overkill and rather distracts from the algorithm, as I have to search through a lot of code (a lot of it boilerplate) to see what's going on. It's not that extra class that makes the processing loop much simpler. It's the algorithm.</p>\n<p>Further changes:</p>\n<ul>\n<li><code>keyOffset</code> isn't clear to me in which direction it's offset, so I renamed that to <code>addedToKey</code> (likewise for value).</li>\n<li>Ordered the operation names as in the problem specification, both to stay close to the specification and because that order makes more sense to me.</li>\n<li>Introduced <code>args</code> to save some code repetition.</li>\n<li>Used <code>long</code>/<code>Long</code> for everything, not just for the sum. After all, adding to the keys/values could make them overflow if we just use <code>int</code>/<code>Integer</code>.</li>\n</ul>\n<pre><code>static long hashMap(String[] queryType, int[][] query) {\n Map<Long, Long> map = new HashMap<>();\n long sum = 0, addedToKey = 0, addedToValue = 0;\n for (int i = 0; i < query.length; i++) {\n int[] args = query[i];\n switch (queryType[i]) {\n case "insert":\n map.put(args[0] - addedToKey, args[1] - addedToValue);\n break;\n case "get":\n sum += map.get(args[0] - addedToKey) + addedToValue;\n break;\n case "addToKey":\n addedToKey += args[0];\n break;\n case "addToValue":\n addedToValue += args[0];\n }\n }\n return sum;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T20:04:09.870",
"Id": "502464",
"Score": "0",
"body": "Why does uniformly adding `addedToKey` to the value's key not work, yet subtracting it for the `insert` and `get` actions does work?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T11:26:18.770",
"Id": "249489",
"ParentId": "244468",
"Score": "2"
}
},
{
"body": "<p>Simple O(nlogn) 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>long long hashMap(vector<string> query, vector<vector<int>> q) {\n int n = query.size();\n int KeyOff = 0, ValOff = 0;\n map<int, int> mp;\n int x, y;\n int ans = 0;\n for(int i = 0 ; i < n ; i++) {\n if(query[i] == \"insert\") {\n x = q[i][0];\n y = q[i][1];\n mp[x-KeyOff] = y - ValOff;\n }\n else if(query[i] == \"addToValue\") {\n y = q[i][0];\n ValOff += y;\n }\n else if(query[i] == \"addToKey\") {\n x = q[i][0];\n KeyOff += x;\n }\n else {\n x = q[i][0];\n ans += mp[x-KeyOff] + ValOff;\n }\n }\n return ans;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T19:34:53.690",
"Id": "529967",
"Score": "4",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T23:33:49.637",
"Id": "529989",
"Score": "1",
"body": "How does this differ from [superb rain's answer](https://codereview.stackexchange.com/a/249489/93149)? Down to both (all, in all fairness) implementations making me parse `[i][0]` more often than I care to."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T18:50:40.280",
"Id": "268698",
"ParentId": "244468",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T20:54:27.253",
"Id": "244468",
"Score": "10",
"Tags": [
"java",
"algorithm",
"programming-challenge",
"time-limit-exceeded",
"hash-map"
],
"Title": "Enhanced Hashmap - Add a number to all keys/values"
}
|
244468
|
<p>I'm solving a knapsack problem <a href="https://atcoder.jp/contests/dp/tasks/dp_e" rel="nofollow noreferrer">here</a>. It works, but gives time limit exceeds on a certain test case.</p>
<hr />
<h3>Problem statement</h3>
<p>There are N
items, numbered 1,2,…,N. For each i (1≤i≤N), Item i has a weight of wi and a value of vi</p>
<p>Taro has decided to choose some of the N
items and carry them home in a knapsack. The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W</p>
<p>Find the maximum possible sum of the values of items that Taro takes home.</p>
<hr />
<p>The input is in the following form:</p>
<pre><code>N W
w1 v1
w2 v2
:
wN vN
</code></pre>
<p>N: Number of items.</p>
<p>W: Max weight I can have.</p>
<p>wi: ith weight.</p>
<p>vi: ith value.</p>
<p>Here is my solution to it:</p>
<pre><code>using System;
using System.Collections.Generic;
public static class Solution
{
// Both s_weights and s_values will have the same length.
private static int[] s_weights; // array holding the weights of the items.
private static int[] s_values; // array holding the values of the items.
private static Dictionary<(int, int), long> s_memo; // memoization dictionary.
// NOTE: I cannot use an array instead of a dictionary here, cause it
// will be a very large 2d array and will give OutOfMemoryException.
public static void Main()
{
// Read the first line, which contains number of items and max weight.
string[] nw = Console.ReadLine().Split(' ');
// Parse n.
int n = int.Parse(nw[0]);
// Parse the max weight.
int maxWeight = int.Parse(nw[1]);
s_weights = new int[n];
s_values = new int[n];
// arbitrary high capacity dictionary to avoid resizing which is O(n).
s_memo = new Dictionary<(int, int), long>(10000000);
// Read each line from the input.
for (int i = 0; i < n; i++)
{
string[] wv = Console.ReadLine().Split(' ');
s_weights[i] = int.Parse(wv[0]);
s_values[i] = int.Parse(wv[1]);
}
// Start the recursion with the maximum weight and all the items.
Console.WriteLine(Solve(maxWeight, n));
}
private static long Solve(int weightLeft, int numberOfItemsToConsider)
{
// simple base case.
if (weightLeft == 0 || numberOfItemsToConsider == 0) return 0;
// If already calculated, get it from the dictionary.
if (s_memo.TryGetValue((weightLeft, numberOfItemsToConsider), out var cachedValue))
{
return cachedValue;
}
// Recursive call calculating the solution if we don't take the current item.
long dontTakeCurrent = Solve(weightLeft, numberOfItemsToConsider - 1);
long result;
// Can we take the current item? If yes, calculate the solution.
if (weightLeft >= s_weights[numberOfItemsToConsider - 1])
{
long takeCurrent = s_values[numberOfItemsToConsider - 1] + Solve(weightLeft - s_weights[numberOfItemsToConsider - 1], numberOfItemsToConsider - 1);
// Maximize the value between the two cases, taking or not taking the item.
result = Math.Max(takeCurrent, dontTakeCurrent);
// Add the result to the memo dictionary.
s_memo.Add((weightLeft, numberOfItemsToConsider), result);
return result;
}
// Here, we don't have another choice other than not taking the item.
result = dontTakeCurrent;
s_memo.Add((weightLeft, numberOfItemsToConsider), result);
return result;
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T19:59:27.233",
"Id": "480718",
"Score": "0",
"body": "Do you have to use Console.ReadLine? Can these not be passed as args to main?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T20:39:05.217",
"Id": "480725",
"Score": "1",
"body": "What is the test case where it exceeds the time limit?"
}
] |
[
{
"body": "<p>Instead of storing the actual values in a tuple as the key in a dictionary for memoisation, multiplex them together into a single value and use that as the key. You will need to pick multiplex value that is an order of magnitude higher than the largest "numberOfItemsToConsider" you can expect. Or you could turn them into strings and concat for the key.</p>\n<p>i.e.</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>var key = (weightLeft * 10_000) + numberOfItemsToConsider; // parens for readability.\n// OR\nvar key = weightLeft.ToString() + "_" + numberOfItemsToConsider.ToString(); // parens for readability.\n</code></pre>\n<p><strong>EDIT: Thanks @Jeff E for correcting me on this, Hashtable is slower.</strong>\n<strike>Instead of a dictionary, you could use a hashtable, which is faster. i.e.</strike></p>\n<p>Finally, if you're chasing every little bit of time, allocate all your variables outside of any loops, so they are not continually being reallocated, which has an expense.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-02T13:24:58.567",
"Id": "480798",
"Score": "0",
"body": "Wouldn't the boxing and unboxing with a `Hashtable` make it slower?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-02T14:51:10.220",
"Id": "480807",
"Score": "0",
"body": "@JeffE, you are correct! After some research I realise I have been miss-using this. Updating my answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T20:18:48.433",
"Id": "244851",
"ParentId": "244470",
"Score": "2"
}
},
{
"body": "<blockquote>\n<pre><code>// Both s_weights and s_values will have the same length.\nprivate static int[] s_weights; // array holding the weights of the items.\nprivate static int[] s_values; // array holding the values of the items.\nprivate static Dictionary<(int, int), long> s_memo; // memoization dictionary.\n\n// NOTE: I cannot use an array instead of a dictionary here, cause it\n// will be a very large 2d array and will give OutOfMemoryException.\n\npublic static void Run(int n, int maxWeight, int[] weights, int[] values)\n{\n</code></pre>\n</blockquote>\n<p>In general: IMO it's bad design if you use static members as state members. Here it's maybe unimportant because it's just an exercise, but in real world you shouldn't do that, because it's asking for trouble if you for instance run the code in two different threads at the same time.</p>\n<p>So change them to instance members and provide a static starter method like:</p>\n<pre><code>public class Knapsack\n{\n private int n;\n private int maxWeight;\n private int[] weights;\n private int[] values;\n\n public Knapsack(int n, int maxWeight, int[] weights, int[] values)\n {\n this.n = n;\n this.maxWeight = maxWeight;\n this.weights = weights;\n this.values = values;\n }\n\n public long Run()\n {\n // TODO: The algorithm\n }\n\n public static long Solve(int n, int maxWeight, int[] weights, int[] values)\n {\n Knapsack solution = new Knapsack(n, maxWeight, weights, values);\n return solution.Run();\n }\n}\n</code></pre>\n<hr />\n<p>Besides that, I won't mention that you should separate the input handling and the processing into different classes.</p>\n<hr />\n<p>When it comes to the algorithm it self, I have tried to clean it up a bit:</p>\n<pre><code>private static long Solve(int weightLeft, int numberOfItemsToConsider)\n{\n // simple base case.\n if (weightLeft == 0 || numberOfItemsToConsider == 0) return 0;\n\n // If already calculated, get it from the dictionary.\n if (s_memo.TryGetValue((weightLeft, numberOfItemsToConsider), out var cachedValue))\n return cachedValue;\n\n long result = Solve(weightLeft, numberOfItemsToConsider - 1);\n\n // Can we take the current item? If yes, calculate the solution.\n if (weightLeft >= s_weights[numberOfItemsToConsider - 1])\n {\n long takeCurrent = s_values[numberOfItemsToConsider - 1] + Solve(weightLeft - s_weights[numberOfItemsToConsider - 1], numberOfItemsToConsider - 1);\n // Maximize the value between the two cases, taking or not taking the item.\n result = Math.Max(takeCurrent, result);\n // Add the result to the memo dictionary.\n }\n\n s_memo[(weightLeft, numberOfItemsToConsider)] = result;\n return result;\n}\n</code></pre>\n<p>It doesn't do much performance wise but, is maybe a little easier to follow.</p>\n<hr />\n<p>A significant performance gain you'll only get, if you substitute the <code>s_memo</code>-dictionary with a two dimensional jagged array:</p>\n<pre><code>static long[][] valueTable = null;\n\npublic static void Run(...) {\n valueTable = Enumerable.Range(0, n + 1).Select(i => Enumerable.Range(0, maxWeight + 1).Select(_ => -1L).ToArray()).ToArray();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-02T17:14:41.200",
"Id": "244891",
"ParentId": "244470",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T22:28:42.640",
"Id": "244470",
"Score": "2",
"Tags": [
"c#",
"algorithm",
"dynamic-programming",
"memoization",
"knapsack-problem"
],
"Title": "Knapsack performance issue"
}
|
244470
|
<p>I have written a few classical Python functions in JavaScript. I would appreciate any kind of feedback. The main goal is to learn about JavaScript. For example errors, improvements or existing JavaScript functions that I missed. Additionally, challenges that would be interesting to tackle next would be appreciated.</p>
<pre class="lang-javascript prettyprint-override"><code>// Lets start with a simple one:
function list(e){
return Array.from(e);
}
function* zip(...iterables){
const iterators = iterables.map(it => iter(it));
while(true){
const items = iterators.map(it => it.next());
if (items.some(item => item.done)){
return;
}
yield items.map(item => item.value);
}
}
function* map(func, iterable){
for (let elem of iterable){
yield func(elem);
}
}
function* enumerate(iterable, start=0){
let i = start;
for (let elem of iterable){
yield [i++, elem];
}
}
function* iter(object, sentinel){
if (!sentinel){
yield* object;
return;
}
while (true) {
if (typeof object !== "function"){
throw TypeError("iter(object, sentinel): object must be a function")
}
result = object();
if (result === sentinel){
return;
}
yield result;
}
}
function* repeat(object, times){
for (let i = 0; i < times; i += 1) yield object;
}
function* range(start, end=undefined, step=1) {
if(end === undefined){
end = start;
start = 0;
}
for (let i = start; i < end; i += step){
yield i;
}
}
function* cycle(iterable){
saved = [];
for (const e of iterable){
yield e
saved.push(e);
}
while (true) yield* saved;
}
function* islice(iterable, start, end){
if (!end){
end = start;
start = 0;
}
dropfirsts(iterable, start);
yield* firsts(iterable, end-start);
}
function dropfirsts(iterable, n){
for (let i of range(n)){
if (iterable.next().done) return;
}
}
function* firsts(iterable, n){
for (let j of range(n)){
const item = iterable.next();
if (item.done) return;
yield item.value;
}
}
</code></pre>
<p>Here are a few examples of how to use it.
These are likely not the best.</p>
<pre class="lang-javascript prettyprint-override"><code>console.log("Repeating the same value with repeat():")
console.log("\t", list(repeat("x", 5)));
console.log("Pairs of consecutive items from a list using zip():");
const l = [1,2,3,4];
const liter = iter(l);
const literNext = iter(l);
literNext.next();
for (const [x, y] of zip(liter, literNext)) {
console.log("\t", x, y);
}
console.log("Iterator over a callable (with sentinel):");
function f(){
let count = 0;
return () => count+=1;
}
for (const x of iter(f(), 5)){
console.log("\t", x);
}
console.log("Pairing two lists of distinct size with zip():");
for (const [x, y] of zip([1, 2, 3], ["a", "b"])) {
console.log("\t", x, y);
}
console.log("Building two lists from a list of pairs using zip():");
const pairList = [[1,2], [3,4], [5,6], [7,8]];
for (const X of zip(...pairList)) {
console.log("\t", X);
}
console.log("Time two table using zip() and range():");
for (let [i,j] of zip(range(5), range(0, 10, 2))){
console.log("\t", `${i} x 2 = ${j}`);
}
console.log("Enumerate letters from the alphabet with enumerate():");
for (let [i, e] of enumerate(["a", "b", "c"], 1)){
console.log("\t", e, i);
}
console.log("Convert an iterable to an array using list():");
const rangeLen = 5;
console.log("\t", `list(range(${rangeLen})) = `, list(range(rangeLen)));
const squares = list(map(i => i*i, range(5))).join(',');
console.log("Map an iterator using map():");
console.log("\t", `squares = ${squares}`);
const size = 3;
const cycleThrough = [1, 2];
console.log(`Cycle (firsts ${size} elements) of [${cycleThrough}] using cycle():`);
let i = 0;
for (const x of cycle(cycleThrough)){
i += 1;
if (i > size) break;
console.log("\t", x);
}
console.log(`Same using cycle() and islice():`);
for (const x of islice(cycle(cycleThrough), size)){
console.log("\t", x);
}
const start = 1;
console.log(`Same but starting at element ${start}:`);
for (const x of islice(cycle(cycleThrough), start, size+start)){
console.log("\t", x);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T23:32:07.903",
"Id": "479930",
"Score": "3",
"body": "FWIW your current title makes me think that you'll be transpiling from a Pythonesque language to JavaScript. However this is not the case, a better title may be something like \"Adding common Python functions to JavaScript\"."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T23:03:12.837",
"Id": "244472",
"Score": "1",
"Tags": [
"javascript",
"functional-programming"
],
"Title": "Adding common Python functions to JavaScript"
}
|
244472
|
<p>This JavaScript code generates the full name of the numeral scales for large numbers under the "<strong>Short Scale Numeral System</strong>" using the Conway-Guy system for forming number prefixes.</p>
<p>Some very brief information on how this is done can be found at the end of <a href="https://en.wikipedia.org/wiki/Names_of_large_numbers" rel="nofollow noreferrer">this Wikipedia article</a>.</p>
<p>However, I have tried in this article to give more details on how this can be generated and coded programmatically and an explanation of the system.</p>
<p>The code handles numeral scales names up to 1000^999 (i.e. the number 1 followed by 3000 zeros).</p>
<p>The naming procedure for large numbers is based on taking the number power of the number and concatenating the Latin roots for its units, tens, and hundreds place, together with the suffix "<strong>llion</strong>".</p>
<p>Note the sequence and order of the concatenation is from lowest to largest (this opposite to how we pronounce and write numbers such as 123 [one hundred twenty-three]).</p>
<p>This way, numbers up to 10^3000 (or 1000^ 999) may be named easily.</p>
<p>The choice of Latin roots and the concatenation procedure is as follows:</p>
<p><strong>For small powers from 1 to 9:</strong> Use standard dictionary (i.e. million, billion, trillion, etc. up to nonillion).</p>
<p><strong>For larger powers (between 10 and 999):</strong> prefixes are constructed based on a system described by John Horton Conway and Richard K. Guy using the Latin roots.</p>
<p>The Conway-Guy System for forming prefixes is included in the following table:</p>
<p><a href="https://i.stack.imgur.com/vviWw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vviWw.png" alt="enter image description here" /></a></p>
<p>The Scale Name can be generated by concatenating the Unit Name, Tens Name, Hundreds Name, and adding "<strong>llion</strong>" to the end of the concatenated string as illustrated below:</p>
<p><a href="https://i.stack.imgur.com/koyVH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/koyVH.png" alt="enter image description here" /></a></p>
<p>However, concatenation is not that straight forwards because four (4) of the Unit Names (tre (3), se (6), septe (7), and nove (9)) cannot be concatenated directly "as is" and require modification depending on the Tens Name or Hundred Name that follows them.</p>
<p>For example: unit name "tri (3)" need to be changed to "tres" if it is to be concatenated with (say) 20 (viginti) or with 300 (tricinti).</p>
<p>Similarly, "se" need to be changed to "ses" or "sex", "septe" and "nove" also need to be changed to "septem" and "novem" or "septen" and "noven" respectively depending on the tens or hundreds name.</p>
<p>Therefore, for each Tens Name and Hundreds Name there is a corresponding Unit Name that can precede it for the purpose concatenation (this is the purpose of so ugly array).</p>
<p>The illustrative tables below list the changes needed for each Unit Name depending on the Tens Name and the Hundreds Name.</p>
<p><a href="https://i.stack.imgur.com/2o1k1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2o1k1.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/ulTyb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ulTyb.png" alt="enter image description here" /></a></p>
<p>One additional requirement to be considered when concatenating the various names is that Unit Names ending in "a" need to be changed to end with "i" when they are to be concatenated with the word "<strong>llion</strong>". Names ending with "a" only exist in the Tens Names!</p>
<p>For example:</p>
<p>The number 10^31 ==> "triginta" becomes "<strong>triginti</strong>" + "llion" ==> <strong>trigintillion</strong></p>
<p>The number 10^81 ==> "octoginta" becomes "<strong>octoginti</strong>" + "llion" ==> <strong>octogintintillion</strong></p>
<p>The handling of this situation is catered for in the "Tens" array; the last element made as Boolean True being a marker.</p>
<p>Additional Examples are shown in the image below:</p>
<p><a href="https://i.stack.imgur.com/kRZKS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kRZKS.png" alt="enter image description here" /></a></p>
<p>The input to the function is a number which is the power of the base 1000.</p>
<ul>
<li>1 means 1000^1 = 1,000</li>
<li>2 means 1000^2 = 1,000,000 (million)</li>
<li>3 means 1000^3 = 1,000,000,000 (billion)</li>
</ul>
<p>The code function is made to generate the Scale Names for the Short Scale Numeral System used in (USA, UK, Canada, i.e. System using Billion instead of Milliard). You can read about the differences between the Short and Long Scale Numeral Systems <a href="https://en.wikipedia.org/wiki/Long_and_short_scales" rel="nofollow noreferrer">here</a>.</p>
<p>The reason for the code line <code>Power -=1;</code> is that the formula for generating a Scale Name under the Short Scale System for a number n is 10^(3n+3). You can see that from (say) the number "<strong>tri</strong>llion" where "<strong>tri</strong>" means <strong>3</strong> but the number trillion is 10^<strong>4</strong> and not 10^3. <em>So, the prefix Latin names do not correlate to the power number.</em></p>
<p>The code can be modified easily to generate the strings for the Long Scale System using the same arrays. In this case, the maximum power is 10^6000 (i.e. 1 with 6000 zeros).</p>
<p>Test code is included that tests various numbers.</p>
<p>Also included in the testing (however, currently commented) is testing to generate the Scale Names for the powers from 0 to 999. (<em>However, note that the Stack Exchange console will only print out the last 50 lines</em>).</p>
<p>Although the function is not intended to handle powers from 0 to 10, I have included them with a quick check for completeness with full dictionary names for speed.</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 : numberScaleNameShortScale()
* @Purpose : Construct full name of the Short Scale Numeral System
* Using the Conway-Guy system for forming number prefixes
*
* @Version : 0.02
* @Author : Mohsen Alyafei
* @Date : 12 Jun 2020
* @Param : {number} [Power=0] the power numeral of the base 1000
* e.g. 1 means 1000^1 = 1,000
* e.g. 2 means 1000^2 = 1,000,000 (million)
* e.g. 3 means 1000^3 = 1,000,000,000 (billion)
*
* @Returns : {string} The name of the large number
* @Example :
* numberScaleNameShortScale(4);
* // => trillion
*
* numberScaleNameShortScale(21);
* // => vigintillion
*
* @Description : Handles power from 0 to 999
* The larget scale name is therefor the umber with
* 3,000 zeros (Novenonagintanongentillion)
* @Reference : https://en.wikipedia.org/wiki/Names_of_large_numbers
*
* For powers n from 1 to 10, prefixes are constructed based on
* standard dictionary entry.
* For larger powers of n (between 11 and 999), prefixes are constructed
* based on the system described by John Horton Conway and Richard K. Guy.
*************************************************************************/
function numberScaleNameShortScale(Power=0) {
// Do this first and get out quick as it is the most used 99% of the time
// You may delete following line if only interested in Powers above 10 (i.e. 1,000^11 and above)
if (Power<11) return ["","thousand","million","billion","trillion","quadrillion","quintillion","sextillion","septillion","octillion","nonillion"][Power];
Power-=1; // Adjust the sequence above power of 10 as these are now systematic
let TensList = [
["" ,["","","","" ,"","","" ,"" ,"","" ,false]],
["deci" ,["","","","" ,"","","" ,"n","","n",false]], // 10
["viginti" ,["","","","s","","","s","m","","m",false]], // 20
["triginta" ,["","","","s","","","s","n","","n",true ]], // 30
["quadraginta" ,["","","","s","","","s","n","","n",true ]], // 40
["quinquaginta",["","","","s","","","s","n","","n",true ]], // 50
["sexaginta" ,["","","","" ,"","","" ,"n","","n",true ]], // 60
["septuaginta" ,["","","","" ,"","","" ,"n","","n",true ]], // 70
["octoginta" ,["","","","" ,"","","x","m","","m",true ]], // 80
["nonaginta" ,["","","","" ,"","","" ,"" ,"","" ,true ]] // 90
];
let HundredsList = [
["" ,["","","","" ,"","","" ,"" ,"","" ]],
["centi" ,["","","","" ,"","","x","n","","n"]], // 100
["ducenti" ,["","","","" ,"","","" ,"n","","n"]], // 200
["trecenti" ,["","","","s","","","s","n","","n"]], // 300
["quadringenti",["","","","s","","","s","n","","n"]], // 400
["quingenti" ,["","","","s","","","s","n","","n"]], // 500
["sescenti" ,["","","","" ,"","","" ,"n","","n"]], // 600
["septingenti" ,["","","","" ,"","","" ,"n","","n"]], // 700
["octingenti" ,["","","","" ,"","","x","m","","m"]], // 800
["nongenti" ,["","","","" ,"","","" ,"" ,"","" ]] // 900
];
let Hund = Math.floor(Power / 100), // Hundred Digit
Ten = Math.floor(Power % 100 / 10), // Ten Digit
Unit = Power % 10 % 10, // Unit Digit
UnitName = ["","un","duo","tre","quattuor","quin","se","septe","octo","nove"][Unit], // Get Unit Name from Array
TenName = TensList [Ten][0], // Get Tens Name from Array
HundName = HundredsList[Hund][0]; // Get Hundreds Name from Array
// convert Ten names ending with "a" to "i" if it was prceeding the "llion" word
if (!Hund && TensList[Ten][1][10]) TenName = TenName.slice(0,-1)+"i";
// Pickup and add the correct suffix to the Unit Name (s,x,n, or m)
if (Ten) TenName = TensList[Ten] [1][Unit]+TenName;
if (Hund && !Ten) HundName = HundredsList[Hund][1][Unit]+HundName;
return UnitName + TenName + HundName + "llion"; // Create name
}
//=========================================
// Test Codes
//=========================================
function test(n,should) {
var result = numberScaleNameShortScale(n);
if (result !== should) {
console.log(`${n} Output : ${result}`);
console.log(`${n} Should be: ${should}`);
return 1;
}
}
var r=0; // test tracker
r |= test(2,"million");
r |= test(3,"billion");
r |= test(4,"trillion");
r |= test(5,"quadrillion");
r |= test(6,"quintillion");
r |= test(7,"sextillion");
r |= test(8,"septillion");
r |= test(9,"octillion");
r |= test(10,"nonillion");
r |= test(11,"decillion");
r |= test(12,"undecillion");
r |= test(13,"duodecillion");
r |= test(14,"tredecillion");
r |= test(15,"quattuordecillion");
r |= test(16,"quindecillion");
r |= test(17,"sedecillion");
r |= test(18,"septendecillion");
r |= test(19,"octodecillion");
r |= test(20,"novendecillion");
r |= test(21,"vigintillion");
r |= test(22,"unvigintillion");
r |= test(23,"duovigintillion");
r |= test(24,"tresvigintillion");
r |= test(25,"quattuorvigintillion");
r |= test(26,"quinvigintillion");
r |= test(27,"sesvigintillion");
r |= test(28,"septemvigintillion");
r |= test(29,"octovigintillion");
r |= test(30,"novemvigintillion");
r |= test(31,"trigintillion");
r |= test(32,"untrigintillion");
r |= test(33,"duotrigintillion");
r |= test(34,"trestrigintillion");
r |= test(35,"quattuortrigintillion");
r |= test(36,"quintrigintillion");
r |= test(37,"sestrigintillion");
r |= test(38,"septentrigintillion");
r |= test(39,"octotrigintillion");
r |= test(40,"noventrigintillion");
r |= test(41,"quadragintillion");
r |= test(51,"quinquagintillion");
r |= test(61,"sexagintillion");
r |= test(71,"septuagintillion");
r |= test(81,"octogintillion");
r |= test(91,"nonagintillion");
r |= test(101,"centillion");
r |= test(102,"uncentillion");
r |= test(111,"decicentillion");
r |= test(112,"undecicentillion");
r |= test(121,"viginticentillion");
r |= test(122,"unviginticentillion");
r |= test(131,"trigintacentillion");
r |= test(141,"quadragintacentillion");
r |= test(151,"quinquagintacentillion");
r |= test(161,"sexagintacentillion");
r |= test(171,"septuagintacentillion");
r |= test(181,"octogintacentillion");
r |= test(191,"nonagintacentillion");
r |= test(201,"ducentillion");
r |= test(251,"quinquagintaducentillion");
r |= test(301,"trecentillion");
r |= test(351,"quinquagintatrecentillion");
r |= test(378,"septenseptuagintatrecentillion");
r |= test(401,"quadringentillion");
r |= test(451,"quinquagintaquadringentillion");
r |= test(454,"tresquinquagintaquadringentillion");
r |= test(501,"quingentillion");
r |= test(601,"sescentillion");
r |= test(701,"septingentillion");
r |= test(801,"octingentillion");
r |= test(901,"nongentillion");
r |= test(999,"octononagintanongentillion");
if (r==0) console.log("All Passed.");
// Uncomment the following line to list all names from 0 to 999
// for (i=0;i<1000;i++) {console.log(i+": "+numberScaleNameShortScale(i));}</code></pre>
</div>
</div>
</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T23:22:57.990",
"Id": "244474",
"Score": "3",
"Tags": [
"javascript",
"converting",
"number-systems"
],
"Title": "Large Number Scales Names Generator"
}
|
244474
|
<p>The first part of the code opens Chrome and navigates to GitHub. If I don't find my solution, I open a new tab with <kbd>ctrl</kbd><kbd>t</kbd>. Then my code goes to Stack Overflow and searches there for solutions.</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import *
import time
import keyboard
q = input("what is your programming question : ")+(' python')
class github :
path = "c:/users/admin/appdata/local/programs/python/python38-32/chromedriver.exe"
driver = webdriver.Chrome(path)
driver.get("https://github.com/")
question = driver.find_element_by_name("q")
time.sleep(3)
question.send_keys(q)
question.send_keys(Keys.RETURN)
while True:
if keyboard.is_pressed("ctrl+t"):
driver.switch_to_window(driver.window_handles[-1])
driver.get("https://stackoverflow.com/")
question_2 = driver.find_element_by_name("q")
question_2.send_keys(q)
question_2.send_keys(Keys.RETURN)
break
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T10:53:44.227",
"Id": "479973",
"Score": "1",
"body": "Did you consider using URL like `https://stackoverflow.com/search?q=test` for the search, instead of finding DOM element, and entering keystrokes ? You can add filters of your own, like tags `https://stackoverflow.com/search?q=+test+%5Bpython%5D` where `%5B` is `[` and `%5D` is `]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T19:15:26.237",
"Id": "480163",
"Score": "1",
"body": "I would argue that the class isn't necessary here, since this seems like a small script."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T20:39:16.357",
"Id": "480174",
"Score": "0",
"body": "@Linny I know that the class wasn't necessary. I wanted to be more comfortabel using classes and to get to know it better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T10:16:14.070",
"Id": "480199",
"Score": "1",
"body": "Scrapy should be your choice if you are interested in using classes. In Python, it's not like Java where you have to put class everywhere. Modular code with functions is good enough."
}
] |
[
{
"body": "<h2>Selenium</h2>\n<p>Selenium imposes a lot of overhead and complexity that you don't need to deal with. If you needed to scrape, use <code>requests</code> + <code>beautifulsoup</code>; but you don't: StackExchange has a <a href=\"https://api.stackexchange.com/\">good API</a>, so you should strongly prefer using that. It will get you results more efficiently and the results will be more accurate and less fragile.</p>\n<h2>PEP8</h2>\n<pre><code>class github :\n</code></pre>\n<p>should be</p>\n<pre><code>class Github:\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T17:08:48.103",
"Id": "244518",
"ParentId": "244475",
"Score": "5"
}
},
{
"body": "<p>For simply content scrapping without javascript and ajax content try <a href=\"https://scrapy.org/\" rel=\"nofollow noreferrer\">scrapy</a> for best practices. Scrapy uses python classes by default as it is a python framework.\nEasy tutorial to learn Scrapy\n<a href=\"https://www.youtube.com/watch?v=vkA1cWN4DEc&list=PLZyvi_9gamL-EE3zQJbU5N3nzJcfNeFHU\" rel=\"nofollow noreferrer\">Scrapy Tutorial on Youtube</a>\n<a href=\"https://www.scrapinghub.com/learn-scrapy#get-started-scrapy-tutorials\" rel=\"nofollow noreferrer\">Official site of ScrappingHub</a></p>\n<p>Selenium is good for scraping dynamic content and causes unnecessary overhead as mentioned in above answer.</p>\n<p>For above code:\nTry avoiding <code>time.sleep</code> and use <code>EC.presence_of_element_located</code> and similar functions to obtain desired behavior. <a href=\"https://selenium-python.readthedocs.io/waits.html\" rel=\"nofollow noreferrer\">Selenium Waits</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T19:08:25.780",
"Id": "244586",
"ParentId": "244475",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T23:26:11.930",
"Id": "244475",
"Score": "6",
"Tags": [
"python",
"stackexchange",
"selenium",
"webdriver",
"google-chrome"
],
"Title": "Finding solutions on GitHub and Stack Overflow"
}
|
244475
|
<p>First time working with any type of graph traversal. The algorithm determines whether a path exists between two nodes using breadth first searching (BFS). The BFS method returns a tuple; indicating whether a match has been found and the length between the two nodes. I implemented it this way since it's part of a private member and wont be seen externally. When the result is seen as part of the <code>HasPath</code> method I modeled it after the Try-Pattern similar to <code>TryParse(...)</code>.</p>
<p>The local function <code>EnqueueNonVisitedChildrenNodes</code> is declared as such since it would make no sense to call it anywhere else. It too uses a tuple to simplify its invocation.</p>
<p>Am I properly using the tuple type? Is there anything that could be improved with code structure?</p>
<pre><code>using System.Collections.Generic;
using System.Diagnostics;
[DebuggerDisplay("Name = {Name}, ChildCount = {Children.Count}")]
public class Node
{
public string Name { get; }
public List<Node> Children { get; } = new List<Node>();
public bool Visited { get; set; }
public Node(string Name)
{
this.Name = Name;
}
public Node(string name, IEnumerable<Node> children)
{
Name = name;
foreach (var node in children)
{
AddChild(node);
}
}
public void AddChild(Node node)
{
Children.Add(node);
}
}
</code></pre>
<p>The implemented algorithm.</p>
<pre><code>public class PathAlgorithm
{
Node Start { get; }
Node End { get; }
public PathAlgorithm(Node start, Node end)
{
Start = start ?? throw new ArgumentNullException(nameof(start));
End = end ?? throw new ArgumentNullException(nameof(end));
}
public bool HasPath(out int length)
{
bool hasPath;
(hasPath, length) = BreadthFirstSearch(Start);
return hasPath;
}
public (bool, int) BreadthFirstSearch(Node root)
{
if (root == null)
{
return (false, 0);
}
Queue<(Node, int)> searchQueue = new Queue<(Node, int)>();
root.Visited = true;
searchQueue.Enqueue((root, 0));
while (searchQueue.Any())
{
(Node node, int length) = searchQueue.Dequeue();
if (node == End)
{
return (true, length);
}
EnqueueNonVisitedChildrenNodes(searchQueue, (node, length));
}
return (false, 0);
void EnqueueNonVisitedChildrenNodes(Queue<(Node, int)> queue, (Node node, int length) foo)
{
foreach (var n in foo.node.Children)
{
if (!n.Visited)
{
n.Visited = true;
searchQueue.Enqueue((n, foo.length + 1));
}
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The code you have there may accomplish the task you have in mind for it, but it's not useful for a "real world" usecase.<br />\nThat's because usually you'd want to be able to run an algorithm like this multiple times on the same graph, maybe even concurrently.</p>\n<p>The problem that's posing itself here is that <code>Node</code> mixes two concerns: Representing the graph <strong>and</strong> traversing it.</p>\n<p>Storing the <code>Visited</code> state inside the Node is really useful, but it's also quite limiting. As such you could greatly benefit from storing visited <code>Node</code>s as a <code>Set</code> instead to separate traversal from representation.</p>\n<hr />\n<p>There's also some minor optimization possibilities:</p>\n<ul>\n<li><p>Replace the <code>foreach</code> in the <code>Node</code> constructor with <code>AddRange</code></p>\n</li>\n<li><p>Once .NET 5 releases (or you switch to .NET Core) You can slightly simplify the while loop in the BFS itself using <code>searchQueue.TryDequeue(var (node, length))</code>.</p>\n</li>\n<li><p>Storing visited nodes in a HashSet (or similar) enables reformulating <code>EnqueueNotVisitedChildrenNodes</code> as:</p>\n<pre><code>foreach (var child in node.Children.ExceptWith(visited))\n{\n searchQueue.Enqueue((child, length + 1));\n}\n</code></pre>\n<p>This reformulation of course then messes with the visited state of nodes you didn't actually visit yet, since you set <code>Visited</code> when you <strong>enqueue</strong> the node, not when you actually visit it.</p>\n<p>This flagging visited when enqueueing utterly breaks as soon as you start working with "weighted graphs", where the smallest number of edges may not be the optimal path (like the following)</p>\n<pre><code>(A) -(1)- (B) -(1)- (C)\n \\ /\n -------(5)-------\n</code></pre>\n<p>Going from (A) to (C) via (B) is cheaper than the direct route here :), if your real target was a node (D) that's only connected to (C), your current code would route you through (C) because the shorter route through (B) would be ignored since (C) already counts as visited when you dequeue (B).</p>\n</li>\n</ul>\n<hr />\n<p>Overall this code is really nice and clean, but it lacks general applicability (which is not a bad thing in itself).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T13:14:44.703",
"Id": "244501",
"ParentId": "244477",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244501",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T00:06:19.700",
"Id": "244477",
"Score": "4",
"Tags": [
"c#",
"algorithm"
],
"Title": "Algorithm to find path between nodes"
}
|
244477
|
<p>I wrote a script to compute the polarity of sentences. The script is based on this:</p>
<blockquote>
<p>The lexicon based approach assigns a sentiment tags to words in a text based on dictionaries of positive and negative words. A sentiment score is then calculated for each document as:</p>
<p><span class="math-container">$$\frac{\text{number of positive words} - \text{number of negative words}}{\text{total number of words}}$$</span></p>
</blockquote>
<p>Is the code below okay? Should I have to improve it to take into consideration the position of the word in the sentence?</p>
<pre><code>fileDir = os.path.dirname(os.path.realpath('__file__'))
lexiconpos = open(os.path.join(fileDir, 'Ressources/positive.txt'), 'r', encoding='utf-8')
lexiconpos = set([line.rstrip() for line in lexiconpos])
lexiconneg = open(os.path.join(fileDir, 'Ressources/negative.txt'),'r', encoding='utf-8')
lexiconneg = set([line.rstrip() for line in lexiconneg])
path = os.path.join(fileDir, 'data/reference/freins.tsv')
with open(path, 'r', encoding='utf-8') as l_1:
next(l_1)
l_1 = [line.rstrip() for line in l_1]
tagger = treetaggerwrapper.TreeTagger(TAGLANG='fr')
def process_text(text):
'''extract lemma and lowerize then removing stopwords.'''
text_preprocess =[]
text_without_stopwords= []
text = tagger.tag_text(text)
for word in text:
parts = word.split('\t')
try:
if parts[2] == '':
text_preprocess.append(parts[0])
else:
text_preprocess.append(parts[2])
except:
print(parts)
text_without_stopwords= [word.lower() for word in text_preprocess if word.isalnum()] #if word not in stopWords
#return text_without_stopwords
return text_preprocess
def extract_info(texte, lexique1, lexique2):
lemme_treetagger = []
lemme_sent = []
len_sent = []
for elt in texte:
texte_treetagger = process_text(elt.lower())
lemme_treetagger.append(" ".join(texte_treetagger))
len_sent.append(len(" ".join(texte_treetagger)))
word_pos=[]
word_neg=[]
word_pos_len=[]
word_neg_len=[]
for elt in lemme_treetagger:
word_pos.append([word for word in lexique1 if word in elt])
word_neg.append([word for word in lexique2 if word in elt])
for lst in word_pos:
word_pos_len.append(len(lst))
for lst in word_neg:
word_neg_len.append(len(lst))
print(len_sent)
return texte, lemme_treetagger, len_sent, word_pos, word_neg, word_pos_len, word_neg_len
texte, lemme_treetagger, len_sent, word_pos, word_neg, word_pos_len, word_neg_len = extract_info(l_1, lexiconpos, lexiconneg)
def polarity_word(texte, *args):
texte, lemme_treetagger, len_sent, word_pos, word_neg, word_pos_len, word_neg_len = extract_info(texte, lexiconpos, lexiconneg)
for elt in lemme_treetagger:
print(elt)
sub_list = list(map(operator.sub, word_pos_len, word_neg_len))
score = list(map(truediv, sub_list, len_sent))
return score
</code></pre>
|
[] |
[
{
"body": "<h2>TSV parsing</h2>\n<p>You should not need to do this yourself. The <a href=\"https://docs.python.org/3.8/library/csv.html\" rel=\"nofollow noreferrer\">csv</a> module accepts a <a href=\"https://docs.python.org/3.8/library/csv.html#csv.Dialect.delimiter\" rel=\"nofollow noreferrer\">delimiter</a> that you can set to <code>'\\t'</code>.</p>\n<h2>Context management</h2>\n<p>You use <code>with</code> in one out of three file opens - the other two would benefit.</p>\n<h2>Inner list</h2>\n<p>This:</p>\n<pre><code>set([line.rstrip() for line in lexiconpos])\n</code></pre>\n<p>can be</p>\n<pre><code>{line.rstrip() for line in lexiconpos}\n</code></pre>\n<p>The set literal and removal of the inner list will both express this better.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T16:40:17.027",
"Id": "244516",
"ParentId": "244479",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T02:05:22.357",
"Id": "244479",
"Score": "3",
"Tags": [
"python"
],
"Title": "Computing the sentiment score of a sentence"
}
|
244479
|
<p>I have created a simple HealthCheck service. I have two approaches:</p>
<ol>
<li>Create a task canceling the previous one if the system is active, rescheduling the new task.</li>
<li>Create a periodic task and regularly check the last active time.</li>
</ol>
<p>Which one is better?</p>
<p>Recommendations on how to improve my usage of synchronized, volatile, AtomicBoolean keywords in both approaches above are welcome.</p>
<pre><code>public interface IHealthCheck {
void start();
void stop();
void onActive();
void onExpire();
}
</code></pre>
<pre><code>public class Main {
public static void main(String[] args) {
IHealthCheck check = new HealthCheck2();
new Thread(() -> checkTask(check, 5)).start();
new Thread(() -> checkTask(check, 6)).start();
new Thread(() -> checkTask(check, 7)).start();
sleep(100);
check.start();
}
private static void checkTask(IHealthCheck check, long sleep) {
for (int i = 0; i < 1000; i++) {
sleep(sleep);
check.onActive();
}
}
private static void sleep(long n) {
try {
Thread.sleep(n);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
</code></pre>
<pre><code>package com.deneme;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class HealthCheck implements IHealthCheck {
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private ScheduledFuture<?> future;
@Override
public void start() {
onActive();
}
@Override
public synchronized void stop() {
if (future != null) {
future.cancel(true);
}
}
@Override
public synchronized void onActive() {
if (future != null) {
future.cancel(true);
}
System.out.println("Active: " + System.currentTimeMillis());
future = scheduler.schedule(this::onExpire, 200, TimeUnit.MILLISECONDS);
}
@Override
public void onExpire() {
System.out.println("Expired: " + System.currentTimeMillis());
}
}
</code></pre>
<pre><code>package com.deneme;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class HealthCheck2 implements IHealthCheck {
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private ScheduledFuture<?> future;
private Instant lastActiveTime;
private boolean expired;
@Override
public void start() {
onActive();
future = scheduler.scheduleWithFixedDelay(this::check, 50, 50, TimeUnit.MILLISECONDS);
}
private synchronized void check() {
long diff = ChronoUnit.MILLIS.between(lastActiveTime, Instant.now());
if (diff > 100) {
onExpire();
}
}
@Override
public synchronized void stop() {
if (future != null) {
future.cancel(true);
}
}
@Override
public synchronized void onActive() {
expired = false;
lastActiveTime = Instant.now();
System.out.println("Active: " + lastActiveTime.toEpochMilli());
}
@Override
public void onExpire() {
if (!expired) {
expired = true;
System.out.println("Expired: " + System.currentTimeMillis());
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>It depends on your needs, but generally I would say that the second approach would be better.</p>\n<p>Why? because it allows you to run multiple tasks and that gives flexibility to your system. Now the use of <code>synchronized</code> may be troublesome if there are many threads running, if you don't need to handle <code>static</code> or shared resources/variables it would be better to not use it.</p>\n<p>Now, in the first place your classes has no <code>static</code> variables, and does not access to shared resources so synchronization is not needed. In the case of the class <code>HealthCheck2</code>, the following method will work fine without <code>synchronized</code></p>\n<pre class=\"lang-java prettyprint-override\"><code> private void check() {\n //the variable diff isn't needed either\n if (ChronoUnit.MILLIS.between(lastActiveTime, Instant.now()) > 100)\n onExpire();\n }\n</code></pre>\n<p>Why? Because the check method is uniquely owned by each <code>HealthCheck2</code> instance, even if they call the <code>start</code> method, the <code>scheduler</code> and the <code>future</code> variables are equally owned.</p>\n<p>I think you could remember when you were learning about static <em>variables</em> and <em>methods</em> that these are accessible and modifiable by any class instance. Well, the oposite is true, non-static variables and methods are unique for each instance.</p>\n<p>Hope it helped you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T03:23:16.653",
"Id": "480189",
"Score": "0",
"body": "\"the following method will work fine without synchronized\"... I'm accessing same healthcheck object from different threads. These threads are updating lastActive time variable. Without synchronization lastActive time may be falsely accessed by the schedulerexecutor thread."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T23:34:12.340",
"Id": "244538",
"ParentId": "244481",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T02:51:41.983",
"Id": "244481",
"Score": "3",
"Tags": [
"java",
"comparative-review",
"scheduled-tasks"
],
"Title": "Checking inactivity with periodic tasks in Java"
}
|
244481
|
<p>The <a href="https://github.com/javascript-utilities/decimal-to-base" rel="nofollow noreferrer">Source code</a> is maintained on GitHub and may be cloned via the following commands. A <a href="https://javascript-utilities.github.io/decimal-to-base/index.html" rel="nofollow noreferrer">Live demo</a> is hosted online, thanks to GitHub Pages.</p>
<pre class="lang-bash prettyprint-override"><code>mkdir -vp ~/git/hub/javascript-utilities
cd ~/git/hub/javascript-utilities
git clone git@github.com:javascript-utilities/decimal-to-base.git
</code></pre>
<p>The build target is ECMAScript version 6, and so far both manual tests and automated JestJS tests show that the <code>decimalToBase</code> function functions as intended, both for Browser and NodeJS environments.</p>
<p>I am aware of <code>(number).toString(radix)</code> for converting numbers to another base. However, the built-in <code>Number.toString()</code> method doesn't seem to have options for prefixing Binary, Octal, or Heximal bases; among other features that I'm implementing.</p>
<p><strong>Example Usage</strong></p>
<pre><code>decimalToBase(540, 16);
//> "0x21C"
</code></pre>
<p>I am mostly concerned with improving the <a href="https://github.com/javascript-utilities/decimal-to-base/blob/main/decimal-to-base.js" rel="nofollow noreferrer">JavaScript</a>, and <a href="https://github.com/javascript-utilities/decimal-to-base/blob/main/ts/decimal-to-base.ts" rel="nofollow noreferrer">TypeScript</a>. The HTML and CSS are intended to be simple and functional.</p>
<p>Pleas post any suggestion to the JavaScript. Additionally if anyone has a clean way of handling floating point numbers that'd be super, because at this time the current implementation only handles integers.</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";
/**
* Converts decimal to another base, eg. hex, octal, or binary
* @function decimalToBase
* @param {number|string} decimal
* @param {number|string} radix - default `16`
* @param {boolean} verbose - default `false`
* @param {string[]} symbols_list - default `[...'0123456789abcdefghijklmnopqrstuvwxyz']`
* @returns {string}
* @throws {SyntaxError|RangeError}
* @author S0AndS0
* @license AGPL-3.0
* @see {link} - https://www.tutorialspoint.com/how-to-convert-decimal-to-hexadecimal
* @see {link} - https://www.ecma-international.org/ecma-262/6.0/#sec-literals-numeric-literals
* @example
* decimalToBase(540, 16);
* //> "0x21C"
*/
const decimalToBase = (decimal, radix = 16, verbose = false, symbols_list = [...'0123456789abcdefghijklmnopqrstuvwxyz']) => {
decimal = Math.floor(Number(decimal));
radix = Number(radix);
const max_base = symbols_list.length;
if (isNaN(decimal)) {
throw new SyntaxError('First argument is Not a Number');
}
else if (isNaN(radix)) {
throw new SyntaxError('radix is Not a Number');
}
else if (radix > max_base) {
throw new RangeError(`radix must be less than or equal to max base -> ${max_base}`);
}
else if (radix < 2) {
throw new RangeError(`radix must be greater than 2`);
}
let prefix = '';
switch (radix) {
case 16: // Hexadecimal
prefix = '0x';
break;
case 8: // Octal
prefix = '0o';
break;
case 2: // Binary
prefix = '0b';
break;
}
if (radix >= 10 && decimal < 10) {
return `${prefix}${symbols_list[decimal]}`;
}
let converted = '';
let dividend = decimal;
while (dividend > 0) {
const remainder = dividend % radix;
const quotient = (dividend - remainder) / radix;
/* istanbul ignore next */
if (verbose) {
console.log(`dividend -> ${dividend}`, `remainder -> ${remainder}`, `quotient -> ${quotient}`);
}
converted = `${symbols_list[remainder]}${converted}`;
dividend = quotient;
}
return `${prefix}${converted.toUpperCase()}`;
};
/* istanbul ignore next */
if (typeof module !== 'undefined') {
module.exports = decimalToBase;
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>*, *::before, *::after {
box-sizing: border-box;
}
.container {
max-width: 50%;
position: relative;
}
.row {
padding-top: 1rem;
}
.row::after {
content: '';
position: absolute;
left: 0;
background-color: lightgrey;
height: 0.2rem;
width: 100%;
}
.label {
font-weight: bold;
font-size: 1.2rem;
width: 19%;
padding-right: 1%;
}
.text_input {
float: right;
width: 79%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Tests Decimal to Base</title>
<!-- <link rel="stylesheet" href="assets/css/main.css"> -->
<!-- <script type="text/javascript" src="assets/js/modules/decimal-to-base/decimal-to-base.js"></script> -->
<script type="text/javascript">
function updateOutput(_event) {
const decimal = document.getElementById('decimal').value;
const radix = document.getElementById('radix').value;
const output_element = document.getElementById('output');
let output_value = 'NaN';
try {
output_value = decimalToBase(decimal, radix)
} catch (e) {
if (e instanceof SyntaxError) {
console.error(e);
} else if (e instanceof RangeError) {
console.error(e);
} else {
throw e;
}
}
output_element.value = output_value;
}
window.addEventListener('load', (_event) => {
document.getElementById('decimal').addEventListener('input', updateOutput);
document.getElementById('radix').addEventListener('input', updateOutput);
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<span class="label">Radix: </span>
<input type="text" class="text_input" id="radix" value="16">
</div>
<br>
<div class="row">
<span class="label">Input: </span>
<input type="text" class="text_input" id="decimal">
</div>
<br>
<div class="row">
<span class="label">Output: </span>
<input type="text" class="text_input" id="output" readonly>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<hr />
<p>For completeness here are the <a href="https://github.com/javascript-utilities/decimal-to-base/blob/main/__tests__/tests-decimal-to-base.js" rel="nofollow noreferrer">JestJS</a> tests.</p>
<pre class="lang-javascript prettyprint-override"><code>"use strict";
/**
* @author S0AndS0
* @copyright AGPL-3.0
* @example <caption>Jest Tests for decimalToBase</caption>
* // Initialize new class instance and run tests
* const test_decimalToBase = new decimalToBase_Test();
* test_decimalToBase.runTests();
*/
class decimalToBase_Test {
constructor() {
this.decimalToBase = require('../decimal-to-base.js');
this.decimal_limits = { min: 1, max: 16 };
this.base_configs = [
{
base: 2,
name: 'Binary'
},
{
base: 3,
name: 'Trinary'
},
{
base: 4,
name: 'Quaternary'
},
{
base: 5,
name: 'Quinary AKA Pental'
},
{
base: 6,
name: 'Senary AKA Heximal or Seximal'
},
{
base: 7,
name: 'Septenary'
},
{
base: 8,
name: 'Octal'
},
{
base: 9,
name: 'Nonary'
},
{
base: 10,
name: 'Decimal AKA Denary'
},
{
base: 11,
name: 'Undecimal'
},
{
base: 12,
name: 'Duodecimal AKA Dozenal or Uncial'
},
{
base: 13,
name: 'Tridecimal'
},
{
base: 14,
name: 'Tetradecimal'
},
{
base: 15,
name: 'Pentadecimal'
},
{
base: 16,
name: 'Hexadecimal'
}
];
}
/**
* Runs all tests for this module
*/
runTests() {
this.testsErrors();
this.testsConversion();
}
/**
* Uses `(Number).toString()` to check conversions, note this will only work for radix between `2` though `36`, and default `symbols_list`
*/
static doubleChecker(decimal, radix) {
decimal = Number(decimal);
radix = Number(radix);
let prefix = '';
switch (radix) {
case 2:
prefix = '0b';
break;
case 8:
prefix = '0o';
break;
case 16:
prefix = '0x';
break;
}
return `${prefix}${(decimal).toString(radix).toUpperCase()}`;
}
/**
* Tests available error states
*/
testsErrors() {
test('Is a `SyntaxError` thrown, when `decimal` parameter is not a number?', () => {
expect(() => {
this.decimalToBase('spam!', 10);
}).toThrow(SyntaxError);
});
test('Is a `SyntaxError` thrown, when `radix` parameter is not a number?', () => {
expect(() => {
this.decimalToBase(42, 'ham');
}).toThrow(SyntaxError);
});
test('Is a `RangeError` thrown, when `symbols_list` is not long enough?', () => {
expect(() => {
this.decimalToBase(42, 37);
}).toThrow(RangeError);
});
test('Is a `RangeError` thrown, when `radix` parameter is less than `2`?', () => {
expect(() => {
this.decimalToBase(42, 1);
}).toThrow(RangeError);
});
}
/**
* Loops through `this.base_configs` and tests decimal integers between `this.decimal_limits['min']` and `this.decimal_limits['max']`
*/
testsConversion() {
const min = this.decimal_limits['min'];
const max = this.decimal_limits['max'];
this.base_configs.forEach((config) => {
const { base } = config;
const { name } = config;
for (let decimal = min; decimal <= max; decimal++) {
const expected_value = this.constructor.doubleChecker(decimal, base);
test(`Base ${base}, does ${decimal} equal "${expected_value}" in ${name}?`, () => {
expect(this.decimalToBase(decimal, base)).toEqual(expected_value);
});
}
});
}
}
const test_decimalToBase = new decimalToBase_Test();
test_decimalToBase.runTests();
</code></pre>
<hr />
<h2>Questions</h2>
<ul>
<li>Are there any mistakes?</li>
<li>Have I missed any test cases?</li>
<li>Any suggestions on expanding this implementation to handle floating point numbers?</li>
<li>Any suggestions on making the code more readable?</li>
<li>Are there any additional features that are wanted?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T11:06:32.840",
"Id": "479974",
"Score": "0",
"body": "Deleting the radix 16 in the test code field generates an error and thereafter entering any radix number gives an error. Maybe it is the field entry code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T15:47:23.017",
"Id": "480011",
"Score": "0",
"body": "Thanks for the heads-up @MohsenAlyafei. By design the `decimalToBase` function will throw a `SyntaxError` or `RangeError`, which _should_ be caught by in-lined JavaScript within the HTML. But for some reason CodeReview has their own _catcher_ which is adding an overlaid element, so it seems to be necessary to use the _\"Expand snippit\"_ so that errors do not hide elements used for input/output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T20:17:53.560",
"Id": "480528",
"Score": "1",
"body": "``radix must be less than max base -> ${max_base}``. If `max-base = 16` then this says \"radix cannot be 16.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T20:24:39.590",
"Id": "480529",
"Score": "1",
"body": "Not sure... do non-integer `decimal` parameter values get caught?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T00:40:16.423",
"Id": "480545",
"Score": "0",
"body": "@radarbob Thanks for pointing out these bugs! I've corrected'em both on GitHub and here, as well as added ya to the list of attribution links."
}
] |
[
{
"body": "<p>From the array variable:<code>symbols_list = [...'0123456789abcdefghijklmnopqrstuvwxyz']</code>, I would assume that the function would permit the use of alternative symbols for representing numbers in formats above the decimal format. I have not come across such formats, like Hexadecimal numbers being represented by letters other than the English (Latin) letters A to F.</p>\n<p>However, if you stick with the English letters A to Z, then I would suggest that you could simplify the process by using the built-in (number).toString(radix) (which you are already aware of) and then just add the needed prefix (which is only required for outputs in Binary, Octal, and Hex numbers).</p>\n<p>I would do this by making use of the built-in function as follows:</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 decimalToBase = (decimal, radix = 16) => {\n let converted = (decimal).toString(radix);\n let prefix = '';\n switch (radix) {\n case 16:\n prefix = '0x';\n break;\n case 8:\n prefix = '0o';\n break;\n case 2:\n prefix = '0b';\n }\n return prefix + converted.toUpperCase();\n}\n\nconsole.log(decimalToBase(540)); // 0x21C (default radix)\nconsole.log(decimalToBase(123, 2)); // 0b1111011\nconsole.log(decimalToBase(123, 8)); // 0o173\nconsole.log(decimalToBase(123, 10)); // 123\nconsole.log(decimalToBase(123, 32)); // 3R\nconsole.log(decimalToBase(123, 36)); // 3F</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T00:40:28.160",
"Id": "480546",
"Score": "0",
"body": "Thanks for the feedback! The `doubleChecker` method within the `decimalToBase_Test` class does mostly this, and the `symbols_list` parameter is there for those that want to experiment with bases larger than 36; which is the upper limit for `toString()` method on Numbers."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T19:40:38.680",
"Id": "244747",
"ParentId": "244488",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T05:55:02.843",
"Id": "244488",
"Score": "2",
"Tags": [
"javascript",
"functional-programming",
"reinventing-the-wheel",
"converting",
"number-systems"
],
"Title": "JavaScript -- Convert decimal to another base"
}
|
244488
|
<p>I recently wrote a mathematical expression parser in C++. The software can read valid mathematical expressions and evaluate them. An example of an expression the code can parse is <code>(sin(pi)*e^(-3))</code>. I would love to receive constructive feedback if possible for the code. Such as compiler optimizations, memory optimization and algorithms improvements.</p>
<p>The important methods are:</p>
<ol>
<li><code>tokenize</code></li>
<li><code>pre_process_trig_and_constants</code></li>
<li><code>evaluate</code></li>
<li><code>eval_with_braces</code></li>
</ol>
<p>The important structs are:</p>
<ol>
<li><code>toks_and_ops</code></li>
<li><code>expr_stack</code></li>
</ol>
<p><code>tokenize</code></p>
<pre><code>toks_and_ops parser::tokenize(string expr){
/**
* This method tokenizes a string (without braces) into numbers and operands. The string must be a valid mathematical expression
* It is recommended to be called from evaluate() method since there is no support for braces.
* For evaluation of expressions with braces check out struct expr_stack.
*
*/
const int len= expr.size();
string tok ="";
char current_char;
// struct toks_and_ops is used here and the following vector<> members are for the struct feilds.
vector<double> toks;
vector<char> ops ;
int current_index=0;
while(current_index<len){
current_char=expr.at(current_index);
/**
* check if the character is a number a.k.a between values 57 and 48 in ASCII
*'.' is 46 in ASCII and - is 45
*This method is faster than cross referencing character with every other numbers
*/
if((current_char<58 && current_char>44) && current_char != 47){
if(current_char == MINUS){
if(expr.at(current_index -1) > 47 && expr.at(current_index -1) <58){
/**
* Pure subtraction is considered as addition of a negative value.
* if the character before the minus sign is a number its a pure subtraction
* if the character before is an operation it is a normal operation
* It is guaranteed that there will be always one character before minus sign
* evaluate() method will append '0' before an expression if the first character is '-'
* Furthermore evaluate() will only work with expressions without braces so an error is not possible
*/
ops.push_back(PLUS);
toks.push_back(get_num(tok));
tok="";
}
}
tok +=current_char;
}else{
/**
* If the character is not a number , '.' or '-'
*/
toks.push_back( get_num(tok));
ops.push_back(current_char);
tok="";
}
current_index++;
}
toks.push_back(get_num(tok));
toks_and_ops res ={toks,ops};
return res;
}
</code></pre>
<p><code>pre_process_trig_and_constants</code></p>
<pre><code>string parser::pre_process_trig_and_constants(string source){
source =replace_expr(source,"sin","s");
source =replace_expr(source,"cos", "c");
source =replace_expr(source,"tan", "t");
source =replace_expr(source,"e", to_string(exp(1)));
source =replace_expr(source,"pi", to_string(M_PI));
return source;
}
</code></pre>
<p><code>evaluate</code><br />
<strong>WARNING</strong>: This is long.</p>
<pre><code>double parser::evaluate(string expr){
/**
* Central method for evaluation.
* This method is not directly called by the user
* This method serves as a helper for the structure expr_stack to evaluate expressions with braces
* This method can be called if required to evaluate simple expressions i.ewithout any braces.
*/
if(expr.empty()){
return 1;
}if(expr.at(0) == MINUS){
/**
* preventing an error for tokenize() method
*/
expr ="0" +expr;
}if(expr.size() ==1 ){
return get_num(expr);
}
toks_and_ops r =tokenize(expr);
int ops_index=0;
/**
* The operations use BEDMAS
* In this context we exclude braces since this method does not evaluate expression with brace
* Power takes precedence then * ->/ -> +
* Indirectly expressions inside brackets are evaluated first by the expression_stack
*/
for(auto i = r.ops.begin(); i< r.ops.end();){
if(*i == POWER){
r.toks[ops_index] = pow(r.toks[ops_index] , r.toks[ops_index+1]);
remov(ops_index+1, r.toks);
remov(ops_index, r.ops);
}else{
i++;
ops_index++;
}
}
if(r.toks.size() ==1){
return r.toks[0];
}
ops_index=0;
for(auto i = r.ops.begin(); i< r.ops.end();){
if(*i == MULTI){
r.toks[ops_index] =r.toks[ops_index+1] * r.toks[ops_index];
remov(ops_index+1, r.toks);
remov(ops_index, r.ops);
}else{
i++;
ops_index++;
}
}
if(r.toks.size() ==1){
return r.toks[0];
}
ops_index=0;
for(auto i = r.ops.begin(); i< r.ops.end();){
if(*i == DIV){
r.toks[ops_index] = r.toks[ops_index] / r.toks[ops_index+1];
remov(ops_index+1, r.toks);
remov(ops_index, r.ops);
}else{
i++;
ops_index++;
}
}
if(r.toks.size() ==1){
return r.toks[0];
}
ops_index=0;
for(auto i = r.ops.begin(); i< r.ops.end();){
if(*i == PLUS){
r.toks[ops_index] = r.toks[ops_index+1] + r.toks[ops_index];
remov(ops_index+1, r.toks);
remov(ops_index, r.ops);
}else{
i++;
ops_index++;
}
}
return r.toks[0];
};
</code></pre>
<p><code>eval_with_braces</code></p>
<pre><code>double parser::eval_with_braces(string expr){
/**
* evaluates expressions with braces
* see expr_stack structure for more information on evaluation of expressions with braces
*/
expr_stack eval;
expr_stack trig_eval;
int ind=0;
int trig_ind;
string temp="";
string sec_temp="";
expr.erase( remove(expr.begin(),expr.end(), ' '), expr.end());
expr = pre_process_trig_and_constants(expr);
expr =expr+"+0";
for(auto i =expr.begin();i<expr.end();){
if((*i!=SIN && *i !=COS) && *i != TAN){
eval.push(*i);
i++;
ind++;
}else{
trig_ind =ind+1;
//isolates the immediate valid expression after trig indicator i.e sin, cos or tan
while(!trig_eval.expr_done){
trig_eval.push(expr.at(trig_ind));
trig_ind++;
}
if(*i== SIN){
temp= to_string(round_val(sin(evaluate(trig_eval.expr))));
}else if(*i== COS){
temp= to_string(round_val(cos(evaluate(trig_eval.expr))));
}else{
temp= to_string(round_val(tan(evaluate(trig_eval.expr))));
}
sec_temp =expr.substr(0,ind) ;
sec_temp+= temp;
sec_temp+=expr.substr(ind+ trig_eval.push_count +1);
expr=sec_temp;
sec_temp="";
temp="";
trig_eval.recycle();
trig_ind=0;
}
}
return evaluate(eval.expr);
};
</code></pre>
<p><code>toks_and_ops</code></p>
<pre><code> struct toks_and_ops{
/**
* compound data type for conveninece
*/
vector<double> toks;
vector<char> ops;
};
</code></pre>
<p><code>expr_stack</code></p>
<pre><code>struct expr_stack{
/**
* member fields
* */
bool expr_done =false;
int ind=0;
int prev= -1;
int push_count=0;
vector<int> prev_l_bracs;
string expr="";
string ref;
/**
* for re-initializing this stack
*/
void recycle(){
/**
* sets all members fields to initial value
*/
expr_done =false;
ind=0;
prev= -1;
push_count=0;
prev_l_bracs.clear();
expr="";
ref="";
}
/**
* method for the stack
* */
void push(char i){
/**
* The algorithm for push() dynamically checks for complete braces ( complete braces are a pair of adjacent ( and ) )
* If more left braces are found the current starting index of a brace to be completed is updated as the index of most recent left brace
* While there is a left brace and a right brace is found , it denotes a valid brace expression and the contents inside it is evaluated as
* a mathematical expression by calling evaluate()
* After this the current starting index for a brace to be completed is updates as the most recent one before the previousleft brace
* The previous valid brace expression is replaced by the result of the evaluation
*
* Once a full valid brace expression is completely pushed inside this stack there will not be any braces left and
* evaluate() method can be called to evaluate it.
*
* expr_stack acts like a pre-processor for expressions
*/
push_count++;
if(i == LBRAC){
prev_l_bracs.push_back(ind);
prev= ind;
expr+= i;
ind++;
}else if(i == RBRAC && prev>=0){
ref=expr.substr(prev +1 , ind -prev );
ref=to_string(evaluate(ref));
expr = expr.substr(0, prev)+ ref;
ind =prev+ ref.size();
remov(prev_l_bracs.size() -1 ,prev_l_bracs);
if(!prev_l_bracs.empty()){
prev = (prev_l_bracs.at(prev_l_bracs.size()-1));
}else{
prev =-1;
expr_done = true;
}
}else{
expr+= i;
ind++;
}
};
};
</code></pre>
<p>Please ask or comment if any clarification is needed, or if anything is ambiguous :)</p>
|
[] |
[
{
"body": "<h2>Constant parameters</h2>\n<pre><code>parser::tokenize(string expr){\n</code></pre>\n<p>would be better off as</p>\n<pre><code>parser::tokenize(const string &expr) {\n</code></pre>\n<p>Similarly for <code>pre_process_trig_and_constants</code>, which should use an intermediate variable for the reassignment statements in that function.</p>\n<h2>Encapsulation</h2>\n<pre><code>toks_and_ops res ={toks,ops};\n</code></pre>\n<p>Rather than structures that don't know how to initialize themselves - such as this <code>toks_and_ops</code> - I would sooner see a constructor for this <code>toks_and_ops</code> as class that accepts a <code>const string &expr</code> and does most of what <code>tokenize</code> is doing now.</p>\n<h2>ASCII symbols</h2>\n<pre><code>if((current_char<58 && current_char>44) && current_char != 47){\n</code></pre>\n<p>is very difficult to understand and maintain. Given that you say you're already assuming ASCII, as long as your compiler is <a href=\"https://stackoverflow.com/questions/6794590/how-does-file-encoding-affect-c11-string-literals\">configured to also apply ASCII to literals</a>, you should just be using character literals like <code>'.'</code> .</p>\n<h2>For-loop</h2>\n<pre><code>int current_index=0;\n\nwhile(current_index<len){\n // ...\n\n current_index++;\n}\n</code></pre>\n<p>should just be</p>\n<pre><code>for (int current_index = 0; current_index < len; current_index++) {\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T16:29:36.953",
"Id": "244515",
"ParentId": "244489",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T07:00:15.443",
"Id": "244489",
"Score": "4",
"Tags": [
"c++",
"performance",
"algorithm",
"parsing",
"calculator"
],
"Title": "A mathematical expression parser with custom data structures"
}
|
244489
|
<p>I'm looking for advice on how to improve this program and use Pandas more effectively.</p>
<p>I have a data set of orders from a market. Each order has four properties:</p>
<ol>
<li>A <code>type_id</code> representing the good</li>
<li>Whether the order is either a buy or sell order</li>
<li>The price of the order</li>
<li>The order's volume.</li>
</ol>
<p>I process the market data to create a new DataFrame containing every <code>type_id</code> and how much it costs to buy or sell n% of the volume on the market.</p>
<pre><code>import pandas as pd
type_ids = {
0: 'Item A',
1: 'Item B',
}
market_order_list = [
{'type_id': 0, 'is_buy_order': False, 'price': 80, 'volume': 22},
{'type_id': 0, 'is_buy_order': False, 'price': 70, 'volume': 12},
{'type_id': 0, 'is_buy_order': False, 'price': 60, 'volume': 9},
{'type_id': 0, 'is_buy_order': True, 'price': 50, 'volume': 3},
{'type_id': 0, 'is_buy_order': True, 'price': 40, 'volume': 9},
{'type_id': 0, 'is_buy_order': True, 'price': 30, 'volume': 33},
{'type_id': 1, 'is_buy_order': False, 'price': 30, 'volume': 28},
{'type_id': 1, 'is_buy_order': False, 'price': 25, 'volume': 11},
{'type_id': 1, 'is_buy_order': False, 'price': 20, 'volume': 7},
{'type_id': 1, 'is_buy_order': True, 'price': 15, 'volume': 8},
{'type_id': 1, 'is_buy_order': True, 'price': 10, 'volume': 12},
{'type_id': 1, 'is_buy_order': True, 'price': 5, 'volume': 24}
]
def inner_func(df, tracking):
if tracking['volume_processed'] == tracking['total_volume_to_process']:
# We already filled our total volume, no more processing needed
return
# We need to process this much more volume
needed_volume = tracking['total_volume_to_process'] - tracking['volume_processed']
if df['volume'] >= needed_volume:
# This order can fully fill us
tracking['volume_processed'] += needed_volume
tracking['total_price_paid'] += needed_volume * df['price']
else:
# This order can only partially fill us
tracking['volume_processed'] += df['volume']
tracking['total_price_paid'] += df['volume'] * df['price']
def outer_func(df_orig, result_list, percent):
# Determine if this is a list of buy or sell orders and get the type
is_buy = df_orig['is_buy_order'][0]
type_id = df_orig['type_id'][0]
# Sort price in correct direction for buy/sell, and calculate how much volume is needed
df = df_orig.sort_values('price', ascending=not is_buy, inplace=False).reset_index(drop=True)
total_volume_to_process = int(df['volume'].sum() * percent)
# Make tracking dictionary which will capture results of this set of orders
tracking = {
'type_id': type_id,
'is_buy': is_buy,
'volume_processed': 0,
'total_volume_to_process': total_volume_to_process,
'total_price_paid': 0,
}
# Each inner_func call will be just the buy side, or just the sell side, for a single type_id
df.apply(func=inner_func, axis=1, args=(tracking,))
# Append the results to our list
result_list.append(tracking)
result_list = []
# Load the dataframe
df = pd.DataFrame(market_order_list)
g = df.groupby(['type_id', 'is_buy_order']).apply(outer_func, result_list=result_list, percent=0.33)
# Load the result_list into a dataframe and display
result_frame = pd.DataFrame(result_list)
print('=== Result === ')
print(result_frame)
print('\nWhat is the cost of buying 33% of the volume for type_id = 0?')
total_price_paid = result_frame[(result_frame.type_id == 0) & (result_frame.is_buy == True)]['total_price_paid'].item()
print(total_price_paid)
</code></pre>
<p>This is the output:</p>
<pre><code>=== Result ===
type_id is_buy volume_processed total_volume_to_process total_price_paid
0 0 False 14 14 890
1 0 True 14 14 570
2 1 False 15 15 340
3 1 True 14 14 180
What is the cost of buying 33% of the volume for type_id = 0?
570
</code></pre>
<p>Do you have any advice on how I did and how I can improve the code?
Is there a proper way to do this operation?</p>
|
[] |
[
{
"body": "<p>I think you can do two things. First, you should be able to directly use the output of applying the outer function. No need for this <code>output_list</code> business. Next thing, you should vectorize your inner function. You actually don't need it at all, you can just use <code>numpy.searchsorted</code> to find how many rows you need.</p>\n<pre><code>import numpy as np\nimport pandas as pd\n\ndef track(group, percent):\n assert 0 <= percent <= 1\n type_id = group["type_id"][0]\n is_buy = group["is_buy_order"][0]\n total_volume_to_process = int(group["volume"].sum() * percent)\n\n # find the position where the total volume is satisfied\n group = group.sort_values("price", ascending=not is_buy)\n cumulative_volume = group["volume"].cumsum()\n n = np.searchsorted(cumulative_volume, total_volume_to_process)\n\n # get only those rows which are needed\n # copy is needed because we will potentially modify it\n processed = group.head(n + 1).copy()\n\n if 0 <= n < len(group):\n # fix the last volume so that the sum is satisfied\n last_volume = total_volume_to_process - cumulative_volume.iloc[n-1]\n processed.iloc[-1, processed.columns.get_loc("volume")] = last_volume\n else:\n # np.searchsorted returns 0 or N in case no match is found\n # 0 is fine, we just take a part of the first volume,\n # but N means there is not enough volume available.\n raise RuntimeError("Could not satisfy order")\n\n # return results\n total_price = (processed["volume"] * processed["price"]).sum()\n return pd.Series({"volume_processed": processed["volume"].sum(),\n "total_volume_to_process": total_volume_to_process,\n "total_price_paid": total_price})\n</code></pre>\n\n<pre><code>if __name__ == "__main__":\n df = ...\n percent = 0.33\n print(df.groupby(["type_id", "is_buy_order"], as_index=False)\n .apply(track, percent)\n .reset_index()\n .rename(columns={"is_buy_order": "is_buy"}))\n\n# type_id is_buy volume_processed total_volume_to_process total_price_paid\n# 0 0 False 14 14 890\n# 1 0 True 14 14 570\n# 2 1 False 15 15 340\n# 3 1 True 14 14 180\n</code></pre>\n<p>Your question prompt can also be faster if you don't reset the index in the above call. Then it becomes just <code>result.loc[(0, True), "total_price_paid"]</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T09:48:28.667",
"Id": "244493",
"ParentId": "244490",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T08:01:48.953",
"Id": "244490",
"Score": "4",
"Tags": [
"python",
"pandas"
],
"Title": "Processing orders of goods from a market"
}
|
244490
|
<p>I am creating a NAME column in a DataFrame and set its value based on substrings contained in another column.</p>
<p>Is there a more efficient way to do this?</p>
<pre><code>import pandas as pd
df = pd.DataFrame([['www.pandas.org','low'], ['www.python.org','high']],
columns=['URL','speed'])
print(df.head())
df['Name'] = df['URL']
print(df.head())
#set Name based on substring in URL
df.loc[df['Name'].str.contains("pandas", na=False), 'Name'] = "PANDAS"
df.loc[df['Name'].str.contains("python|pitone", na=False), 'Name'] = "PYTHON"
print(df.head())
</code></pre>
|
[] |
[
{
"body": "<p>Yes. Try to automate converting a URL to a name, instead of hardcoding the mapping. With only two URLs, your approach is doable, but as soon as you have to handle lots of different URLs, it will quickly become very painful.</p>\n<p>Also, avoid first copying a column and then replacing every item in it. Rather, construct the column with the right contents directly. Here is an example:</p>\n<pre><code>df['Name'] = [url.split('.')[-2].upper() for url in df['URL']]\n</code></pre>\n<p>This will fail for proper URLs like <code>https://www.pandas.org/index.html</code>. If you want to handle that automatically, you'll have to properly parse them, for example using <a href=\"https://docs.python.org/3/library/urllib.parse.html\" rel=\"nofollow noreferrer\"><code>urllib.parse</code></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T06:50:15.367",
"Id": "480088",
"Score": "0",
"body": "You should probably use `df['URL'].str.split('.').str[-2].str.upper()` instead of a list comprehension for some more speed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T16:05:23.733",
"Id": "244511",
"ParentId": "244491",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244511",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T09:13:31.053",
"Id": "244491",
"Score": "3",
"Tags": [
"python",
"pandas"
],
"Title": "Creating names from URLs"
}
|
244491
|
<p>This class validates that a name contains only letters and optionally spaces, hyphens and apostrophes.</p>
<pre><code>public class NameAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null) return ValidationResult.Success;
string name = value.ToString();
var regex = new Regex(@"^[a-zA-Z]+(?:['-][a-zA-Z\s*]+)*$");
return regex.IsMatch(name)
? ValidationResult.Success
: new ValidationResult($"The name '{name}' is invalid, it should consist of only letters, and optionally spaces, apostrophes and/or hyphens.");
}
}
</code></pre>
<p>One thing I wasn't sure on was the null check at the start, we've got the <code>Required</code> attribute if something is required and I don't want the validation to occur if the value is null. Is this an appropriate way of handling it?</p>
|
[] |
[
{
"body": "<p>From the separation of concerns perspective it seems fine that you do not want to validate against emptiness. On the other hand, one can argue that why do you treat an empty string as a valid name.</p>\n<p>My suggestion is to create a ctor with a parameter, where the consumer of the attribute can define how should it behave in case of empty input.</p>\n<pre><code>public class NameAttribute : ValidationAttribute\n{\n private static readonly Regex NameRegex = new Regex(@"^[a-zA-Z]+(?:['-][a-zA-Z\\s*]+)*$", RegexOptions.Compiled);\n private readonly bool shouldTreatEmptyAsInvalid;\n public NameAttribute(bool shouldTreatEmptyAsInvalid = true)\n {\n this.shouldTreatEmptyAsInvalid = shouldTreatEmptyAsInvalid;\n }\n\n protected override ValidationResult IsValid(object value, ValidationContext validationContext)\n {\n if (value == null)\n return shouldTreatEmptyAsInvalid \n ? new ValidationResult($"The name is invalid, it should not be empty.") \n : ValidationResult.Success;\n\n return NameRegex.IsMatch(value.ToString())\n ? ValidationResult.Success\n : new ValidationResult($"The name '{value}' is invalid, it should consist of only letters, and optionally spaces, apostrophes and/or hyphens.");\n }\n}\n</code></pre>\n<p>I moved the creation of the Regex to a static variable, but you should take some measurements in order to be sure, which has the best performance. Please check <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/base-types/best-practices\" rel=\"nofollow noreferrer\">this MSDN article</a> for other alternatives.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T12:25:54.507",
"Id": "479983",
"Score": "0",
"body": "Thanks, so with that in mind, it would negate the need for a Required attribute, is that right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T12:28:30.030",
"Id": "479984",
"Score": "0",
"body": "@MF1010 With this version you are able to use this with / without the `Required` attribute. So your logic does not depend on the existence of an other attribute."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T07:43:52.320",
"Id": "480396",
"Score": "1",
"body": "Thanks, that makes sense."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T11:51:02.987",
"Id": "244498",
"ParentId": "244494",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244498",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T11:10:17.420",
"Id": "244494",
"Score": "1",
"Tags": [
"c#",
"regex",
"asp.net",
"asp.net-core"
],
"Title": "Validating a name with C#, ASP.NET Core 3.1 and Regex"
}
|
244494
|
<p>I am starting with Java and at the beginning I would like someone to catch what mistakes I make. I would like my code to look its best and I want to learn good Java writing habits. Could anyone explain to me where I am making mistakes or what I should do differently for this purpose?</p>
<p>My program presents a music playlist. To add song to a playlist, we must first add the song to the album. All 3 classes are in separate files in my program. I set up getters and setters only when I use them - I don't know if it's a good habit. calledNext flag checks whether iterator.next() was called in the previous run.</p>
<pre><code>public class Main {
private static LinkedList<Song> playlist = new LinkedList<>();
private static LinkedList<Album> albums = new LinkedList<>();
public static void main(String[] args) {
Album a1 = new Album();
a1.addToAlbum("song1", 1.57);
a1.addToAlbum("song2", 2.00);
albums.add(a1);
albums.get(0).addToPlaylist(playlist, "song1");
albums.get(0).addToPlaylist(playlist, "song2");
System.out.println();
runPlaylist();
}
public static void runPlaylist() {
ListIterator<Song> iterator = playlist.listIterator();
Scanner scanner = new Scanner(System.in);
boolean quit = false;
boolean calledNext = true;
System.out.println("Now playing " + iterator.next().toString());
printMenu();
while (!quit) {
if (playlist.isEmpty()) {
System.out.println("Playlist is empty");
break;
}
System.out.println("Enter your choice ");
int x = scanner.nextInt();
scanner.nextLine();
switch (x) {
case 1:
quit = true;
System.out.println("bye bye");
break;
case 2:
if (!calledNext)
if (iterator.hasNext())
iterator.next();
calledNext = true;
if (iterator.hasNext())
System.out.println("Now playing: " + iterator.next().toString());
else
System.out.println("No more songs in the playlist");
break;
case 3:
if (calledNext)
if (iterator.hasPrevious())
iterator.previous();
calledNext = false;
if (iterator.hasPrevious())
System.out.println("Now playing: " + iterator.previous().toString());
else
System.out.println("You are at the beginning");
break;
case 4:
if (calledNext) {
if (iterator.hasPrevious())
System.out.println("Replaying: " + iterator.previous().toString());
else
System.out.println("Replaying: " + playlist.getFirst().toString());
calledNext = false;
} else {
if (iterator.hasNext())
System.out.println("Replaying: " + iterator.next().toString());
else
System.out.println("Replaying: " + playlist.getLast().toString());
calledNext = true;
}
break;
case 5:
printMenu();
break;
case 6:
String titleToAdd = scanner.nextLine();
for (int i = 0; i < albums.size(); i++) {
Album currentAlbum = albums.get(i);
if (!currentAlbum.addToPlaylist(playlist, titleToAdd))
System.out.println("Song not found in album");
}
break;
case 7:
String titleToRemove = scanner.nextLine();
for (int i = 0; i < albums.size(); i++) {
Album currentAlbum = albums.get(i);
if (!currentAlbum.removeFromPlaylist(playlist, titleToRemove))
System.out.println("Song not found in playlist");
}
if (!playlist.isEmpty())
System.out.println("Now playing: " + playlist.getFirst().toString());
break;
case 8:
System.out.println(playlist);
break;
default:
System.out.println("Invalid input");
break;
}
}
}
public static void printMenu() {
System.out.println("Instructions : \nPress" +
" 1 to exit\n" +
"2 to play next song\n" +
"3 to play previous song\n" +
"4 replay\n" +
"5 print menu \n" +
"6 add song to playlist\n" +
"7 remove song from playlist\n" +
"8 print playlist\n");
}
public class Album {
private ArrayList<Song> songs;
public Album() {
this.songs = new ArrayList<>();
}
public void addToAlbum(String title, double duration) {
if (checkAlbum(title) == null) {
songs.add(new Song(title, duration));
} else {
System.out.println("Song already in album");
}
}
public void removeFromAlbum(String title) {
Iterator<Song> iterator = songs.iterator();
if (checkAlbum(title) != null) {
while (iterator.hasNext()) {
if (iterator.next().getTitle().equals(title)) {
iterator.remove();
}
}
}
}
public boolean addToPlaylist(LinkedList<Song> playlist, String title) {
Song checkedSong = checkAlbum(title);
if (checkedSong != null) {
playlist.add(checkedSong);
System.out.println("Song " + title + " has been added to playlist");
return true;
}
return false;
}
public boolean removeFromPlaylist(LinkedList<Song> playlist, String title) {
for (int i = 0; i < playlist.size(); i++) {
Song currentSong = playlist.get(i);
if (currentSong.getTitle().equals(title)) {
playlist.remove(currentSong);
System.out.println("Song " + title + " has been removed from playlist");
return true;
}
}
return false;
}
public Song checkAlbum(String title) {
for (int i = 0; i < songs.size(); i++) {
Song currentSong = songs.get(i);
if (currentSong.getTitle().equals(title)) {
return currentSong;
}
}
return null;
}
}
public class Song {
private String title;
private double duration;
public Song(String title, double duration) {
this.title = title;
this.duration = duration;
}
public String getTitle() {
return title;
}
@Override
public String toString() {
return this.title + ": " + this.duration;
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I suggest avoiding <code>static</code> state. It makes your code more rigid. It works for this very simple app, but the limitations become more apparent in more complex apps. You should remove the <code>static</code> keywords from your two lists and the <code>runPlaylist</code> method. You can instantiate an instance of the class to use in <code>main()</code> and call public methods on it.</p>\n<p>Some of your functionality doesn't employ separation of concerns. For example, your <code>Album</code> class has an <code>addToPlaylist</code> method. The functionality of the method is to check if the given <code>Song</code> is a member of the <code>Album</code> and only add it to the provided list if it is. The only part of that having anything to do with the <code>Album</code> is seeing if it owns the <code>Song</code>. Having the <code>Album</code> responsible for all that other behavior is tangling up your classes. On a large-scale, complicated project, this kind of code would become very difficult to maintain.</p>\n<p>So, I would remove <code>addToPlaylist</code> and <code>removeFromPlaylist</code> from the <code>Album</code> class. I would change the method <code>checkAlbum</code> to <code>containsSong</code> (names are important for code legibility!) and return a <code>boolean</code>. Those two removed methods should be moved up to the <code>Main</code> class, since it is the owner of the <code>Album</code> and the <code>Playlist</code> and so it is the one that knows what it wants to do with a Song.</p>\n<p>You are currently comparing <code>Song</code>s by their <code>title</code> field. This requires other classes (in this case <code>Album</code>) to dig into its internals to be able to compare <code>Song</code>s. Instead, you should have <code>Album</code> override <code>equals()</code> and provide the behavior you want. Since you are currently ignoring the <code>duration</code>, you can do that in its <code>equals</code> method. Now your code will be more maintainable, because you can change this behavior in a single location, and it's the most logical location. Also, it will help you replace some of these verbose <code>for</code> loops with simple <code>contains()</code> calls. <em>(Note, if you override equals, you should always override <code>hashcode</code> as well. The IDE can help you generate these together.)</em></p>\n<p>I would also change the parameters for <code>Album.addSong()</code> and <code>removeSong()</code> to take a <code>Song</code> instance instead of making <code>Album</code> responsible for instantiating <code>Song</code>s.</p>\n<p>And a tip. Use <code>final</code> when declaring fields that don't need to change, especially collections. This reduces the number of mutable things you have to keep track of. When you have a non-final <code>List</code> field, it is mutable in two different ways: you could change the contents of the list or replace the list entirely. Keep it simpler by restricting that to one way of modifying it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T14:54:55.923",
"Id": "480001",
"Score": "0",
"body": "thanks, have a good day"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T15:10:15.443",
"Id": "480003",
"Score": "0",
"body": "do you suggest me to create a Main class object in the main function and call runPlaylist with this object? like this Main play = new Main(); play.runPlaylist();"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T15:12:15.760",
"Id": "480004",
"Score": "0",
"body": "Yes. And probably rename the class Playlist."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T15:15:18.473",
"Id": "480005",
"Score": "0",
"body": "so there is no rule that the program must contain the main class? the main class is where psvm method is right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T15:30:29.730",
"Id": "480008",
"Score": "0",
"body": "It doesn't matter what the name of the class with the `main` method is. Personally, in a case like this, I would have a Playlist class and a separate Main class that has nothing in it except a main method that instantiates your Playlist class and uses it."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T14:38:44.603",
"Id": "244509",
"ParentId": "244504",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244509",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T13:51:43.587",
"Id": "244504",
"Score": "2",
"Tags": [
"java",
"beginner"
],
"Title": "Simple Playlist Editor/Player"
}
|
244504
|
<p>As more fully detailed in <a href="https://security.stackexchange.com/questions/233676/randomly-generating-invoice-ids">my question here</a>, I'm in the process of starting a small, local business and wanted to avoid showing sequential invoice IDs to clients, and instead generate completely random ones. Thanks to the advice in the comments to that question, I decided to eliminate the risk of any collisions by incorporating logic that checks against a database (a flat text file) of all IDs that have previously been generated.</p>
<p>This is my attempt at doing so, which to my amazement is functional, but probably not as robust as it could be. Since then I have also decided on using 5-digit numbers, as these look better to me and a limit of 99,000 transactions (without 00000, and I might even exclude the first 10,000 digits through to 09999) will be more than enough for me, and the logic of the script means that collisions should no longer be an issue.</p>
<pre><code>#!/usr/bin/env bash
generate_num() {
num=$(head /dev/urandom | tr -dc '[:digit:]' | cut -c 1-5)
}
read -p "Are you sure you want to generate a new invoice ID? [Y/n] " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
generate_num && echo Generating a random invoice ID and checking against database...
sleep 2
while grep -xq "$num" "ID_database"
do
echo Invoice ID \#$num already exists in database...
sleep 2
generate_num && echo Generating new random invoice ID and checking against database...
sleep 2
done
echo Generated random invoice ID \#$num
sleep 1
echo Invoice ID \#$num does not exist in database...
sleep 2
echo $num >> "ID_database" && echo Successfully added Invoice ID \#$num to database...
fi
</code></pre>
<p>I have two main questions I'd like answered about it.</p>
<ol>
<li><p>Can the code itself be improved on? This is one of the few Bash scripts I've ever written the core logic for, and perhaps the most involved, so if there's anything I shouldn't be doing or anything I could do better, I'd appreciate this.</p>
</li>
<li><p>Would it be conceivable to move the "database" into the script file itself, thus avoiding the need to maintain two separate files? If not, what are the reasons for this?</p>
</li>
</ol>
<p>Thank you in advance, I'd appreciate some help from those more experienced with Bash than I am.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T16:12:22.873",
"Id": "480013",
"Score": "0",
"body": "Just a thought: Why not using UUIDs as invoice IDs? That would prevent you from the hassle to check if these already exist in your database."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T16:18:44.657",
"Id": "480015",
"Score": "0",
"body": "@πάνταῥεῖ I want something that's nice and short to be more aesthetically appealing and memorable to clients and fit on the invoice, hence the 5 digit limit."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T14:37:22.930",
"Id": "244508",
"Score": "1",
"Tags": [
"random",
"bash",
"database"
],
"Title": "Randomly generating invoice IDs"
}
|
244508
|
<p>I'm posting my code for a LeetCode problem copied here. If you have time and would like to review, please do so.</p>
<h3>Problem</h3>
<blockquote>
<ul>
<li><p>Given a m * n grid, where each cell is either 0 (empty) or 1 (obstacle). In one step, you can move up, down, left or right from and to an empty cell.</p>
</li>
<li><p>Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m-1, n-1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.</p>
</li>
</ul>
<h3>Example 1:</h3>
<pre><code>Input:
grid =
[[0,0,0],
[1,1,0],
[0,0,0],
[0,1,1],
[0,0,0]],
k = 1
Output: 6
Explanation:
The shortest path without eliminating any obstacle is 10.
The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).
</code></pre>
<h3>Example 2:</h3>
<pre><code>Input:
grid =
[[0,1,1],
[1,1,1],
[1,0,0]],
k = 1
Output: -1
Explanation:
We need to eliminate at least two obstacles to find such a walk.
</code></pre>
<h3>Constraints:</h3>
<ul>
<li>grid.length == m</li>
<li>grid[0].length == n</li>
<li>1 <= m, n <= 40</li>
<li>1 <= k <= m*n</li>
<li>grid[i][j] == 0 or 1</li>
<li>grid[0][0] == grid[m-1][n-1] == 0</li>
</ul>
</blockquote>
<h3>Accepted Code</h3>
<pre><code>#include <array>
#include <string>
#include <vector>
#include <unordered_set>
#include <utility>
#include <algorithm>
class Solution {
public:
inline int shortestPath(const std::vector<std::vector<int>>& grid, const int k) {
if (grid.empty()) {
return 0;
}
int path_distance = INT_MAX;
get_manhattan_distance(0, -1, -1, 0, 0, k, grid, path_distance);
return path_distance == INT_MAX ? -1 : path_distance;
}
private:
// Four neighbor cells
static inline std::array<std::pair<int, int>, 4> directions = {{{0, 1}, {1, 0}, {0, -1}, { -1, 0}}};
std::unordered_set<std::string> memo;
// row - col - k string
static inline std::string get_key(const int row, const int col, const int k) {
return std::to_string(row) + "#" + std::to_string(col) + "#" + std::to_string(k);
}
// Calculate Manhattan distance
inline void get_manhattan_distance(const int path, const int prev_row, const int prev_col, const int row, const int col, int k, const std::vector<std::vector<int>>& grid, int& base_distance) {
if (k >= get_row_length(grid) + get_col_length(grid) - 3 - row - col) {
base_distance = min(base_distance, path + get_row_length(grid) + get_col_length(grid) - 2 - row - col);
return;
}
if (row == get_row_length(grid) - 1 && col == get_col_length(grid) - 1) {
base_distance = min(base_distance, path);
return;
}
if (!memo.insert(get_key(row, col, k)).second) {
return;
}
int curr_dist = get_distance(row, col, grid);
for (const auto& direction : directions) {
if (!(row + direction.first == prev_row && col + direction.second == prev_col) && is_valid(row + direction.first, col + direction.second, grid)) {
int dist = get_distance(row + direction.first, col + direction.second, grid);
if (grid[row + direction.first][col + direction.second] == 0) {
get_manhattan_distance(path + 1, row, col, row + direction.first, col + direction.second, k, grid, base_distance);
} else if (dist < curr_dist && k > 0) {
get_manhattan_distance(path + 1, row, col, row + direction.first, col + direction.second, k - 1, grid, base_distance);
}
}
}
}
// Get Current distance
static inline const int get_distance(const int row, const int col, const std::vector<std::vector<int>>& grid) {
return std::abs(row - get_row_length(grid) - 1) + std::abs(col - get_col_length(grid) - 1);
}
// Check for grid boundaries
static inline const bool is_valid(const int row, const int col, const std::vector<std::vector<int>>& grid) {
return row > -1 && row < get_row_length(grid) && col > -1 && col < get_col_length(grid);
}
// Get grid row size
static inline const int get_row_length(const std::vector<std::vector<int>>& grid) {
return grid.size();
}
// Get grid column size
static inline const int get_col_length(const std::vector<std::vector<int>>& grid) {
return grid[0].size();
}
};
</code></pre>
<h3>Reference</h3>
<p>LeetCode has a template for answering question. There is usually a class named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename.</p>
<ul>
<li><p><a href="https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/" rel="nofollow noreferrer">Problem</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/" rel="nofollow noreferrer">Discuss</a></p>
</li>
<li><p><a href="https://en.wikipedia.org/wiki/Taxicab_geometry" rel="nofollow noreferrer">Taxicab Geometry</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<p>The C++ key word <code>inline</code> is pretty much obsolete.<sup><a href=\"https://stackoverflow.com/q/1759300\">1</a> <a href=\"https://stackoverflow.com/q/29796264\">2</a></sup> Since at least C++03 <code>inline</code> is a recommendation to the compiler and nothing more. In the LeetCode environment it may help, but most C++ compilers are optimizing compilers and when code is compiled -O3 for maximum optimization the compiler decides what should and should not be inlined and ignores the keyword.</p>\n<pre><code>#include <array>\n#include <string>\n#include <vector>\n#include <unordered_set>\n#include <utility>\n#include <algorithm>\n\n\nclass Solution {\npublic:\n int shortestPath(const std::vector<std::vector<int>>& grid, const int k) {\n if (grid.empty()) {\n return 0;\n }\n\n int path_distance = INT_MAX;\n get_manhattan_distance(0, -1, -1, 0, 0, k, grid, path_distance);\n return path_distance == INT_MAX ? -1 : path_distance;\n }\n\nprivate:\n // Four neighbor cells\n constexpr static std::array<std::pair<int, int>, 4> directions = {{{0, 1}, {1, 0}, {0, -1}, { -1, 0}}};\n std::unordered_set<std::string> memo;\n\n // row - col - k string\n static std::string get_key(const int row, const int col, const int k) {\n return std::to_string(row) + "#" + std::to_string(col) + "#" + std::to_string(k);\n }\n\n // Calculate Manhattan distance\n void get_manhattan_distance(const int path, const int prev_row, const int prev_col, const int row, const int col, int k, const std::vector<std::vector<int>>& grid, int& base_distance) {\n if (k >= get_row_length(grid) + get_col_length(grid) - 3 - row - col) {\n base_distance = std::min(base_distance, path + get_row_length(grid) + get_col_length(grid) - 2 - row - col);\n return;\n }\n\n if (row == get_row_length(grid) - 1 && col == get_col_length(grid) - 1) {\n base_distance = std::min(base_distance, path);\n return;\n }\n\n if (!memo.insert(get_key(row, col, k)).second) {\n return;\n }\n\n int curr_dist = get_distance(row, col, grid);\n\n for (const auto& direction : directions) {\n if (!(row + direction.first == prev_row && col + direction.second == prev_col) && is_valid(row + direction.first, col + direction.second, grid)) {\n int dist = get_distance(row + direction.first, col + direction.second, grid);\n\n if (grid[row + direction.first][col + direction.second] == 0) {\n get_manhattan_distance(path + 1, row, col, row + direction.first, col + direction.second, k, grid, base_distance);\n\n } else if (dist < curr_dist && k > 0) {\n get_manhattan_distance(path + 1, row, col, row + direction.first, col + direction.second, k - 1, grid, base_distance);\n }\n }\n }\n }\n\n // Get Current distance\n static int get_distance(const int row, const int col, const std::vector<std::vector<int>>& grid) {\n return std::abs(row - get_row_length(grid) - 1) + std::abs(col - get_col_length(grid) - 1);\n }\n\n // Check for grid boundaries\n static const bool is_valid(const int row, const int col, const std::vector<std::vector<int>>& grid) {\n return row > -1 && row < get_row_length(grid) && col > -1 && col < get_col_length(grid);\n }\n\n // Get grid row size\n static int get_row_length(const std::vector<std::vector<int>>& grid) {\n return grid.size();\n }\n\n // Get grid column size\n static int get_col_length(const std::vector<std::vector<int>>& grid) {\n return grid[0].size();\n }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T16:58:17.320",
"Id": "480021",
"Score": "0",
"body": "I don't think it is fair to assume that -O3 is used. A small survey of online coding environments show that more use -O2 than -O3. On Leetcode discuss there are at least two unanswered questions on what the cpp compiler options are set to. I was unable to find an answer for Leetcode (, Hackerrank, or SPOJ). Codeforces, Codechef, ACM-ICPC, and UVa state that code is compiled with -O2, not the maximum optimisation level. Topcoder now uses -O3, but that is a recent change from sometime in the last 3 years. Google Code Jam uses -O3."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T17:00:37.313",
"Id": "480022",
"Score": "1",
"body": "@spyr03 And my review states that it might help in the LeetCode Environment but released code should be -O3, at least in my 30+ years of experience. Note it wasn't until more than 4 years ago that here on Code Review that I learned about this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T17:05:55.620",
"Id": "480024",
"Score": "2",
"body": "This is not completely accurate. `inline` is still meaningful, and required in some circumstances — it's just not related to optimization. Read more here: https://stackoverflow.com/a/5971755/23649"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T17:06:02.420",
"Id": "480025",
"Score": "0",
"body": "@pacmaninbw My point is that I disagree with your first statement \"inline is pretty much obsolete\" as that relies on -O3 being set, and that is not true in general, nor in the common case of online coding environments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T17:10:42.373",
"Id": "480026",
"Score": "3",
"body": "I think the general sentiment holds true. `inline`, certainly when used here and very often elsewhere, is an instance of both premature optimization as well as probably-ineffectual optimization, and is safe to discard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T17:51:56.990",
"Id": "480032",
"Score": "0",
"body": "@pacmaninbw Fair, you've added the code you would change it to. But in my opinion the review is rather lacking. The substantial change is not obvious in amongst the unchanged code. Why has the inline variable 'static inline' become 'constexpr static'? Is that better? If it is to be changed why not 'const' or no modifier at all?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T17:57:00.203",
"Id": "480035",
"Score": "0",
"body": "@spyr03 `Why has the inline variable static inline become constexpr static?` Because it wouldn't compile using in Visual Studio 2019 Professional until I changed it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T18:06:16.257",
"Id": "480036",
"Score": "0",
"body": "@spyr03 I have reviewed a number of the posters questions with additional information about some of the code used in this question, for instance `static` I did not feel it was necessary to reiterate that part of the answer here. Any additional discussion should continue in [the 2nd Monitor](https://chat.stackexchange.com/rooms/8595/the-2nd-monitor)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T16:18:49.473",
"Id": "244513",
"ParentId": "244512",
"Score": "0"
}
},
{
"body": "<h2>Appending to a string</h2>\n<p>For this:</p>\n<pre><code>std::to_string(row) + "#" + std::to_string(col) + "#" + std::to_string(k);\n</code></pre>\n<p>Check the <a href=\"https://www.cplusplus.com/reference/string/string/operator+/\" rel=\"nofollow noreferrer\">list of overloads</a>. One of them accepts a character, which you should prefer to using a string.</p>\n<h2>Const results</h2>\n<p>This:</p>\n<pre><code>inline const int get_distance(...\n</code></pre>\n<p>does not benefit from declaring the return value <code>const</code>. Integers are immutable anyway.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T16:48:08.607",
"Id": "480018",
"Score": "3",
"body": "Thank you <3 It's fun for me."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T16:45:18.643",
"Id": "244517",
"ParentId": "244512",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244513",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T16:07:21.263",
"Id": "244512",
"Score": "2",
"Tags": [
"c++",
"beginner",
"algorithm",
"programming-challenge",
"c++17"
],
"Title": "LeetCode 1293: Shortest Path in a Grid with Obstacles Elimination"
}
|
244512
|
<p>I found this <a href="https://stackoverflow.com/a/62246166">Powershell command</a> useful in comparing folders and find common and different files.
Since I really like C and C++, I've decided to create a program to do that.</p>
<p>It will get all files in 2 folders given as arguments, will store them in an <code>std::map</code>.
After, it will compare the 2 maps and give the common files. Is using <code>std::map</code> the best container for this?</p>
<p>Some notes:</p>
<p>The <code>findFiles</code> method should benefit from RAII treatment, but since I have ZERO work or internship experience, I am unable to implement that.</p>
<p>Some functions like finding a file size and iterating over a folder are present in C++ 17, but I use Digital Mars, an old compiler not up to date.</p>
<p>I use this compiler because it is small, provided as a compressed folder aka portable in the mainstream lexicon (even though portable means something else) and it is straightforward to use.</p>
<p>I used an online code beautifier for indentation.</p>
<p>The <code>sanitizePath</code> method is used to eliminate trailing "/" or "\" from the given path.</p>
<p>Please give all your valuable comments on this work.</p>
<pre><code>#include <iostream>
#include <iterator>
#include <map>
#include <string>
#include <sys/stat.h>
#include <windows.h>
#ifndef INVALID_FILE_ATTRIBUTES
constexpr DWORD INVALID_FILE_ATTRIBUTES = ((DWORD)-1);
#endif
bool IsDir(const std::string &path)
{
DWORD Attr;
Attr = GetFileAttributes(path.c_str());
if (Attr == INVALID_FILE_ATTRIBUTES)
return false;
return (bool)(Attr & FILE_ATTRIBUTE_DIRECTORY);
}
std::string sanitizePath(std::string const &input)
{
auto pos = input.find_last_not_of("/\\");
return input.substr(0, pos + 1);
}
std::map<std::string, unsigned long > findFiles(std::string &spath)
{
size_t i = 1;
WIN32_FIND_DATA FindFileData;
std::map<std::string, unsigned long > list;
std::string sourcepath = spath + std::string("\\*.*");
HANDLE hFind = FindFirstFile(sourcepath.c_str(), &FindFileData);
if (hFind != INVALID_HANDLE_VALUE)
do {
std::string fullpath = std::string(spath) + std::string("\\") + std::string(FindFileData.cFileName);
if (*(fullpath.rbegin()) == '.')
continue;
else
if (FindFileData.dwFileAttributes &FILE_ATTRIBUTE_DIRECTORY)
findFiles(fullpath);
else
{
list[FindFileData.cFileName] = FindFileData.nFileSizeHigh *(MAXWORD + 1) + FindFileData.nFileSizeLow;
}
} while (FindNextFile(hFind, &FindFileData));
FindClose(hFind);
return list;
}
void displayMap(std::map<std::string, unsigned long > &map)
{
std::map<std::string, unsigned long>::const_iterator itr;
for (itr = map.begin(); itr != map.end(); itr++)
std::cout << "File Name: " << itr->first << " Size: " << itr->second << " bytes" << std::endl;
}
std::map<std::string, unsigned long > map_intersect(std::map<std::string, unsigned long > const
&source, std::map<std::string, unsigned long > const &dest)
{
std::map<std::string, unsigned long > inter;
std::map<std::string, unsigned long>::const_iterator iter = dest.begin();
std::map<std::string, unsigned long>::const_iterator end = dest.end();
for (; iter != end; iter++)
{
if (source.find(iter->first) != source.end())
{
inter[iter->first] = iter->second;
}
}
return inter;
}
std::map<std::string, unsigned long > map_difference(std::map<std::string, unsigned long > const
&source, std::map<std::string, unsigned long > const &dest)
{
std::map<std::string, unsigned long > diff = source;
std::map<std::string, unsigned long>::const_iterator iter = dest.begin();
std::map<std::string, unsigned long>::const_iterator end = dest.end();
for (; iter != end; iter++)
{
if (source.find(iter->first) != source.end())
{
diff.erase(iter->first);
}
}
return diff;
}
int main(int argc, char **argv)
{
if (argc <= 2)
{
std::cerr << "No path or filename provided" << std::endl;
return EXIT_FAILURE;
}
const char *source = argv[1];
const char *destination = argv[2];
if (!IsDir(source))
{
std::cerr << "Source path doesn't exist" << std::endl;
return EXIT_FAILURE;
}
if (!IsDir(destination))
{
std::cerr << "Destination path doesn't exist" << std::endl;
return EXIT_FAILURE;
}
std::string spath = sanitizePath(source);
std::string dpath = sanitizePath(destination);
std::cout << "Comparing " << spath << " and " << dpath << std::endl;
std::map<std::string, unsigned long > slist, dlist, ilist, diflist;
slist = findFiles(spath);
dlist = findFiles(dpath);
ilist = map_intersect(slist, dlist);
diflist = map_difference(slist, dlist);
if (ilist.empty())
std::cout << "There is no common files" << std::endl;
else
{
std::cout << "The common files are" << std::endl;
displayMap(ilist);
}
if (diflist.empty())
std::cout << "The 2 folder are the same" << std::endl;
return EXIT_SUCCESS;
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Simplify For Loops by Using Ranged For Loops</strong><br />\n<a href=\"https://en.cppreference.com/w/cpp/language/range-for\" rel=\"nofollow noreferrer\">Ranged for loops</a> have existed in C++ since C++11. A ranged for loop is basically the equivalent of a <code>foreach</code> loop in PHP or C#. The functions <code>displayMap()</code>, <code>map_intersect()</code> and <code>map_difference()</code>. Using ranged for loops in these functions removes the need for the header file <code>iterator</code>.</p>\n<p>Compare the following functions to the ones in the question:</p>\n<pre><code>void displayMap(std::map<std::string, unsigned long >& map)\n{\n for (auto file: map)\n {\n std::cout << "File Name: " << file.first << " Size: " << file.second << " bytes" << "\\n";\n }\n\n std::cout << std::endl;\n}\n\nstd::map<std::string, unsigned long > map_intersect(std::map<std::string, unsigned long > const\n & source, std::map<std::string, unsigned long > const& dest)\n{\n std::map<std::string, unsigned long > intersections;\n for (auto file : dest)\n {\n if (source.find(file.first) != source.end())\n {\n intersections.insert(std::pair<std::string, unsigned long>(file.first, file.second));\n }\n }\n\n return intersections;\n}\n\nstd::map<std::string, unsigned long > map_difference(std::map<std::string, unsigned long > const\n & source, std::map<std::string, unsigned long > const& dest)\n{\n std::map<std::string, unsigned long > differences = source;\n for (auto file: dest)\n {\n if (source.find(file.first) != source.end())\n {\n differences.erase(file.first);\n }\n }\n\n return differences;\n}\n</code></pre>\n<p>The use and declaration of iterators is not required and simplifies the code.</p>\n<p><strong>Variable Names</strong><br />\nWhile the variable names are not <code>a</code>, <code>b</code>, <code>c</code> they are abbreviations and make the code less readable. The functions above have replaced some of the variable names as examples.</p>\n<p>In <code>main()</code> I would also lengthen the variable names of at least the lists:</p>\n<pre><code> std::map<std::string, unsigned long > sourceFiles, destinationFiles, intersections, differences;\n</code></pre>\n<p><strong>Put Variable Declarations on Separate Lines</strong><br />\nTo make code easier to maintain, each map/list should be declared on its own line.</p>\n<pre><code> std::map<std::string, unsigned long > sourceFiles;\n std::map<std::string, unsigned long > destinationFiles;\n std::map<std::string, unsigned long > intersections;\n std::map<std::string, unsigned long > differences;\n</code></pre>\n<p>This makes adding or deleting variables easier as well as making the code more readable.</p>\n<p><strong>Use std::string Rather than C Style Strings</strong><br />\nRather than use old style C strings initialize std::strings with <code>argv[1]</code> and <code>argv[2]</code>.</p>\n<pre><code> std::string source(argv[1]);\n std::string destination(argv[2]);\n</code></pre>\n<p>This ensures that the types match in the function calls.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T02:44:33.660",
"Id": "244546",
"ParentId": "244520",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244546",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T18:08:34.647",
"Id": "244520",
"Score": "4",
"Tags": [
"c++",
"winapi"
],
"Title": "Compare folders and find common files"
}
|
244520
|
<p>I want to understand if I got this concept correctly.</p>
<ol>
<li>I should start work from <code>ViewState</code>; a reference type object holding the state of a view. Here it is called <code>PageIndicatorVM</code>. It is bad-to-impossible to have any internal state in a <code>View</code>.</li>
<li>No logic in the <code>View</code> or so they say. Yet here and there in the code samples I see ternary operators and loops.</li>
<li><code>@Bidindg</code> property wrapper seems quite dangerous for me. It breaks unidirectional data flow and I have doubts if I used it correctly here.</li>
</ol>
<p>Please point out my mistakes. Will appreciate if you point me to best practices.</p>
<hr />
<p>This is a dot indicator component. It switches when <code>vm.next()</code> is called or user taps on a dot.</p>
<pre><code>struct DotIndicator: View {
let pageIndex: Int
@Binding var isOn: Int
var body: some View {
Button(action: {
self.isOn = self.pageIndex
}) {
Circle()
.scaleEffect( isOn == pageIndex ? 1.3 : 0.9)
.animation(.spring())
}
}
}
class PageIndicatorVM: ObservableObject {
@Published var currentPage: Int
let numPages: Int
init(numPages: Int, currentPage: Int = 0) {
self.numPages = numPages
self.currentPage = currentPage
}
func next() {
currentPage = (currentPage + 1) % numPages
}
}
struct PageIndicator: View {
@ObservedObject private var vm = PageIndicatorVM(numPages: 5)
private let spacing: CGFloat = 2
private let dotSize: CGFloat = 8
var body: some View {
VStack {
HStack(alignment: .center, spacing: spacing) {
ForEach((0..<vm.numPages ), id: \.self) {
DotIndicator(pageIndex: $0, isOn: self.$vm.currentPage)
.frame(
width: self.dotSize,
height: self.dotSize
)
}
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code is perfectly fine. Just a couple of comments:</p>\n<blockquote>\n<p>It is bad-to-impossible to have any internal state in a View.</p>\n</blockquote>\n<p>Actually SwiftUI was designed to handle state changes directly in a view. For simple cases you can easily do:</p>\n<pre><code>struct PageIndicator: View {\n @State private var currentPage = 0\n let numPages: Int = 5\n\n private let spacing: CGFloat = 2\n private let dotSize: CGFloat = 8\n\n var body: some View {\n VStack {\n HStack(alignment: .center, spacing: spacing) {\n ForEach(0 ..< numPages, id: \\.self) {\n DotIndicator(pageIndex: $0, isOn: self.$currentPage)\n .frame(width: self.dotSize, height: self.dotSize)\n }\n }\n }\n }\n}\n</code></pre>\n<pre><code>PageIndicator(numPages: 5)\n</code></pre>\n<p>What's more sometimes an <code>@ObservedObject</code> may be reinitialised contrary to a <code>@State</code> property (unless you use a <code>@StateObject</code> available in SwiftUI 2.0).</p>\n<p>For more information see: <a href=\"https://stackoverflow.com/questions/62544115/what-is-the-difference-between-observedobject-and-stateobject-in-swiftui/62544554#62544554\">What is the difference between ObservedObject and StateObject in SwiftUI</a>.</p>\n<blockquote>\n<p>No logic in the View or so they say. Yet here and there in the code\nsamples I see ternary operators and loops.</p>\n</blockquote>\n<p>True, but for simple cases creating a whole new ViewModel can actually make code less readable (as in the example above). Note that a <code>ForEach</code> loop is perfectly valid in a view.</p>\n<hr />\n<p>Apart from the comments above you can use an <code>Image(systemName:)</code> instead of a <code>Circle</code>:</p>\n<pre><code>struct DotIndicator: View {\n let pageIndex: Int\n\n @Binding var isOn: Int\n\n var body: some View {\n Button(action: {\n self.isOn = self.pageIndex\n }) {\n Image(systemName: "circle.fill")\n .imageScale(.small)\n .scaleEffect(isOn == pageIndex ? 1.0 : 0.7)\n .animation(.spring())\n }\n }\n}\n</code></pre>\n<p>Because a <code>Circle</code> consumes all available space, you need to constrain it with the <code>.frame</code> modifier. You don't have to do that with an <code>Image</code> - it reduces the code (<code>dotSize</code> is no longer needed) and scales automatically.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T07:16:37.447",
"Id": "487622",
"Score": "0",
"body": "Thank You for the review! I had been working with SwiftUI for a while after this post and now i am comfortable with it. Agree with all your comments!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T20:07:13.870",
"Id": "248834",
"ParentId": "244522",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248834",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T18:45:05.433",
"Id": "244522",
"Score": "3",
"Tags": [
"swift",
"ios",
"swiftui"
],
"Title": "SwiftUI Dot indicator"
}
|
244522
|
<p>Recently I've been doing some challenges on HackerRank and came across this <a href="https://www.hackerrank.com/challenges/box-operations/problem" rel="nofollow noreferrer">one</a>. First, I tried with Python, and then C. Both of my codes failed due to timeout restrictions.</p>
<p>It would be very helpful, if someone can tell me what can be improved in (one of) my codes (performance-wise).</p>
<p>Challenge description:</p>
<blockquote>
<p>Alice purchased an array of <span class="math-container">\$n\$</span> wooden boxes that she indexed from <span class="math-container">\$0\$</span> to <span class="math-container">\$n - 1\$</span>. On each box <span class="math-container">\$i\$</span>, she writes an integer that we'll refer to as <span class="math-container">\$box_{i}\$</span>.</p>
<p>Alice wants you to perform <span class="math-container">\$q\$</span> operations on the array of boxes. Each operation is in one of the following forms:</p>
<p>(Note: For each type of operations, <span class="math-container">\$l \le i \le r\$</span>)</p>
<ul>
<li><code>1 l r c</code>: Add <span class="math-container">\$c\$</span> to each <span class="math-container">\$box_{i}\$</span>. Note that <span class="math-container">\$c\$</span> can be negative.</li>
<li><code>2 l r d</code>: Replace each <span class="math-container">\$box_{i}\$</span> with <span class="math-container">\$\left\lfloor\frac{box_{i}}{d}\right\rfloor\$</span>.</li>
<li><code>3 l r</code>: Print the minimum value of any <span class="math-container">\$box_{i}\$</span>.</li>
<li><code>4 l r</code>: Print the sum of all <span class="math-container">\$box_{i}\$</span>.</li>
</ul>
<p>Recall that <span class="math-container">\$\lfloor x \rfloor\$</span> is the maximum integer <span class="math-container">\$y\$</span> such that <span class="math-container">\$ y \le x\$</span> (e.g., <span class="math-container">\$\lfloor -2.5\rfloor = -3\$</span> and <span class="math-container">\$\lfloor -7\rfloor = -7\$</span>).</p>
<p>Given <span class="math-container">\$n\$</span>, the value of each <span class="math-container">\$box_{i}\$</span>, and <span class="math-container">\$q\$</span> operations, can you perform all the operations efficiently?</p>
<h2>Input format</h2>
<p>The first line contains two space-separated integers denoting the respective values of <span class="math-container">\$n\$</span> (the number of boxes) and <span class="math-container">\$q\$</span> (the number of operations).</p>
<p>The second line contains <span class="math-container">\$n\$</span> space-separated integers describing the respective values of <span class="math-container">\$box_0, box_1, \dots, box_{n-1}\$</span> (i.e. the integers written on each box).</p>
<p>Each of the <span class="math-container">\$q\$</span> subsequent lines describes an operation in one of the four formats described above.</p>
<h2>Constraints</h2>
<ul>
<li><span class="math-container">\$1 \le n,q \le 10^5\$</span></li>
<li><span class="math-container">\$-10^9 \le box_{i} \le 10^9\$</span></li>
<li><span class="math-container">\$0 \le l \le r \le n - 1\$</span></li>
<li><span class="math-container">\$-10^4 \le c \le 10^4\$</span></li>
<li><span class="math-container">\$2 \le d \le 10^9\$</span></li>
</ul>
<h2>Output Format</h2>
<p>For each operation of type <span class="math-container">\$3\$</span> or type <span class="math-container">\$4\$</span>, print the answer on a new line.</p>
<h2>Sample Input 0</h2>
<pre class="lang-none prettyprint-override"><code>10 10
-5 -4 -3 -2 -1 0 1 2 3 4
1 0 4 1
1 5 9 1
2 0 9 3
3 0 9
4 0 9
3 0 1
4 2 3
3 4 5
4 6 7
3 8 9
</code></pre>
<h2>Sample Output 0</h2>
<pre class="lang-none prettyprint-override"><code>-2
-2
-2
-2
0
1
1
</code></pre>
<h2>Explanation 0</h2>
<p>Initially, the array of boxes looks like this:</p>
<p><code>[ -5 ][ -4 ][ -3 ][ -2 ][ -1 ][ 0 ][ 1 ][ 2 ][ 3 ][ 4 ]</code></p>
<p>We perform the following sequence of operations on the array of boxes:</p>
<ol>
<li>The first operation is <code>1 0 4 1</code>, so we add <span class="math-container">\$1\$</span> to each <span class="math-container">\$box_{i}\$</span> where <span class="math-container">\$0 \le i \le 4\$</span>:</li>
</ol>
<p><code>[ -4 ][ -3 ][ -2 ][ -1 ][ 0 ][ 0 ][ 1 ][ 2 ][ 3 ][ 4 ]</code></p>
<ol start="2">
<li>The second operation is <code>1 5 9 1</code>, so we add <span class="math-container">\$c = 1\$</span> to each <span class="math-container">\$box_i\$</span> where <span class="math-container">\$5 \le i \le 9\$</span>.</li>
</ol>
<p><code>[ -4 ][ -3 ][ -2 ][ -1 ][ 0 ][ 1 ][ 2 ][ 3 ][ 4 ][ 5 ]</code></p>
<ol start="3">
<li>The third operation is <code>2 0 9 3</code>, so we divide each <span class="math-container">\$box_i\$</span> where <span class="math-container">\$0 \le i \le 9\$</span> by <span class="math-container">\$d = 3\$</span> and take the floor:</li>
</ol>
<p><code>[ -2 ][ -1 ][ -1 ][ -1 ][ 0 ][ 0 ][ 0 ][ 1 ][ 1 ][ 1 ]</code></p>
<ol start="4">
<li>The fourth operation is <code>3 0 9</code>, so we print the minimum value of <span class="math-container">\$box_i\$</span> for <span class="math-container">\$0 \le i \le 9\$</span>.
<span class="math-container">$$min(-2, -1, -1, -1, 0, 0, 0, 1, 0, 1) = -2$$</span></li>
<li>The fifth operation is <code>4 0 9</code>, so we print the sum of <span class="math-container">\$box_i\$</span> for <span class="math-container">\$0 \le i \le 9\$</span> which is the result of
<span class="math-container">$$ -2 + -1 + -1 + -1 + 0 + 0 + 0 + 1 + 1 + 1 = -2$$</span>
... and so on.</li>
</ol>
</blockquote>
<p>C code:</p>
<pre><code>int minBox(int *box, int l, int r){
int min=box[l];
for(int i = l+1; i<=r; i++)
if(box[i] < min)
min = box[i];
return min;
}
int sumBox(int *box, int l, int r){
int sum=0;
for(int i = l; i<=r; i++)
sum += box[i];
return sum;
}
void operateOnBox(int *op, int *box){
switch(op[0]){
case 3:
printf("%d\n", minBox(box, op[1], op[2]));
break;
case 4:
printf("%d\n", sumBox(box, op[1], op[2]));
break;
case 1:
for(int i = op[1]; i <= op[2]; i++)
box[i] += op[3];
break;
case 2:
for(int i = op[1]; i <= op[2]; i++)
box[i] = (int) floor(box[i]/((float)op[3]));
break;
}
}
int main()
{
int n, q, *box;
scanf("%d %d", &n, &q);
box = (int*) malloc(sizeof(int) * n);
for(int i = 0; i<n; i++)
scanf("%d", box+i);
for(int i = 0; i<q; i++){
int op[4];
scanf("%d %d %d", op, op+1, op+2);
if(op[0] == 1 || op[0] == 2)
scanf("%d", op+3);
operateOnBox(op, box);
}
return 0;
}
</code></pre>
<p>Python 3 code:</p>
<pre><code>def operate(op, box):
if op[0] == 3:
print(min(box[op[1]:op[2]+1]))
elif op[0] == 4:
print(sum(box[op[1]:op[2]+1]))
elif op[0] == 1:
box[op[1]:op[2]+1] = map(lambda x: x+op[3], box[op[1]:op[2]+1])
elif op[0] == 2:
box[op[1]:op[2]+1] = map(lambda x: math.floor(x/op[3]), box[op[1]:op[2]+1])
if __name__ == '__main__':
nq = input().split()
n = int(nq[0])
q = int(nq[1])
box = list(map(int, input().rstrip().split()))
for i in range(q):
op = list(map(int, input().split()))
operate(op, box)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T19:00:04.910",
"Id": "480040",
"Score": "1",
"body": "Welcome to Code Review! Generally it's better to include text rather than an image because text is searchable and the image is not. Also, the text tends to be smaller."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T19:04:20.700",
"Id": "480042",
"Score": "0",
"body": "@Edward Thank you, I tried to paste a very brief description of it, but it contains mathematic formulas that do not render here. I'll keep it in my mind for next questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T19:07:08.357",
"Id": "480043",
"Score": "1",
"body": "Please take a look at how other [tag:programming-challenge] questions have solved this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T19:43:16.280",
"Id": "480046",
"Score": "0",
"body": "I've edited the question for you to show how this can be done. Please study it so you know how to do it yourself from here on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T20:28:09.330",
"Id": "480048",
"Score": "0",
"body": "@Edward I will, thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T04:17:51.630",
"Id": "495322",
"Score": "0",
"body": "It would be helpful if you can time things yourself. How big of inputs can you handle? How much too slowly are you running? Pay especial attention to the given problem constraints."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T04:21:02.613",
"Id": "495323",
"Score": "0",
"body": "I'm not sure how much experience you have with programming challenges, but if you're encountering timeouts, the problem is probably one that requires a clever algorithm, not slightly better code."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T18:50:31.450",
"Id": "244523",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"c",
"programming-challenge"
],
"Title": "Performance challenge: Box operations (HackerRank) (C, Python)"
}
|
244523
|
<p>I made this Tic Tac Toe game in C. It works but I thinks it could be programmed better. You have the option to play alone or between two players. It also lets the player select if he uses 'X' or 'O'.
Please check it out and review.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char marks[3][3]; /*stores each move the players make*/
int counter = 0; /*counter to check if space available*/
void initialize_rdm(void); /*initializes random number generator*/
void initialize_grid(void); /*resets the array marks to numbers*/
void grid(void); /*prints the grid and the array*/
int checker(char c, int player); /*checks if the grid selected is available*/
void result(void); /*checks if there is a winner and prints result*/
void retry(void); /*after game finished, can call main function again*/
void ai_opponent(int n); /*randomly fills the grid, used as opponent for player*/
void singleplayer(int n); /*calls all funtion used to play alone, against computer*/
void multiplayer(void); /*calls all funtions used to play between to people*/
int main(void){
int op, x;
initialize_rdm();
initialize_grid();
grid();
printf("\tGame Options:\n\n\t1 - Player 1 vs. Player 2.");
printf("\n\n\t2 - Player vs. Computer.\n\n\t3 - Computer vs. Computer (EXTRA MODE).\n\n\t4 - Exit Game.");
printf("\n\nSelect an option: ");
for(;;){
scanf("%d", &op);
switch(op){
case 1:
multiplayer();
case 2:
grid();
printf("\tHow would you like to play?.\n\n");
printf("\t1 - Play using 'X' (Player 1).\n\n\t2 - Play using 'O' (Player 2).");
printf("\n\n\nSelect an option: ");
scanf("%d", &x);
while(x != 1 && x != 2){
printf("\nERROR! Please select a valid option: ");
scanf("%d", &x);
}
singleplayer(x);
case 3:
for(;;){
ai_opponent(1);
result();
ai_opponent(2);
result();
}
case 4:
printf("\nThanks for Playing! :D");
printf("\n\nMade by:\n\nMe XDXDXDXDXD.");
exit (EXIT_SUCCESS);
default:
printf("\nERROR! Please select a valid option: ");
}
}
}
void initialize_rdm(void){
srand((unsigned) time(NULL));
}
void initialize_grid(void){
int i, j;
char k = '1';
for(i = 0; i < 3; i++){
for(j = 0; j < 3; j++){
marks[i][j] = k++;
}
}
}
void grid(void){
system("CLS");
printf("Tic-Tac-Toe: The Game / Ta-Te-Ti: El Juego\n");
printf("\n\t | |\n");
printf("\t %c | %c | %c\n", marks[0][0], marks[0][1], marks[0][2]);
printf("\t | |\n");
printf("\t-------------------------\n");
printf("\t | |\n");
printf("\t %c | %c | %c\n", marks[1][0], marks[1][1], marks[1][2]);
printf("\t | |\n");
printf("\t-------------------------\n");
printf("\t | |\n");
printf("\t %c | %c | %c\n", marks[2][0], marks[2][1], marks[2][2]);
printf("\t | |\n\n");
}
int checker(char c, int player){
int i,j;
if(c < '1' || c > '9'){
printf("\nERROR! Please select a valid grid: ");
return 0;
}
for(i = 0; i < 3; i++){
for(j = 0; j < 3; j++){
if(marks[i][j] == c){
switch(player){
case 1:
counter++;
marks[i][j] = 'X';
return 1;
case 2:
counter++;
marks[i][j] = 'O';
return 1;
}
}
}
}
printf("\nGRID ALREADY FILLED!\n\nPlease select another grid: ");
return 0;
}
void result(void){
float condition;
int i, j, winner = 3;
grid();
for(i = 0; i < 3; i++){
for(j = 0, condition = 0; j < 3; j++){ /*checks rows*/
if(marks[i][j] == 'X' || marks[i][j] == 'O'){
condition += marks[i][j];
}
if((condition / 'X') == 3.0){
winner = 1;
} else if((condition / 'O') == 3.0){
winner = 2;
}
}
}
for(j = 0; j < 3; j++){
for(i = 0, condition = 0; i < 3; i++){ /*checks columns*/
if(marks[i][j] == 'X' || marks[i][j] == 'O'){
condition += marks[i][j];
}
if((condition / 'X') == 3.0){
winner = 1;
} else if((condition / 'O') == 3.0){
winner = 2;
}
}
}
for(i = 0, j = 0, condition = 0; i < 3; i++, j++){ /*checks diagonally*/
if(marks[i][j] == 'X' || marks[i][j] == 'O'){
condition += marks[i][j];
}
if((condition / 'X') == 3.0){
winner = 1;
} else if((condition / 'O') == 3.0){
winner = 2;
}
}
for(i = 2, j = 0, condition = 0; j < 3; i--, j++){ /*checks diagonally*/
if(marks[i][j] == 'X' || marks[i][j] == 'O'){
condition += marks[i][j];
}
if((condition / 'X') == 3.0){
winner = 1;
} else if((condition / 'O') == 3.0){
winner = 2;
}
}
if(counter >= 9 && winner == 3)
winner = 0;
switch(winner){
case 0:
printf("\a\nIT'S A DRAW!");
retry();
case 1:
printf("\aPLAYER 1 WINS!");
retry();
case 2:
printf("\aPLAYER 2 WINS!");
retry();
default: return;
}
}
void retry(void){
char c;
counter = 0;
printf("\n\nWould you like to play again?(Y/N): ");
scanf(" %c", &c);
if(c == 'Y' || c == 'y'){
main();
} else{
printf("\n\nThanks for Playing! :)");
printf("\n\nMade by:\n\nInsert Students names xd.");
exit(EXIT_SUCCESS);
}
}
void ai_opponent(int n){
int a, b, i;
for(;;){
a = rand() % 3;
b = rand() % 3;
if(marks[a][b] != 'X' && marks[a][b] != 'O'){
switch(n){
case 1:
marks[a][b] = 'X';
counter++;
return;
case 2:
marks[a][b] = 'O';
counter++;
return;
}
}
}
}
void singleplayer(int n){
char c;
grid();
for(;;){
if(n == 1){
printf("\nPlease select a grid: ");
do{
scanf(" %c", &c);
} while(checker(c, n) != 1);
result();
ai_opponent(2 / n);
} else if(n == 2){
ai_opponent(2 / n);
result();
printf("\nPlease select a grid: ");
do{
scanf(" %c", &c);
} while(checker(c, n) != 1);
}
result();
}
}
void multiplayer(void){
char c;
grid();
for(;;){
printf("\nPlayer 1: Please select a grid: ");
do{
scanf(" %c", &c);
} while(checker(c, 1) != 1);
result();
printf("\nPlayer 2: Please select a grid: ");
do{
scanf(" %c", &c);
} while(checker(c, 2) != 1);
result();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T18:19:30.470",
"Id": "480484",
"Score": "1",
"body": "Not enough for a review, but *definitely* work on your indentation. It took me a bit to see where certain functions ended."
}
] |
[
{
"body": "<blockquote>\n<p>Please check it if you can, and give your opinion!</p>\n</blockquote>\n<p><strong>Enable more warnings</strong></p>\n<pre><code>warning: this statement may fall through [-Wimplicit-fallthrough=]\n\nunused variables `int a, b, i;`\n</code></pre>\n<p><strong>Spell check</strong></p>\n<p><em>funtion</em></p>\n<p><strong>Do not re-enter <code>main()</code></strong></p>\n<p>Yes, it is possible, yet makes code review and debug a <a href=\"https://www.macmillandictionary.com/us/dictionary/american/a-bear\" rel=\"nofollow noreferrer\">bear</a> and hard to spin this code off into its own <code>TicTacToe()</code> function. Don't do that.</p>\n<pre><code>if (c == 'Y' || c == 'y') {\n // main();\n alternative code\n</code></pre>\n<p><strong>Flush when you are done</strong></p>\n<p>To insure output is seen when expected, usual a final <code>'\\n'</code> is enough for <em>line buffered</em> <code>stdout</code>.</p>\n<pre><code>// printf("\\nThanks for Playing! :D");\nprintf("\\nThanks for Playing! :D\\n");\n// ^^\n</code></pre>\n<p>Pedantically, could use <code>fflush(stdout);</code> instead.</p>\n<pre><code>printf("\\nThanks for Playing! :D");\nfflush(stdout);\n</code></pre>\n<p>This advice applies to all the <code>printf()</code>s.</p>\n<p><strong>Format</strong></p>\n<p>Always a personal preference, yet at a minimum, add a blank line between functions.</p>\n<p><strong>Why <code>float</code>?</strong></p>\n<p>Use of floating point here makes little sense.</p>\n<pre><code>// float condition;\n// if((condition / 'X') == 3.0){\n\nint condition;\nif (condition == 3*'X') {\n</code></pre>\n<p>Further:</p>\n<p>Accumulating with <code>condition += marks[i][j];</code> and testing with <code>(condition / 'X') == 3.0</code> or <code>condition == 3*'X'</code> could incorrectly be true under select character coding and alternative values for the "empty" squares.</p>\n<p>Alternative:</p>\n<pre><code>int32_t condition = 0;\n...\ncondition = condition*256 + marks[i][j];\n... \nif (condition == 'X'*(65536 + 256 + 1))) { \n</code></pre>\n<p><strong>Test evil user input</strong></p>\n<p>Robust code would check the return value of <code>scanf()</code> before using scanned results.</p>\n<pre><code>//scanf(...\nif (scanf(...) != Expected_Scan_Count) Handle_Error();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T03:46:53.930",
"Id": "480078",
"Score": "2",
"body": "Overall agree. However, flushing the final string before the program exits is really not necessary. There will be an implicit flush on exit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T03:51:05.650",
"Id": "480079",
"Score": "3",
"body": "@Reinderien `printf()` is not only used here just before exit. This answer's advise applies to all `printf()`s. Answer amended to reflect that idea. In particular, a `printf()` as part of a prompt before a `scanf()` can get hung up in buffering. For maximum portability, `fflush()`. For common portability, end the `printf()` with a `'\\n'` before a `scanf()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T07:46:34.467",
"Id": "480091",
"Score": "4",
"body": "re: code formatting: I'd definitely also recommend indenting function bodies at least some, so it's easier to spot top-level lines. Every level of `{}` should be a new level of indentation, including the outer-most."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T08:22:13.167",
"Id": "480093",
"Score": "1",
"body": "@PeterCordes Concerning horizontal white-space idea. I agree. Since I cut/paste/auto format, the code I reviewed is nicely formatted - to my liking - except for the vertical intra-function spacing mentioned. IMO, well formatted code is good when \n it can auto re-format easily."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T08:23:22.653",
"Id": "480094",
"Score": "1",
"body": "@PeterCordes except for switch-case according to at least some style guides where the statements are indented, the case labels are not."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T03:35:50.407",
"Id": "244551",
"ParentId": "244524",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "244551",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T19:06:25.583",
"Id": "244524",
"Score": "12",
"Tags": [
"beginner",
"c",
"game",
"tic-tac-toe"
],
"Title": "I made Tic Tac Toe in C"
}
|
244524
|
<p>This piece of code does a linear generation with two 'tweaks':</p>
<ol>
<li>It sets a global <code>loop</code> as an index to reference variables that are holding values that need to be exclusive to that value of <code>loop</code>. These variable are those using pointers and double pointers. That way we can play on the loop value with each word's generation and the final output are the words, looping in chunks starting with the remainings shortests words to the longests ones.</li>
<li>The sequence is modified, you can check the <a href="https://github.com/e2002e/zhou/blob/master/README.md" rel="nofollow noreferrer">readme on github</a></li>
</ol>
<p>It can restore sessions and needs to be parallelized.</p>
<pre><code>#include <cstdlib>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <omp.h>
#include <math.h>
#include <signal.h>
#include "zhou.h"
bool one = 0; //needed for option parsing and in generate1/2/3()
int min, max;
int length;//length of each character sets
char *arrayofchars;//the character sets
char *tmp;
int **arrayofindex;
unsigned long int *counters;
unsigned long int total, A, B;
unsigned long int *rain;
int loop;
int mmm;//max-min
inline int accu(int value) {
int i;
int sum = 0;
for(i=1; i<=value; ++i) {
sum+=i;
}
return sum;
}
void gen_next() {
int i;
for(i=0; i<min+loop; ++i) {
tmp[i] = arrayofchars[(arrayofindex[loop][i]+rain[loop])%length];
rain[loop]+=i+1;
}
if(length%10 == 0)
rain[loop]-=accu(min+loop)-2;
else if(length%2 == 0)
rain[loop]-=accu(min+loop)-4;
else if(length%2)
rain[loop]-=accu(min+loop)-1;
//hydra's bfg method by Jan Dlabal
int pos = min + loop - 1;
while(pos >= 0 && ++arrayofindex[loop][pos] >= length) {
arrayofindex[loop][pos] = 0;
pos--;
}
tmp[min+loop]='\n';
tmp[min+loop+1]='\0';
}
void gen() {
//int nt = omp_get_max_threads();
int loop2 = B;
tmp = (char *) malloc(max);
for(unsigned long int a=A; a<total; ++a) {
loop = B = loop2;
while(loop <= mmm) {
if(counters[loop] >= (unsigned long int) pow((double) length, (double) min+loop)) {
++loop2;
}
else {
gen_next();
printf("%s", tmp);
++counters[loop];
}
++loop;
}
}
}
void showhelp() {
printf(\
"Minimum arguments:\n"
"./zhou [ min max --set | -set <string> ] | [ -r | -restore | --restore ]\n"
"./zhou 4 8 -set ABCD\n"
);
}
void signalHandler(int sig) {
FILE* fd = fopen("restore", "w");
fprintf(fd, "%d:", max);
fprintf(fd, "%d:", min);
fprintf(fd, "%d:", length);
fprintf(fd, "%s:%d:", arrayofchars, loop);
for(int a=0; a<=mmm; ++a) {
for(int b=0; b<max; ++b)
fprintf(fd, "%d:", arrayofindex[a][b]);
fprintf(fd, "%ld:%ld:", rain[a], counters[a]);
}
fprintf(fd, "%ld:", A);
fprintf(fd, "%ld:", B);
exit(0);
}
int main(int argc, char *argv[]) {
int arg;
total = 0;
signal(SIGKILL, signalHandler);
signal(SIGINT, signalHandler);
if(argc > 2) {
for(arg=1; arg<argc; arg++) {
if(strcmp(argv[arg], "--set") == 0 || strcmp(argv[arg], "-set") == 0 || strcmp(argv[arg], "-s") == 0) {
length = strlen(argv[arg+1]);
arrayofchars = (char*) malloc(length);
strcpy(arrayofchars, argv[arg+1]);
one = 1;
}
if(strcmp(argv[arg], "-h") == 0 || strcmp(argv[arg], "--help") == 0 || strcmp(argv[arg], "-help") == 0) {
showhelp();
exit(0);
}
}
if(!(min = atoi(argv[1]))) { printf("invalid minimum length; ./zhou min max ...\n"); exit(-1); }
if(!(max = atoi(argv[2]))) { printf("invalid minimum length; ./zhou min max ...\n"); exit(-1); }
if(!one) { printf("need input characters: --set option.\n"); exit(-1); }
mmm = max-min;
rain = (long unsigned int*)malloc((mmm+1)*sizeof(long unsigned int));
counters = (long unsigned int*)malloc((mmm+1)*sizeof(long unsigned int));
arrayofindex = (int**)malloc(max*sizeof(int**));
for(int a=0; a<=mmm; ++a) {
total += (long int)pow((double)length,(double)min+a);
arrayofindex[a] = (int*) malloc(max*sizeof(int));
for(int b=0; b<max; ++b)
arrayofindex[a][b] = 0;
rain[a] = 0;
counters[a] = 0;
}
A=0;
B=0;
loop = 0;
}
else if(argc == 2 && (strcmp(argv[1], "-r") == 0 || strcmp(argv[1], "--restore") == 0 || strcmp(argv[1], "-restore") == 0)) {
FILE *fd = fopen("restore", "r+");
int filesize=0;
do {
++filesize;
getc(fd);
} while(!feof(fd));
char *buff = (char*)malloc(filesize);
fseek(fd, 0, SEEK_SET);
max = (int)strtol(strtok(buff, ":"), NULL, 10);
min = (int)strtol(strtok(NULL, ":"), NULL, 10);
mmm = max-min;
length = (int)strtol(strtok(NULL, ":"), NULL, 10);
rain = (long unsigned int*)malloc((max-min+1)*sizeof(long unsigned int));
counters = (long unsigned int*)malloc((max-min+1)*sizeof(long unsigned int));
arrayofindex = (int**)malloc(mmm*sizeof(int*));
arrayofchars = (char*)malloc(length);
arrayofchars = strtok(NULL, ":");
loop = (int)strtol(strtok(NULL, ":"), NULL, 10);
for(int a=0; a<=max-min; ++a) {
arrayofindex[a] = (int*) malloc(max*sizeof(int));
for(int b=0; b<max; ++b)
arrayofindex[a][b] = (int)strtol(strtok(NULL, ":"), NULL, 10);
total += (long int)pow((double)length,(double)min+a);
rain[a] = (unsigned long int)strtol(strtok(NULL, ":"), NULL, 10);
counters[a] = (unsigned long int)strtol(strtok(NULL, ":"), NULL, 10);
}
A = (unsigned long int)strtol(strtok(NULL, ":"), NULL, 10);
B = (unsigned long int)strtol(strtok(NULL, ":"), NULL, 10);
}
else {
showhelp();
exit(0);
}
gen();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T20:37:06.133",
"Id": "480049",
"Score": "1",
"body": "On Code Review we only review code that is working as intended. Since you're talking about a bug this is clearly not the case."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T20:14:47.227",
"Id": "244525",
"Score": "2",
"Tags": [
"c++",
"algorithm",
"generator"
],
"Title": "A word generator meant to be piped to hashcat/jrt which would then use amplificators (rules)"
}
|
244525
|
<p>I wrote a script to execute a service on the <a href="https://f-tep.com/" rel="nofollow noreferrer">Forestry TEP platform</a> via its REST API. This service has certain input parameters, some of them are numerical values, other strings or files. The current workflow is:</p>
<ol>
<li><p>There is a configuration file that has options for file and literal inputs. Each option is a dictionary, where each key is equal to one parameter of the service I want to execute. Example of such file:</p>
<pre class="lang-py prettyprint-override"><code>file_inputs= {"cfg" : "forest_flux/FTEP_service/cfg.ini",
"parsawen" : "forest_flux/FTEP_service/parsawen.csv",
"weather" : "forestflux/data/fin_01/weather/weather_2004.csv"}
literal_inputs = {"version" : 3}
</code></pre>
</li>
<li><p>In the script, I read the cfg and iterate over items in these dictionaries. For each <code>key,value</code> pair, I use <code>exec()</code> to store the value in a class variable of the same name. For file inputs, I first upload the file on the platform and store the file's location on the platform in the variable.</p>
<pre><code> input_files_dict = json.loads(cfg.get("service_info", "file_inputs"))
for key, val in input_files_dict.items():
exec("self.{} = self.post_data('{}')".format(key, val))
literal_inputs_dict = json.loads(cfg.get("service_info", "literal_inputs"))
for key, val in literal_inputs_dict.items():
exec("self.{} = '{}'".format(key, val))
</code></pre>
</li>
<li><p>I request service inputs and I try to match the service parameters with my class variables. I add it to a dictionary of parameters which I then send to the platform when executing the service.</p>
<pre><code> r2 = requests.get(url = url2, verify=False, allow_redirects=False, cookies=self.session_cookies)
data_inputs = json.loads(r2.text)['serviceDescriptor']['dataInputs']
for _input in data_inputs:
value_to_set = eval("self." + _input["id"].lower())
job_config["inputs"][_input["id"]] = [value_to_set]
</code></pre>
</li>
</ol>
<p>This current workflow works well for me but I have strong suspicion that it is a very bad practice. I have read that using exec() and eval() is discouraged as there are security issues. However, I cannot think of a better way to achieve this functionality, i.e. to pair values in configuration with service inputs automatically. I want this script to be generic, i.e. usable for any service on the platform.</p>
<p><strong>Question:</strong> How could I do this without using the problematic functions? How could using these functions be problematic in this case?</p>
<p>Please note that I removed a lot of code that is not related to the problem I am asking about (e.g. error handling).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T20:26:03.773",
"Id": "480047",
"Score": "0",
"body": "You could use [ast.literal_eval](https://docs.python.org/3/library/ast.html#ast.literal_eval) but beware that \"_It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler._\""
}
] |
[
{
"body": "<p>You can use <code>getattr</code>, <code>setattr</code> and <code>delattr</code> to retrieve, modify and remove attributes respectively. This avoids most potential messes <code>eval</code> has.</p>\n<pre><code>input_files_dict = json.loads(cfg.get("service_info", "file_inputs"))\nfor key, val in input_files_dict.items():\n setattr(self, key, self.post_data(f'{value}'))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T17:40:17.587",
"Id": "480149",
"Score": "0",
"body": "Thanks! So f'{value}') is equal to '{}'.format(value) ? Is one preferred over the other and why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T17:49:21.660",
"Id": "480150",
"Score": "2",
"body": "@JanPisl Yes. `f'{value}'` is preferred (as it is shorter) than `str.format`. But some modern programs still use `str.format` as they need to support versions of Python that f-strings are not available in."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T20:38:53.877",
"Id": "244529",
"ParentId": "244526",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244529",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T20:18:31.833",
"Id": "244526",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"security",
"configuration"
],
"Title": "How to avoid using exec() and eval() in Python"
}
|
244526
|
<p>For a library I am working on, I have created a class <code>WatchableCollection</code> which will monitor an endpoint of an API for updates and issue events (<code>WatchableCollection</code> extends <code>EventEmitter</code>). The constructor of <code>WatchableCollection</code> takes an initial set of values to store and an async function to check for new endpoints.</p>
<p>Users of <code>WatchableCollection</code> can enable polling the check function for new updates using the <code>.watch()</code> method, and stop polling using the <code>.unwatch()</code> method.</p>
<p>Where my concern rests is in the method I have added recently, <code>.filter()</code> which will return a new <code>WatchableCollection</code> with only items that meet the passed predicate function. <strong>Additionally, it updates the check function of this new WatchableCollection to only issue events on new/updated items that fit this predicate</strong>. This is where I have concerns for extra network requests and/or memory allocation.</p>
<pre><code>// WatchableCollection.ts
/**
* Returns a new WatchableCollection of the items which pass the filter.
* Note this collection is watchable, and watch events will only be triggered for items that fit the filter function.
*
* @example
* const event = await robotevents.events.get(sku);
* const skills = (await event.skills()).filter(run => run.score > 30);
*
* skills.watch();
* skills.on("add", run => console.log("New run over 30pts", run));
*
* @param predicate
*/
filter(
predicate: (
item: T,
id: I,
collection: WatchableCollection<T, I>
) => boolean
): WatchableCollection<T, I> {
const inital: [I, T][] = [];
for (const [id, item] of this.contents) {
if (predicate(item, id, this)) {
inital.push([id, item]);
}
}
// Filtered check
const check: CheckFunction<T, I> = (collection) =>
Promise.resolve(this.check(this)).then((runs) =>
runs.filter((run) => predicate(run, run.id, collection))
);
return new WatchableCollection(inital, check);
}
</code></pre>
<p>Here is the whole <code>WatchableCollection.ts</code> file, and you can view the rest of the codebase in context on <a href="https://github.com/MayorMonty/robotevents" rel="nofollow noreferrer">GitHub</a>;</p>
<pre><code>/**
* Creates a watchable collection,
* basically an array of contents that can be passed .watch()
* to watch for updates
*
* const teams = await event.teams()
*/
import { EventEmitter } from "events";
interface WatchableCollectionEvents<T> {
add: (item: T) => void;
remove: (item: T) => void;
update: (current: T, old: T) => void;
}
export default interface WatchableCollection<T> {
on<U extends keyof WatchableCollectionEvents<T>>(
event: U,
listener: WatchableCollectionEvents<T>[U]
): this;
once<U extends keyof WatchableCollectionEvents<T>>(
event: U,
listener: WatchableCollectionEvents<T>[U]
): this;
off<U extends keyof WatchableCollectionEvents<T>>(
event: U,
listener: WatchableCollectionEvents<T>[U]
): this;
}
type CheckFunction<T extends { id: I }, I> = (
self: WatchableCollection<T, I>
) => Promise<T[]> | T[];
export default class WatchableCollection<T extends { id: I }, I = number>
extends EventEmitter
implements Map<I, T> {
// Holds all of contents of the collection
private contents: Map<I, T> = new Map<I, T>();
// Polling config
private check: CheckFunction<T, I>;
private interval: NodeJS.Timeout | null = null;
private frequency: number = 30 * 1000;
polling = false;
constructor(inital: [I, T][], check: CheckFunction<T, I>) {
super();
this.contents = new Map(inital);
this.check = check;
}
// Map methods
clear() {
this.contents.clear();
}
delete(id: I) {
if (!this.contents.has(id)) {
throw new Error(
`WatchableCollection does not contain item with id ${id}`
);
}
this.emit("remove", this.contents.get(id) as T);
return this.contents.delete(id);
}
get(id: I) {
return this.contents.get(id);
}
has(id: I) {
return this.contents.has(id);
}
set(id: I, value: T) {
if (this.contents.has(id)) {
this.emit("update", value, this.contents.get(id) as T);
} else {
this.emit("add", value);
}
this.contents.set(id, value);
return this;
}
get size() {
return this.contents.size;
}
forEach(callback: (value: T, key: I, map: Map<I, T>) => void) {
this.contents.forEach(callback);
}
keys() {
return this.contents.keys();
}
values() {
return this.contents.values();
}
entries() {
return this.contents.entries();
}
[Symbol.iterator] = this.entries;
[Symbol.toStringTag] = "WatchableCollection";
// Other utility methods
array(): T[] {
return [...this.contents.values()];
}
idArray(): I[] {
return [...this.contents.keys()];
}
/**
* Returns a new WatchableCollection of the items which pass the filter.
* Note this collection is watchable, and watch events will only be triggered for items that fit the filter function.
*
* @example
* const event = await robotevents.events.get(sku);
* const skills = (await event.skills()).filter(run => run.score > 30);
*
* skills.watch();
* skills.on("add", run => console.log("New run over 30pts", run));
*
* @param predicate
*/
filter(
predicate: (
item: T,
id: I,
collection: WatchableCollection<T, I>
) => boolean
): WatchableCollection<T, I> {
const inital: [I, T][] = [];
for (const [id, item] of this.contents) {
if (predicate(item, id, this)) {
inital.push([id, item]);
}
}
// Filtered check
const check: CheckFunction<T, I> = (collection) =>
Promise.resolve(this.check(this)).then((runs) =>
runs.filter((run) => predicate(run, run.id, collection))
);
return new WatchableCollection(inital, check);
}
/**
* Looks for an item in the collection
* @param predicate
*/
find(
predicate: (
item: T,
id: I,
collection: WatchableCollection<T, I>
) => boolean
): T | undefined {
for (const [id, item] of this.contents) {
if (predicate(item, id, this)) {
return item;
}
}
return undefined;
}
/**
* Checks if some of the elements in the collection pass the criterion
* @param predicate
*/
some(
predicate: (
item: T,
id: I,
collection: WatchableCollection<T, I>
) => boolean
) {
for (const [id, item] of this.contents) {
if (predicate(item, id, this)) {
return true;
}
}
return false;
}
/**
* Checks if every singe one of the elements in the collection pass the criterion
* @param predicate
*/
every(
predicate: (
item: T,
id: I,
collection: WatchableCollection<T, I>
) => boolean
) {
for (const [id, item] of this.contents) {
if (!predicate(item, id, this)) {
return false;
}
}
return true;
}
// Watching
watch(frequency?: number) {
this.polling = true;
if (frequency) {
this.frequency = frequency;
}
this.interval = setInterval(async () => {
const current = new Map(makeMappable<T, I>(await this.check(this)));
// Check for new and updated items
for (const [id, value] of current) {
if (!this.contents.has(id)) {
this.set(id, value);
continue;
}
const old = this.contents.get(id) as T;
if (!eq(value, old)) {
this.set(id, value);
}
}
// Check for removed values
for (const [id, value] of this.contents) {
if (current.has(id)) continue;
this.delete(id);
}
}, this.frequency);
}
unwatch() {
if (!this.polling || !this.interval) {
return;
}
clearInterval(this.interval);
}
/**
* Creates a new watchable collection from a check function
* @param check
*/
static async create<T extends { id: number }>(
check: () => Promise<T[]> | T[]
) {
const inital = makeMappable(await check());
return new WatchableCollection(inital, check);
}
}
function makeMappable<T extends { id: I }, I = number>(values: T[]): [I, T][] {
return Object.entries(values).map(([i, value]) => [value.id, value]);
}
function eq(a: object, b: object): boolean {
for (const [key, value] of Object.entries(a)) {
if (!b.hasOwnProperty(key)) return false;
const compare = (b as any)[key];
switch (typeof compare) {
case "object": {
return eq(value, compare);
}
default: {
if (value !== compare) return false;
}
}
}
return true;
}
</code></pre>
<p>My concerns are twofold:</p>
<ul>
<li>There is a high possibility the original <code>WatchableCollection</code> will go out of scope of the user, however it won't be able to GC'd because the new <code>WatchableCollection</code> is referencing the old collection's check function. The contents of the collection can be fairly large, so this can lead to memory leaks.</li>
<li>Even though polling needs to be activated by the user via <code>.watch()</code>, there is still a possibility that polling is enabled on the old collection via <code>.watch()</code>, and if it went out of scope, the user would have no ability to disable watching. Caching might help mitigate the problems of this, but there is still going to be overhead.</li>
</ul>
<p>Is there a way I can refactor <code>.filter</code> to ensure the old <code>WatchableCollection</code> has all references removed, allowing it to be Garbage Collected?</p>
|
[] |
[
{
"body": "<p>Well you're right to be concerned.</p>\n<p>Your example is essentially this</p>\n<pre><code>function wrapCheck(check) {\n return {\n check,\n largeArr: Array(1000000)\n .fill(0)\n .map((_, i) => i),\n makeNew: function (pred) {\n return wrapCheck(() => check(this).filter(pred));\n }\n };\n}\n\nconst check = (o) => o.largeArr.slice(0, 10);\n\nlet s = wrapCheck(check);\nwhile (true) {\n s = s.makeNew((x) => x % 2 === 0);\n}\n</code></pre>\n<p>Which yes is a memory leak (takes about 20 secs to run out of memory for me).</p>\n<p>I'll confess I haven't fully appreciated your code, but what prevents you from making a new WatchableCollection with just initial, and adding the check on afterwards, now using the reference to your newly made object?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T00:38:16.453",
"Id": "480060",
"Score": "0",
"body": "The main problem lies in the new Collections check function to be reliant on filtering the old function. Because check is making a request against the same endpoint, it may be possible to refactor check to be copied across into the new collection instead. \n\nThe problem lies in the fact the collection check function is reliant on the previous collection. It may be possible to encode check in such a way that check can be copied (as all my check functions right now are just using the same request function).\n\nThanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T22:01:48.310",
"Id": "244533",
"ParentId": "244528",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244533",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T20:24:43.940",
"Id": "244528",
"Score": "2",
"Tags": [
"performance",
"node.js",
"typescript",
"memory-optimization"
],
"Title": "TypeScript: Object Duplication impact on performance"
}
|
244528
|
<p>I'm doing Project Euler problems as a learning platform for Forth. Currently I'm solving Project Euler Problem 8 which involves a 1000-long string, which I entered directly in the <a href="https://github.com/pm62eg/ProjectEuler/blob/977e3a8b94f137b624efa86ed3e5fe218937d93a/forth/p008.fs" rel="nofollow noreferrer">source code</a>.</p>
<p>My questions are:</p>
<ol>
<li>What options are common for dealing with input?</li>
<li>If I put the <code>locals</code> on the stack, won't that make the loop too full of (otherwise unneeded) stack manipulation words?</li>
<li>Suggestions, criticism, nitpicks are welcome...</li>
</ol>
<pre><code>: e008-multNdigits ( a n -- p )
1 swap 0 do swap dup i + c@ [char] 0 - rot * loop nip ;
: euler008
0 13 locals| length maxproduct |
s" 731671765313306249192...450"
( a 1000 )
length - 0 do
dup i + length e008-multNdigits
dup maxproduct > if to maxproduct else drop then
loop maxproduct . ;
</code></pre>
|
[] |
[
{
"body": "<p>Disclaimer: my Forth is extremely rusty.</p>\n<ul>\n<li><p><code>length</code> does not need to be local; is not a variable, it is a constant. Declare it as such:</p>\n<pre><code>13 constant length\n</code></pre>\n</li>\n<li><p>Dealing with input. The stack annotation <code>( a 1000 )</code> strongly hints that what follows wants to be the word on its own. Indeed, logic should be separated from IO. Consider, for example, something along the lines of</p>\n<pre><code>: e008 ( a n -- p)\n ....\n;\n\ns" 731671765313306249192...450"\neuler008\n.\n</code></pre>\n<p>Once the logic and IO are separated, you may use <code>open-file</code> and <code>read-file</code> if you wish.</p>\n</li>\n<li><p>I do not endorse one-liners, especially if they involve loop. Consider</p>\n<pre><code>: e008-multNdigits ( a n -- p )\n 1 swap 0\n do\n swap\n dup i +\n c@ [char] 0 -\n rot *\n loop\n nip ;\n</code></pre>\n<p>As a side note, <code>nip</code> is very rarely useful, and usually it is an indication of the suboptimal design. Try to get rid of it. The nipped value, if I am not mistaken, is a base address of the array. I have an impression that its only purpose is to undo a <code>dup</code> in the caller. Try to get rid of both.</p>\n</li>\n<li><p>The line</p>\n<pre><code> dup maxproduct > if to maxproduct else drop then\n</code></pre>\n<p>is a long way to say</p>\n<pre><code> maxproduct max to maxproduct\n</code></pre>\n</li>\n<li><p>Consider having max product at TOS prior to setting up a call to <code>e008-multNdigits</code>. In this case,</p>\n<pre><code> length - 0 do\n dup i + length e008-multNdigits\n max\n</code></pre>\n<p>would suffice, and eliminate the need for the local.</p>\n</li>\n</ul>\n<hr />\n<p>Not Forth-related issues:</p>\n<ul>\n<li><p>The algorithm performs 13000 multiplications. A sliding window approach lets you get away with 1000 multiplications and 1000 divisions. Of course an extra care should be taken when <code>0</code> is encountered.</p>\n</li>\n<li><p>The product of 13 digits may take as much as 42 bits. A naive multiplication fails on a 32-bit cells.</p>\n</li>\n</ul>\n<hr />\n<p>Finally, Project Euler is not about programming. It is about math. To hone your Forth skills, consider implementing classical algorithms, and benchmark them against conventional implementations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T10:39:16.567",
"Id": "480200",
"Score": "0",
"body": "Thanks a lot for your comments; still working on them. I'm using gforth on a 64-bit Debian: it uses 64-bits cells -- I had checked that earlier."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T05:48:06.047",
"Id": "244599",
"ParentId": "244530",
"Score": "3"
}
},
{
"body": "<p>After @<a href=\"https://codereview.stackexchange.com/users/40480/vnp\">vnp</a>'s suggestions (input separated from logic, locals removed without too many stack manipulations, use MAX word, maximum product on TOS), the code changed to</p>\n<pre><code>s" 731671765313306249192251196744265747423...450"\n 2constant e008-input-string\n\n\\ stack comment legend\n\\ a address; w width, p product, l length, M maxproduct\n\n\\ multiply w consecutive digits from a\n\\ uses w internally but keeps it on stack for next loop\n: e008-multNdigits ( w a -- w p )\n 2dup + 1 rot rot swap \\ ( w 1 w+a a )\n do i c@ [char] 0 - * loop ; \\ keep *ing each digit with the 1\n\n: euler008 ( w a l -- M )\n \\ set up stack\n >r >r 0 over rot r> dup rot - r> + swap ( 0 w a-w+l a )\n do i e008-multNdigits rot max swap\n loop drop ;\n\n\\ run with, eg: 13 e008-input-string euler008 .\n\\ or 2 s" 1111111118761111" euler008 . ==> prints 56\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T16:01:20.260",
"Id": "244618",
"ParentId": "244530",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "244599",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T20:41:08.577",
"Id": "244530",
"Score": "3",
"Tags": [
"beginner",
"forth"
],
"Title": "Project Euler 8: find the maximum product of 13 consecutive digits"
}
|
244530
|
<p>My program makes API requests to Pinnacle Sports to retrieve future events and saves them to the database.</p>
<p><strong>Questions:</strong></p>
<ol>
<li>Do I manage the database resources correctly? It takes about 3 seconds to check whether there are duplicate entries so that apparently it is very inefficient. The previous approach was to have global constants with the database connection and cursor and it worked much faster, though probably not that safe.</li>
<li>Do I handle possible request errors the right way? Some problems that come to my mind: no Internet connection, <code>HTTP</code> error, empty response .</li>
<li>Should I get rid of the raw loop in <code>save_fixtures</code> and to introduce a function for dealing with each league separately?</li>
<li>How can I track the status of a script? At the moment I output everything in the <code>console</code>, though maybe there are more convenient ways for doing that like <code>logging</code> or something.</li>
</ol>
<p><strong>Code:</strong></p>
<p><code>auth.py</code></p>
<pre><code>"Creates signature and headers for interacting with Pinnacle API"
import base64
def create_signature(username, password):
"Given username and password creates base64 encoded signature username:password"
return base64.b64encode(f'{username}:{password}'.encode('utf-8'))
def create_headers(signature):
"Given a signature creates required headers for interacting with Pinnacle API"
return {
'Content-length' : '0',
'Content-type' : 'application/json',
'Authorization' : "Basic " + signature.decode('utf-8')
}
</code></pre>
<p><code>database.py</code></p>
<pre><code>"Functionality for interacting with the database."
import pymysql
from contextlib import contextmanager
SERVER = 'localhost'
USER = 'root'
PASSWORD = ''
DATABASE = 'bets'
@contextmanager
def get_connection():
"Creates database connection."
connection = pymysql.connect(host=SERVER, user=USER, password=PASSWORD, db=DATABASE)
try:
yield connection
finally:
connection.close()
def record_fixture(league_id, fixture):
"Records given fixture to the database."
with get_connection() as con:
with con.cursor() as cursor:
event_id = fixture['id']
starts = fixture['starts'][0:10] # Example: 2019-08-22
home = fixture['home']
away = fixture['away']
sql = "INSERT INTO fixture (event_id, league_id, match_date, \
home_team, away_team) VALUES (%s, %s, %s, %s, %s)"
cursor.execute(sql, (event_id, league_id, starts, home,
away))
con.commit()
def is_duplicated_entry(event_id):
"Returns True if an entry with given event_id already exists"
with get_connection() as con:
with con.cursor() as cursor:
cursor = con.cursor()
sql = "SELECT * from fixture WHERE event_id = %s"
result = cursor.execute(sql, event_id)
return result != 0
</code></pre>
<p><code>get_fixtures.py</code></p>
<pre><code>"""Obtains fixture list from Pinnacle API for the given list of leagues
and records them to the database."""
import json
import datetime
import time
import requests
import auth
import database
LEAGUES = ['1980', '5487', '2436', '5488', '2196', '5490', '1842', '5874',
'2627', '2630', '5452', '6263', '5938']
USERNAME = ""
PASSWORD = ""
SIGNATURE = auth.create_signature(USERNAME, PASSWORD)
HEADERS = auth.create_headers(SIGNATURE)
DELAY = 60
def get_fixtures(leagues):
"Gets fixtures list for the given list of leagues."
url = "https://api.pinnacle.com/v1/fixtures?sportId=29&leagueIds=" + ','.join(leagues)
try:
response = requests.get(url, headers=HEADERS)
except requests.ConnectionError:
print(f"{datetime.datetime.now()} No Internet connection")
return None
except requests.HTTPError:
print(f"{datetime.datetime.now()} An HTTP error occured.")
return None
if response.text == '':
print(f"{datetime.datetime.now()} There are no fixtures available")
return None
fixtures = json.loads(response.text)
return fixtures
def save_fixtures(fixtures):
"Records fixtures to the database and notifies about the new fixtures."
if not fixtures is None:
for league in fixtures['league']:
for fixture in league['events']:
if not database.is_duplicated_entry(fixture['id']):
notify_new_fixture(fixture)
database.record_fixture(league['id'], fixture)
def update_fixtures(leagues, delay=DELAY):
"""
Every DELAY seconds retrieves fixture list for the given leagues
and records them to the database.
"""
while True:
fixtures = get_fixtures(leagues)
save_fixtures(fixtures)
print(f"{datetime.datetime.now()}")
time.sleep(delay)
def notify_new_fixture(fixture):
""" Prints a notification about a new fixture. """
print(f"{datetime.datetime.now()} {fixture['id']} {fixture['home']} - {fixture['away']}")
if __name__ == '__main__':
update_fixtures(LEAGUES, DELAY)
</code></pre>
|
[] |
[
{
"body": "<h2>Type hints</h2>\n<pre><code>def create_signature(username, password):\n</code></pre>\n<p>can be</p>\n<pre><code>def create_signature(username: str, password: str) -> bytes:\n</code></pre>\n<h2>Quote style consistency</h2>\n<p>Pick single or double:</p>\n<pre><code>'Authorization' : "Basic "\n</code></pre>\n<h2>Connection string security</h2>\n<p>Please (please) do not store a password as a hard-coded source global:</p>\n<pre><code>SERVER = 'localhost'\nUSER = 'root'\nPASSWORD = ''\nDATABASE = 'bets'\n</code></pre>\n<p>for so many reasons. At least the password - and often the entire connection string - are externalized and encrypted, one way or another. I had assumed that there are high-quality wallet libraries that can make this safe for you, but have struggled to find one, so I have <a href=\"https://security.stackexchange.com/questions/233825/encryption-not-hashing-of-credentials-in-a-python-connection-string\">asked on Security</a>.</p>\n<h2>A correct context manager!</h2>\n<pre><code>@contextmanager\ndef get_connection():\n</code></pre>\n<p>Thank you! Too bad <code>pymysql</code> didn't bundle this...</p>\n<h2>String continuation</h2>\n<pre><code> sql = "INSERT INTO fixture (event_id, league_id, match_date, \\\n home_team, away_team) VALUES (%s, %s, %s, %s, %s)"\n</code></pre>\n<p>I find more legible as</p>\n<pre><code>sql = (\n "INSERT INTO fixture (event_id, league_id, match_date, "\n "home_team, away_team) VALUES (%s, %s, %s, %s, %s)"\n)\n</code></pre>\n<p>with a bonus being that there won't be stray whitespace from your indentation.</p>\n<h2>Requests sugar</h2>\n<p>This:</p>\n<pre><code>url = "https://api.pinnacle.com/v1/fixtures?sportId=29&leagueIds=" + ','.join(leagues)\n</code></pre>\n<p>should not bake in its query params. Pass those as a dict to requests like this:</p>\n<p><a href=\"https://requests.readthedocs.io/en/master/user/quickstart/#passing-parameters-in-urls\" rel=\"nofollow noreferrer\">https://requests.readthedocs.io/en/master/user/quickstart/#passing-parameters-in-urls</a></p>\n<p>Also, do not call <code>json.loads(response.text)</code>; just use <code>response.json()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T13:25:30.693",
"Id": "480114",
"Score": "0",
"body": "Thanks for the review! Could you provide an example what can be done to avoid storing password as hard-coded source global?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T16:12:22.140",
"Id": "480142",
"Score": "0",
"body": "Regarding your last suggestion: ```response.json``` != ```json.loads(response.text)```, it outputs ```<bound method Response.json of <Response [200]>>```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T16:28:05.070",
"Id": "480144",
"Score": "0",
"body": "Yep; it's a function, it needs to be `json()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T18:15:30.847",
"Id": "480154",
"Score": "0",
"body": "Re. _an example what can be done to avoid storing password as hard-coded source global_, I do not have a good answer, so I have asked: https://stackoverflow.com/questions/62600585/encryption-not-hashing-of-credentials-in-a-python-connection-string"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T18:45:31.227",
"Id": "480157",
"Score": "0",
"body": "Have you already deleted it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T18:48:59.467",
"Id": "480158",
"Score": "0",
"body": "Given you don't have a good answer: did you mean anything specific by saying _There are high-quality wallet libraries that can make this safe for you_?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T19:06:52.630",
"Id": "480161",
"Score": "0",
"body": "I made an assumption that turns out to be non-trivial, so I have edited my answer to link to a subsequent question on Security."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T19:15:37.967",
"Id": "480164",
"Score": "0",
"body": "By the way I store Pinnacle password as a global constant too so maybe the answer will help with this problem as well."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T03:06:18.400",
"Id": "244550",
"ParentId": "244532",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244550",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T21:52:07.047",
"Id": "244532",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"mysql",
"web-scraping",
"database"
],
"Title": "Get future events from Pinnacle API"
}
|
244532
|
<p>This is a Biopython alternative with pretty straightforward code. How can I make this more concise?</p>
<pre><code>def genbank_to_fasta():
file = input(r'Input the path to your file: ')
with open(f'{file}') as f:
gb = f.readlines()
locus = re.search('NC_\d+\.\d+', gb[3]).group()
region = re.search('(\d+)?\.+(\d+)', gb[2])
definition = re.search('\w.+', gb[1][10:]).group()
definition = definition.replace(definition[-1], "")
tag = locus + ":" + region.group(1) + "-" + region.group(2) + " " + definition
sequence = ""
for line in (gb):
pattern = re.compile('[a,t,g,c]{10}')
matches = pattern.finditer(line)
for match in matches:
sequence += match.group().upper()
end_pattern = re.search('[a,t,g,c]{1,9}', gb[-3])
sequence += end_pattern.group().upper()
print(len(sequence))
return sequence, tag
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T02:00:55.087",
"Id": "480064",
"Score": "1",
"body": "@Emma here is an example. 'REGION: 26156329..26157115'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T02:38:32.120",
"Id": "480068",
"Score": "1",
"body": "@Emma Those numbers are not always 8 digits long it depends. Here are the links for the reference I use. https://www.ncbi.nlm.nih.gov/nuccore/NC_000006.12?report=genbank&from=26156329&to=26157115 (GenBank file) https://www.ncbi.nlm.nih.gov/nuccore/NC_000006.12?report=fasta&from=26156329&to=26157115 (FASTA file)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T02:53:23.923",
"Id": "480072",
"Score": "1",
"body": "@Emma that's good to know. My main problem came with the sequence. If the last group of DNA was not a group of 10, my current code will not parse it so I had to write the end_pattern pattern in order to get the last one. I think there is a better way to do it but I'm not sure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T08:01:15.757",
"Id": "480092",
"Score": "0",
"body": "What is the order of the size of the input files? Kilobytes? Gigabytes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T23:25:38.320",
"Id": "480182",
"Score": "0",
"body": "@PeterMortensen I believe it is in kilobytes"
}
] |
[
{
"body": "<h2>Line iteration</h2>\n<pre><code> gb = f.readlines()\n locus = re.search('NC_\\d+\\.\\d+', gb[3]).group()\n region = re.search('(\\d+)?\\.+(\\d+)', gb[2])\n definition = re.search('\\w.+', gb[1][10:]).group()\n\n for line in (gb):\n # ...\n end_pattern = re.search('[a,t,g,c]{1,9}', gb[-3])\n</code></pre>\n<p>can be</p>\n<pre><code>next(f)\ndefinition = re.search('\\w.+', next(f)[10:]).group()\nregion = re.search('(\\d+)?\\.+(\\d+)', next(f))\nlocus = re.search('NC_\\d+\\.\\d+', next(f)).group()\n\ngb = tuple(f)\n\nfor line in gb:\n</code></pre>\n<p>Since you need <code>gb[-3]</code>, you can't get away with a purely "streamed" iteration. You could be clever and keep a small queue of the last few entries you've read, if you're deeply worried about memory consumption.</p>\n<h2>Debugging statements</h2>\n<p>Remove this:</p>\n<pre><code> print(len(sequence))\n</code></pre>\n<p>or convert it to a logging call at the debug level.</p>\n<h2>Compilation</h2>\n<p>Do not do this:</p>\n<pre><code> pattern = re.compile('[a,t,g,c]{10}')\n</code></pre>\n<p>in an inner loop. The whole point of <code>compile</code> is that it can be done once to save the cost of re-compilation; so a safe option is to do this at the global level instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T02:57:48.867",
"Id": "244547",
"ParentId": "244535",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "244547",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T23:05:23.960",
"Id": "244535",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-3.x",
"bioinformatics"
],
"Title": "GenBank to FASTA format using regular expressions without Biopython"
}
|
244535
|
<p><strong>HOW IT WORKS</strong> - When you update a field, all of the fields after it are cleared. (It must work this way to ensure the user fills it out in order. Also a field depends on the value in the previous field)
Each child component has a useEffect which should reset the field if the parent tells it to do so, then tell the parent that it has been reset by setting setClear**** back to false;</p>
<p>I've created a simplified example below, that resembles the structure of a more complicated form I have created in another application.</p>
<p>Although it works, I'm unhappy with how fields are being cleared. I feel that it should be more simple. If my form grows by adding just a single element, for example 'Name', I'd have to add state 'Name', add state for 'clearName', and add another case to my switch statement. To me, I think this is too complex considering my actual application has 8 input fields.</p>
<p>(The child components in the actual application are not as simple and repetitive as they are in this example... this has simplified just to focus on the clearing aspect of the code)</p>
<p>Any suggested improvements for my design structure would be much appreciated!</p>
<p><strong>PARENT COMPONENT</strong></p>
<pre><code>import React, { useState, useEffect } from 'react';
const ParentComponent = () => {
const SPECIES_FIELD = 'speciesField';
const BREED_FIELD = 'breedField';
const COLOR_FIELD = 'colorField';
const ALL = 'all';
const [species, setSpecies] = useState('');
const [breed, setBreed] = useState('');
const [color, setColor] = useState('');
const [clearSpecies, setClearSpecies] = useState('');
const [clearBreed, setClearBreed] = useState('');
const [clearColor, setClearColor] = useState('');
const resetElementsAfter = field => {
switch (field) {
case ALL:
setClearSpecies(true);
setClearBreed(true);
setClearColor(true);
case SPECIES_FIELD:
setClearBreed(true);
setClearColor(true);
break;
case BREED_FIELD:
setClearColor(true);
break;
}
};
return (
<>
<ChooseSpecies changed={val => {resetElementsAfter(SPECIES_FIELD); setSpecies(val);}} clearField={clearSpecies} setClearField={setClearSpecies}/>
<ChooseBreed changed={val => {resetElementsAfter(BREED_FIELD); setBreed(val);}} clearField={clearBreed} setClearField={setClearBreed}/>
<ChooseColor changed={setColor} clearField={clearColor} setClearField={setClearColor}/>
<div>Species: {species}</div>
<div>Breed: {breed}</div>
<div>Color: {color}</div>
<Button onClick={() => resetElementsAfter(ALL)} />
</>
);
}
</code></pre>
<p><strong>CHILD COMP - 1ST FIELD</strong></p>
<pre><code>import React, { useState, useEffect } from 'react';
const ChooseSpecies = ({ changed, clearField, setClearField }) => {
const values = ['Dog', 'Cat'];
const [fieldValue, setFieldValue] = ('');
useEffect(() => {
if(clearField){
changed('');
setFieldValue('');
setClearField(false);
}
}, [clearField]);
const handleChange = e => {
setFieldValue(e.target.value);
changed(e.target.value);
};
<Dropdown values={values} fieldValue={fieldValue} changed={handleChange}/>
}
</code></pre>
<p><strong>CHILD COMP - 2ND FIELD</strong></p>
<pre><code>import React, { useState, useEffect } from 'react';
const ChooseBreed = ({ changed, clearField, setClearField }) => {
const values = [{
Dog: ['Lab', 'Staffie'],
Cat: ['Maine Coone, Sphynx']
}];
const [fieldValue, setFieldValue] = ('');
useEffect(() => {
if(clearField){
changed('');
setFieldValue('');
setClearField(false);
}
}, [clearField]);
const handleChange = e => {
setFieldValue(e.target.value);
changed(e.target.value);
};
<Dropdown values={values} fieldValue={fieldValue} changed={handleChange}/>
}
</code></pre>
<p><strong>CHILD COMP - 3RD FIELD</strong></p>
<pre><code>import React, { useState, useEffect } from 'react';
const ChooseColor = ({ changed, clearField, setClearField }) => {
const values = ['Black', 'White', 'Brown'];
const [fieldValue, setFieldValue] = ('');
useEffect(() => {
if(clearField){
changed('');
setFieldValue('');
setClearField(false);
}
}, [clearField]);
const handleChange = e => {
setFieldValue(e.target.value);
changed(e.target.value);
};
<Dropdown values={values} fieldValue={fieldValue} changed={handleChange}/>
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<p><em>If my form grows .. I'd have to add state ... and add state ... and [add] another case to my switch statement</em></p>\n</blockquote>\n<p>This is a code smell, and not unique to Javascript. This is design problem and the fix has to be at the core of the design - <strong>a JS data structure will fix it</strong>.</p>\n<p><strong>An array of field objects</strong> (in the proper order) will eliminate code proliferation. You will <code>new field()</code> for each actual UI field. Pass constructor parameters for field-specific values.</p>\n<blockquote>\n<p><em>I'm unhappy with how fields are being cleared</em></p>\n</blockquote>\n<p>"change", "set", "clear" are all the same thing. A field cleared in the course of validating - setting state - is the same as setting any value. It is trivial to iterate the collection and set child fields with no regard to field names. NO <code>switch</code> STATEMENT REQUIRED.</p>\n<blockquote>\n<p>Any suggested improvements for my design structure would be much appreciated!</p>\n</blockquote>\n<ul>\n<li><p>Creating data structures significantly cleans up and simplifies code. <em><strong>The data structure is the UI state</strong></em></p>\n</li>\n<li><p>A collection (e.g. array) of same-type objects, scales very well. The more dependencies among UI entries, the more bang for the buck. Hear me now and believe me later!</p>\n</li>\n<li><p>How it works</p>\n<ul>\n<li><p>Populate the data structure from the UI. Include all UI entry values and properties needed for setting visual state, like graying out or hiding.</p>\n</li>\n<li><p>Validate data structure setting its object properties to a valid state.</p>\n</li>\n<li><p>Replace all UI fields/properites from the data structure.</p>\n</li>\n<li><p>Pass all values/properties every time. Never this: "field x was not changed so don't pass it" - irrelevant because the data structure is always evaluated top to bottom and always ends up in a valid state.</p>\n</li>\n</ul>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T01:43:01.967",
"Id": "244594",
"ParentId": "244536",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "244594",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T23:14:49.540",
"Id": "244536",
"Score": "2",
"Tags": [
"javascript",
"react.js"
],
"Title": "Looking for a better way to clear fields in child components"
}
|
244536
|
<p>I have a class that exposes <code>var_dump</code> data in order to get better human readable layout.</p>
<p>I have achieved this with a lot of <code>preg_replace</code> and a series of regular expressions that run one after another. They parse the result of the <code>var_dump</code> to have a more readable and highlighted output.</p>
<p>I would like them to review and verify it in order to optimize it and reduce the code if possible.</p>
<p><strong>Check the Update 1</strong></p>
<p>My code can also be found on <a href="https://github.com/arcanisgk/test-code-style" rel="nofollow noreferrer">GitHub</a>.</p>
<pre><code><?php //this PHP code is old. In the repository is the updated code, see update # 1.
class ClassVarsManager
{
private function GetType($var)
{
if (in_array($var, ['null', 'NULL', null], true)) {
return '(Type of NULL)';
}
if (in_array($var, ['TRUE', 'FALSE', 'true', 'false', true, false], true)) {
return 'boolean';
}
if (is_array($var)) {
return 'array';
}
if (is_object($var)) {
return 'object';
}
if ((int) $var == $var && is_numeric($var)) {
return 'integer';
}
if ((float) $var == $var && is_numeric($var)) {
return 'float';
}
if (strpos($var, 'resource') !== false) {
foreach ($this->GetResourceTypeArray() as $value) {
if (strpos($var, $value) !== false) {
return 'resource (' . $value . ')';
}
}
}
if (strpos($var, '/') !== false) {
if (in_array($var, timezone_identifiers_list())) {
return 'time-zone';
}
}
if (strpos($var, ' ') !== false and strpos($var, ':') !== false) {
$testdate = explode(' ', $var);
if ($this->ValidateDate($testdate[0], false) && $this->ValidateDate($testdate[1], false && strpos($testdate[1], ':') !== false)) {
return 'datetime';
}
}
if ($this->ValidateDate($var, false) and strpos($var, ':') !== false) {
return 'time';
}
if ($this->ValidateDate($var, false) and strlen($var) >= 8) {
return 'date';
}
if (is_string($var)) {
return 'string(' . strlen($var) . ')';
}
}
private function VarExportFormat($var, $highlight = false)
{
ob_start();
var_dump($var);
$var_dump = ob_get_clean();
$var_dump = preg_replace(["/\[\"/", "/\"\]/", "/\]/", "/\[/", "/\)\s*\{(\s*\w*)/", "/(\s*\w*)\}(\s*\w*)/", "/=>\s*(\w)/", "/\[\s*\](,)/", "~^ +~m"], ["'", "'", '', '', ') [$1', '$1],$2', ' => $1', '[]$1', '$0$0'], $var_dump);
$var_dump = preg_split('~\R~', $var_dump);
$var_dump = preg_replace_callback(
'/(\s*=>\s*)(NULL)/',
function ($m) {
return $m[1] . $this->GetType(str_replace("'", '', $m[2])) . ": {$m[2]},";
}, $var_dump
);
$var_dump = preg_replace_callback(
'/(\w+\W\d\W)\s*"([^"]+)"$/',
function ($m) {
return $this->GetType(str_replace("'", '', $m[2])) . ": {$m[2]},";
}, $var_dump
);
$var_dump = preg_replace_callback(
'/\w+\((\D+)\)$/',
function ($m) {
return $this->GetType(str_replace("'", '', $m[1])) . ": {$m[1]},";
}, $var_dump
);
$var_dump = preg_replace_callback(
'/\w+\((\d+)\)$/',
function ($m) {
return $this->GetType(str_replace("'", '', $m[1])) . ": {$m[1]},";
}, $var_dump
);
$var_dump = preg_replace_callback(
'/\w+\((\d*\.\d*)\)$/',
function ($m) {
return $this->GetType(str_replace("'", '', $m[1])) . ": {$m[1]},";
}, $var_dump
);
$var_dump = preg_replace_callback(
'/\w+\(\d+\)(\s*)"([^"]*)"$/',
function ($m) {
return $m[1] . $this->GetType(str_replace("'", '', $m[2])) . ': "' . $m[2] . '",';
}, $var_dump
);
$var_dump = implode(PHP_EOL, $var_dump);
$var_dump = preg_replace("/(NULL)(\r|\n)/", '$1,$2', $var_dump);
$var_dump = preg_replace("/(\w+\s*\[)$/", '$1]', $var_dump);
$var_dump = rtrim($var_dump, ',');
if ($highlight && VERSYSTEM !== 'cli') {
$textvar = highlight_string('<?php ' . PHP_EOL . '/***** Output of Data *****/' . PHP_EOL . $var_dump . ';' . PHP_EOL . '/***** Output of Data *****/' . PHP_EOL . '', true);
$textvar = preg_replace("/\r|\n|<br>/", "", $textvar);
}
return $textvar;
}
public function VarExport($Var, $Var2 = null, $Var3 = null, $Var4 = null, $Var5 = null)
{
echo PRES;
echo $this->VarExportFormat($Var, true) . EOL_SYS;
if (null !== $Var2) {
echo $this->VarExportFormat($Var2, true) . EOL_SYS;
}
if (null !== $Var3) {
echo $this->VarExportFormat($Var3, true) . EOL_SYS;
}
if (null !== $Var4) {
echo $this->VarExportFormat($Var4, true) . EOL_SYS;
}
if (null !== $Var5) {
echo $this->VarExportFormat($Var5, true) . EOL_SYS;
}
echo PREE;
}
public function ValidateDate($date)
{
if (($timestamp = strtotime($date)) != false) {
return true;
} else {
return false;
}
}
}
</code></pre>
<p><strong><strong><strong><strong>UPDATE 1</strong></strong></strong></strong></p>
<p><strong>After the Suggestions and Updates from</strong> <a href="https://codereview.stackexchange.com/users/141885/mickmackusa">mickmackusa</a>.</p>
<p><a href="https://github.com/arcanisgk/test-code-style/blob/master/class/classgen/class-vars.php" rel="nofollow noreferrer">class-vars.php</a></p>
|
[] |
[
{
"body": "<ol>\n<li><p>Unless you have a valuable/deliberate reason to use <code>and</code> in your condition statements, I recommend consistently using <code>&&</code>. Condition logic can sometimes fall prey to <a href=\"https://www.php.net/manual/en/language.operators.precedence.php#117390\" rel=\"nofollow noreferrer\">unintended "precedence" complications</a>.</p>\n</li>\n<li><p>This whole line is "jacked" (wrong / incorrectly coded):</p>\n<pre><code>if ($this->ValidateDate($testdate[0], false) && $this->ValidateDate($testdate[1], false && strpos($testdate[1], ':') !== false)) {\n</code></pre>\n<p><code>ValidateDate()</code> only accepts one parameter, but you are passing two (in several instances to be honest). The second time that you call this method in this line, you omitted a <code>)</code>, so you are effectively doing this:</p>\n<pre><code>$this->ValidateDate(\n $testdate[1],\n false && strpos($testdate[1], ':') !== false // <-- this, of course, will always be false\n // ...not that the 2nd parameter is ever respected by the method\n)\n</code></pre>\n<p>I <em>think</em> you mean to write the following:</p>\n<pre><code>if (strpos($testdate[1], ':') !== false && $this->ValidateDate($testdate[0]) && $this->ValidateDate($testdate[1])) {\n</code></pre>\n</li>\n<li><p>I don't like the body of the <code>ValidateDate()</code> method at all.</p>\n<ul>\n<li>It declares <code>$timestamp</code> but never uses it.</li>\n<li>It does a falsey check on <code>strtotime()</code>'s return value which can technically return 0.</li>\n<li>It uses <code>if</code> and <code>else</code> to explicitly return <code>true</code> and <code>false</code> instead of returning the evaluation itself.</li>\n</ul>\n<p><br>I recommend that you scrap the method entirely and just call <code>strtotime($string) !== false</code>. That said, there are LOADS of strings that <code>strtotime()</code> will deem to be a date and/or time expression, so I don't know if this is the right form of validation -- maybe this is a subjective judgement call -- the decision/power is yours.</p>\n</li>\n<li><p>Regarding this line:</p>\n<pre><code>$var_dump = preg_replace(["/\\[\\"/", "/\\"\\]/", "/\\]/", "/\\[/", "/\\)\\s*\\{(\\s*\\w*)/", "/(\\s*\\w*)\\}(\\s*\\w*)/", "/=>\\s*(\\w)/", "/\\[\\s*\\](,)/", "~^ +~m"], ["'", "'", '', '', ') [$1', '$1],$2', ' => $1', '[]$1', '$0$0'], $var_dump);\n</code></pre>\n<p>It is far beyond <a href=\"https://www.php-fig.org/psr/psr-2/\" rel=\"nofollow noreferrer\">the recommended character width</a>. It will make your script easier to read if you can avoid horizontal scrolling. Write each function parameter on a new line. Better still, write the elements on their own line; not only will this improve readability, it will afford you the space to write inline comments if you wish. Also, the first two patterns are replaced by <code>'</code> so just combine the patterns with a pipe. Same advice with the 3rd and 4th patterns. Something like this:</p>\n<pre><code>$var_dump = preg_replace(\n [\n '/\\["|"]/',\n "/]|\\[/",\n "/\\)\\s*{(\\s*\\w*)/",\n "/(\\s*\\w*)}(\\s*\\w*)/",\n "/=>\\s*(\\w)/",\n "/\\[\\s*](,)/",\n "~^ +~m"\n ],\n [\n "'",\n '',\n ') [$1',\n '$1],$2',\n ' => $1',\n '[]$1',\n '$0$0'\n ],\n $var_dump\n );\n</code></pre>\n</li>\n<li><p>You are writing a battery of <code>preg_replace_callback()</code> calls on <code>$var_dump</code>. Generally speaking this looks like a perfect candidate for <a href=\"https://www.php.net/manual/en/function.preg-replace-callback-array\" rel=\"nofollow noreferrer\"><code>preg_replace_callback_array()</code></a>.</p>\n</li>\n<li><p>I notice that you are making several <code>str_replace()</code> calls in callbacks where the match string cannot possibly have a single quote in it. These needless calls should be removed -- just pass the value to the <code>GetType()</code> method.</p>\n</li>\n<li><p>This replacement:</p>\n<pre><code>preg_replace("/(NULL)(\\r|\\n)/", '$1,$2', $var_dump);\n</code></pre>\n<p>could be written without the captures/references as:</p>\n<pre><code>preg_replace("/NULL\\K(?=\\R)/", ',', $var_dump);\n</code></pre>\n</li>\n<li><p>Pattern&Replacement: <code>"/(\\w+\\s*\\[)$/", '$1]'</code> could be: <code>"/\\w+\\s*\\[$/", '$0]'</code></p>\n</li>\n<li><p><code>"/\\r|\\n|<br>/"</code> can be simplified to <code>"/\\R|<br>/"</code></p>\n</li>\n<li><p>I don't see where constants <code>PRES</code>, <code>PREE</code>, and <code>EOL_SYS</code> are defined.</p>\n</li>\n<li><p>I assume that you have arbitrarily decided to permit a maximum of 5 parameters to be passed into your <code>VarExport()</code> method. You needn't make such a rigid distinction. You can liberate the method and eliminate the battery of <code>null !==</code> checks using the splat operator and some native functions. Check out this <a href=\"https://3v4l.org/OMZaM\" rel=\"nofollow noreferrer\">Demonstration</a>:</p>\n<pre><code>class ClassVarsManager\n{\n private function VarExportFormat($data) {\n return '*' . $data . '*';\n }\n\n public function VarExport(...$var) {\n echo PRES , implode(EOL_SYS, array_map([$this, 'VarExportFormat'], $var)) , PREE;\n }\n}\n\ndefine('PRES', '<pre>');\ndefine('PREE', '</pre>');\ndefine('EOL_SYS', "\\n");\n\n$obj = new ClassVarsManager();\n$obj->VarExport('one', 'two', 'three');\n</code></pre>\n<p>Output:</p>\n<pre><code><pre>*one*\n*two*\n*three*</pre>\n</code></pre>\n</li>\n</ol>\n<p>Finally, I just want to say good work. I know that you have been toiling at this task for a while now. This is such a great way to challenge yourself and learn new skills.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T19:17:02.463",
"Id": "480712",
"Score": "0",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/110103/discussion-on-answer-by-mickmackusa-parse-and-format-var-dump-data-to-become-mor)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T14:34:00.117",
"Id": "244572",
"ParentId": "244540",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244572",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T00:31:37.003",
"Id": "244540",
"Score": "3",
"Tags": [
"performance",
"beginner",
"php",
"object-oriented",
"regex"
],
"Title": "Parse and format var_dump data to become more readable"
}
|
244540
|
<p>I have a lot of nested for loops is there a better way to organize this code? Also the way I add and remove enemies and lazers seems like a bad implementation. I set the index of the table to nil but then that index doesn't get reused when making more lazers/enemies.</p>
<p>Main</p>
<pre><code>require "..libs.vector"
require "..libs.utility"
require "player"
require "enemy"
players = {}
joysticks = love.joystick.getJoysticks()
enemies = {}
function love.load( ... )
love.window.setFullscreen(true)
windowWidth, windowHeight = love.window.getMode()
for _,v in pairs(joysticks) do
local vid,pid,pv = v:getDeviceInfo()
if vid == 1406 and pid == 8201 and pv == 273 then --Do not use wired connection
break
end
table.insert(players,Player(v,windowWidth/2,windowHeight/2,250))
end
table.insert(enemies,Grunt(windowWidth/2,windowHeight/2,players[1]))
table.insert(enemies,Grunt(windowWidth/2 + 30,windowHeight/2,players[1]))
table.insert(enemies,Grunt(windowWidth/2 + 60,windowHeight/2,players[1]))
table.insert(enemies,Grunt(windowWidth/2 + 90,windowHeight/2,players[1]))
table.insert(enemies,Rocket(windowWidth/2,windowHeight/2,math.pi / 2))
table.insert(enemies,Rocket(windowWidth/2 + 30,windowHeight/2,math.pi / 2))
table.insert(enemies,Rocket(windowWidth/2 + 60,windowHeight/2,math.pi / 2))
table.insert(enemies,Rocket(windowWidth/2 + 90,windowHeight/2,math.pi / 2))
table.insert(enemies,Rocket(windowWidth/2 + 120,windowHeight/2,math.pi / 4))
table.insert(enemies,Rocket(windowWidth/2 + 150,windowHeight/2,math.pi / 2))
table.insert(enemies,Rocket(windowWidth/2 + 180,windowHeight/2,math.pi / 2))
end
function love.update(dt)
for _,player in pairs(players) do
player:update(dt)
for i,lazer in ipairs(player.lazers) do
for j,enemy in ipairs(enemies) do
local depth = isCircleCollision(
lazer.position.x,lazer.position.y,lazer.bounds,
enemy.position.x,enemy.position.y,enemy.bounds)
print(depth)
if depth < 30 then
enemy:delete()
table.remove(player.lazers,i)
table.remove(enemies,j)
end
end
end
end
for k,v in pairs(enemies) do
v:update(dt)
end
end
function love.draw()
for _,v in pairs(players) do
v:draw()
end
for k,v in pairs(enemies) do
v:draw()
end
end
</code></pre>
<p>Player</p>
<pre><code>require "..libs.class"
require "..libs.utility"
theta = 0
Lazer = Class("Lazer")
Lazer.isLazer = true
Lazer.count = 0
function Lazer:init(x,y,speed,rax,ray)
self.position = Vector2(x,y)
self.speed = speed
self.velocity = Vector2(rax,ray):unit()
local direction = self.velocity:direction() -- + math.random(-10,10) * math.pi / 180
local magnitude = self.velocity:magnitude()
self.velocity = self.velocity:fromPolar(magnitude,direction)
self.id = Lazer.count
self.bounds = 5
Lazer.count = Lazer.count + 1
end
function Lazer:update(dt,player)
self.position = self.position + self.velocity * self.speed * dt
if not isPointWithinRect(self.position.x,self.position.y,0,0,windowWidth,windowHeight) then
for i,v in ipairs(player.lazers) do
if v.id == self.id then
table.remove(player.lazers,i)
end
end
end
end
function Lazer:draw()
-- love.graphics.setColor(self.position.x/windowWidth,self.position.y/windowHeight,0)
-- love.graphics.setColor(clamp(math.sin(theta),.5,1),clamp(math.cos(theta),.5,1),clamp(math.tan(theta),.5,1))
love.graphics.setColor(255,255,0)
love.graphics.circle("line",self.position.x,self.position.y,self.bounds,5)
end
Lazer.locked = true
Player = Class("Player")
Player.isPlayer = true
function Player:init(joystick,x,y,speed)
self.joystick = joystick
self.position = Vector2(x,y)
self.velocity = Vector2(0,0)
self.speed = speed
self.acceleration = acceleration
self.terminal_velocity = terminal_velocity
self.lazzer_speed = speed + 25
self.lazers = {}
self.bounds = 15
self.lives = 3
self.timer = 0
self.source = love.audio.newSource("res/pew.wav","static")
end
function Player:update(dt)
theta = theta + .05
self.timer = self.timer + dt
local lax,lay = self.joystick:getAxes()
self.velocity.x = lax
self.velocity.y = lay
if math.abs(lax) > .1 or math.abs(lay) > .1 then
self.velocity = self.velocity:unit()
end
self.position = self.position + self.velocity * self.speed * dt
self.position.x = clamp(self.position.x,0 + self.bounds,windowWidth - self.bounds)
self.position.y = clamp(self.position.y,0 + self.bounds,windowHeight - self.bounds)
local _,_,rax,ray = self.joystick:getAxes()
if (math.abs(rax) > .1 or math.abs(ray) > .1) and self.timer > .1 then
table.insert(self.lazers,Lazer(self.position.x,self.position.y,self.speed + 250,rax,ray))
love.audio.play(self.source)
self.timer = 0
end
for _,v in pairs(self.lazers) do
v:update(dt,self)
end
end
function Player:draw()
love.graphics.setColor(255,255,255,255)
love.graphics.circle("line",self.position.x,self.position.y,self.bounds,30)
for _,v in pairs(self.lazers) do
v:draw()
end
end
Player.locked = true
</code></pre>
<p>Enemy</p>
<pre><code>require "..libs.class"
require "..libs.vector"
Enemy = Class("Enemy")
Enemy.isEnemy = true
function Enemy:init(x,y,speed,bounds,color)
self.position = Vector2(x,y)
self.velocity = Vector2(0,0)
self.speed = speed
self.bounds = bounds
self.color = color or {r=255,g=255,b=255}
self.source = love.audio.newSource("res/explosion.wav","static")
end
function Enemy:draw()
love.graphics.setColor(self.color.r,self.color.g,self.color.b)
love.graphics.circle("line",self.position.x,self.position.y,self.bounds,15)
end
function Enemy:delete()
love.audio.play(self.source)
self = nil
end
Enemy.locked = true
Grunt = Class("Grunt",{},Enemy)
Grunt.isGrunt = true
function Grunt:init(x,y,target)
local speed = 100
local bounds = 10
Enemy.init(self,x,y,speed,bounds,{r=0/255,g=255/255,b=255/255})
self.target = target
end
function Grunt:update(dt)
local dx = self.target.position.x - self.position.x
local dy = self.target.position.y - self.position.y
local direction = math.atan2(dy,dx)
self.velocity = self.velocity:fromPolar(self.speed,direction)
self.position = self.position + self.velocity * dt
end
Grunt.locked = true
Rocket = Class("Rocket",{}, Enemy)
Rocket.isRocket = true
function Rocket:init(x,y,direction)
local speed = 175
local bounds = 10
Enemy.init(self,x,y,speed,bounds,{r=255/255,g=165/255,b=0/255})
self.direction = direction
end
function Rocket:update(dt)
if self.position.x + self.bounds + 5 > windowWidth or self.position.y + self.bounds + 1 > windowHeight or self.position.x - self.bounds - 1 < 0 or self.position.y - self.bounds - 5 < 0 then
self.direction = self.direction + math.pi
end
self.velocity = self.velocity:fromPolar(self.speed,self.direction)
self.position = self.position + self.velocity * dt
self.position.x = clamp(self.position.x,0 + self.bounds,windowWidth - self.bounds)
self.position.y = clamp(self.position.y,0 + self.bounds,windowHeight - self.bounds)
end
Rocket.locked = true
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-02T02:49:23.963",
"Id": "480747",
"Score": "0",
"body": "Im using the nata library now. Nata is an entity management system."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T01:19:57.000",
"Id": "244542",
"Score": "2",
"Tags": [
"lua"
],
"Title": "Hairy collision code"
}
|
244542
|
<p>I'm looking for help speeding up some code I'm tinkering with.</p>
<p>The rest of the code, as well as my 'benchmark', can be found <a href="https://github.com/Levalicious/lalloc/tree/0f9ee7d1175d13a7fa75ea6669284bfaaad0848b" rel="nofollow noreferrer">here</a>.</p>
<pre class="lang-c prettyprint-override"><code>
#ifndef LALLOC_H
#define LALLOC_H
#define PAGESIZE (1048576)
#include <stdbool.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <errno.h>
typedef struct bblk bblock;
typedef bblock* bb;
struct bblk {
size_t ind;
bb next;
size_t occ;
char mem[PAGESIZE - (sizeof(size_t) + sizeof(bb) + sizeof(size_t))];
} __attribute__((packed));
typedef struct smmblk memblock;
typedef memblock* mb;
struct smmblk {
mb prev;
mb next;
void* end;
bb bblk;
bool free;
} __attribute__((packed));
size_t bbhdr = (sizeof(size_t) + sizeof(bb) + sizeof(size_t));
bb first;
/**
* @author Lev Knoblock
* @notice Allocates a 'big block' of memory using mmap and inserts 1 'small block' into it
* @dev Consider moving away from 1 page of memory. Maybe larger blocks would be better.
* @param
* @return bblk *
*/
bb bbinit() {
bb out = mmap(NULL, PAGESIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE, -1, 0);
if (out == MAP_FAILED) {
printf("%s", sys_errlist[errno]);
exit(40);
}
/* Big blocks are appended to an append-only linked list.
* Since initially all memory in the block is free, the
* occupancy is set to 0 */
out->next = NULL;
out->occ = 0;
mb t = (mb) out->mem;
/* The internal small block has no predecessors or
* successors, but spans the full block width */
t->prev = NULL;
t->next = NULL;
t->end = out->mem + (PAGESIZE - (sizeof(size_t) + sizeof(bb) + sizeof(size_t)));
t->free = true;
t->bblk = out;
return out;
}
/**
* @author Lev Knoblock
* @notice Allocates a slice of memory by creating an appropriately sized small block in a big block
* @dev Well its somehow slower than the prototype and I swear I knew what was making that one slow
* @param 'big block' to allocate from, size of slice
* @return void* to memory, or NULL if no space was found.
*/
static void* bblkalloc(bb blk, size_t size) {
mb sb = (mb) blk->mem;
/* Find the first free small block */
while (1) {
if (sb->free) break;
tryGetNext:;
if (sb->next == NULL) {
/* Reached end of big block */
return NULL;
}
sb = sb->next;
}
/* Remaining space in small block */
size_t frsize = sb->end - (((void*)sb) + sizeof(memblock));
/* If there isn't enough space to fit a new small block
* find another block that will fit one */
if (frsize < (size + sizeof(memblock))) {
goto tryGetNext;
}
/* Initialize the new small block by stealing
* space from the end of the 'current' small block */
mb nsb = sb->end - (sizeof(memblock) + size);
nsb->prev = sb;
nsb->next = sb->next;
nsb->end = sb->end;
nsb->free = false;
nsb->bblk = blk;
/* Append new small block to list */
sb->end = nsb;
if (sb->next != NULL) sb->next->prev = nsb;
sb->next = nsb;
sb->bblk = blk;
blk->occ++;
/* Return pointer past allocation header */
return ((void*)nsb) + sizeof(memblock);
}
/**
* @author Lev Knoblock
* @notice Allocates a slice of memory from the memory pool
* @dev Currently has no functionality for reducing number of big blocks.
* @param size of slice
* @return void*
*/
void* lalloc(size_t size) {
void* out;
bb curr = first;
unsigned int ind = 0;
do {
if (curr == NULL) {
/* If current big block is null, set it up with its first small block */
curr = bbinit();
curr->ind = ind;
if (ind == 0) first = curr;
}
/*
if (curr->occ) {
curr = curr->next;
ind++;
continue;
}
*/
out = bblkalloc(curr, size);
/* If allocation fails go to the next big block (and allocate it if necessary)
* otherwise, return the valid pointer */
if (out != NULL) return out;
//curr->occ = 1;
curr = curr->next;
ind++;
} while (1);
}
/**
* @author Lev Knoblock
* @notice Frees a slice of memory from the memory pool
* @dev Not really sure how to optimize further.
* @param void* to slice
* @return
*/
void lfree(void* a) {
/* Decrement pointer to get to begining of header */
mb sb = a - sizeof(memblock);
sb->free = true;
if (sb->prev != NULL && sb->prev->free) {
/* If previous block exists and is free, extend it
* to wrap over this one and remove pointers to
* this block header */
sb->prev->end = sb->end;
sb->prev->next = sb->next;
if (sb->next != NULL) sb->next->prev = sb->prev;
/* Replace block pointer on stack */
sb = sb->prev;
}
if (sb->next != NULL && sb->next->free) {
/* If next block exists extend current one over
* it and scrub pointers to it */
sb->end = sb->next->end;
sb->next = sb->next->next;
if (sb->next != NULL) sb->next->prev = sb;
}
/* Decrement occupancy */
sb->bblk->occ--;
}
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T01:32:01.283",
"Id": "480061",
"Score": "0",
"body": "(If I should put an explanation for how it is supposed to work, let me know, I wasn't sure)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T01:33:51.280",
"Id": "480062",
"Score": "0",
"body": "(Also I realize there was a goto in there, I'm sorry, I kind of like goto?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T02:08:04.690",
"Id": "480065",
"Score": "5",
"body": "You don't need to apologise for the `goto`, nor does it bring your question off-topic... but you'll definitely be called out on it during the review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T17:29:11.853",
"Id": "480148",
"Score": "2",
"body": "When adding additional information you should [edit] your question instead of adding a comment. Learn more about comments including when to comment and when not to in [the Help Center page about Comments](https://codereview.stackexchange.com/help/privileges/comment)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T17:00:08.657",
"Id": "480239",
"Score": "1",
"body": "Please clarify the purpose of the code. What made you write this? What was wrong with the tools already available?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T00:46:47.877",
"Id": "480275",
"Score": "1",
"body": "@Mast Mainly, as a learning experience. I wanted to learn about memory allocation, and I thought this would be a fun thing to try instead of copying a design from wikipedia. Most of my code has really no purpose beyond experimenting with something."
}
] |
[
{
"body": "<h2>Variable linkage</h2>\n<pre><code>bb first;\n</code></pre>\n<p>looks like it's in a header file. That means every time you include it from a different module, it will be re-declared with its own separate address. That's unlikely to be what you want. Instead, declare it <code>extern</code>, and then define it once in a C file.</p>\n<p>Beyond that, though: why declare it in the header at all? It's an implementation detail that you shouldn't expose to your users.</p>\n<p>Further, it looks like absolutely everything - including your function bodies - is in the header. Maybe your theory is that inlining everything produces faster code than having a more standard .c/.h layout. If this library is to be included in another project as a .so/.dll there is some non-zero chance that that's the case, but if this library is included in-source with any kind of self-respecting compiler that has whole program optimization, that chance drops to zero. Basically, I would consider this premature optimization and would be surprised if it's worth doing this over having a separated .c that better isolates your design and reduces code re-declaration.</p>\n<h2>Nested includes</h2>\n<p>These:</p>\n<pre><code>#include <stdbool.h>\n#include <stdlib.h>\n#include <sys/mman.h>\n#include <errno.h>\n</code></pre>\n<p>need to be trimmed down to only what's strictly necessary to declare the symbols in your <code>lalloc.h</code>. <code>errno</code> can definitely be removed; <code>stdbool</code> cannot; and I'm unsure about the others. The trimmed includes would be moved to the .c.</p>\n<h2>stderr</h2>\n<pre><code> printf("%s", sys_errlist[errno]);\n</code></pre>\n<p>should likely be <code>fprintf</code>ed to <code>stderr</code> instead. Also, <code>fprintf</code> is not necessary; you can use <code>puts</code>/<code>fputs</code>.</p>\n<h2>Mystery error codes</h2>\n<pre><code> exit(40);\n</code></pre>\n<p>should get a <code>#define</code>.</p>\n<h2>Yes, goto is actually bad</h2>\n<p>This:</p>\n<pre><code>while (1) {\n tryGetNext:;\n // ...\n}\n\nif (frsize < (size + sizeof(memblock))) {\n goto tryGetNext;\n}\n</code></pre>\n<p>just demonstrates that your <code>while</code> has not adequately captured what you're <em>actually</em> looping over. An outer loop should include everything everything up to this <code>goto</code>; the existing <code>while</code> should become an inner loop and the <code>goto</code> should go away.</p>\n<p>An example is:</p>\n<pre><code>size_t frsize;\ndo {\n while (!sb->free) {\n if (sb->next == NULL) {\n /* Reached end of big block */\n return NULL;\n }\n sb = sb->next;\n }\n\n /* Remaining space in small block */\n frsize = sb->end - (((void*)sb) + sizeof(memblock));\n\n /* If there isn't enough space to fit a new small block\n * find another block that will fit one */\n} while (frsize >= size + sizeof(memblock));\n</code></pre>\n<p>It's not strictly equivalent because in the original version you skip a <code>free</code> check under certain conditions. I'm not clear on whether this is a problem.</p>\n<h2>Pointer math</h2>\n<pre><code>size_t frsize = sb->end - (((void*)sb) + sizeof(memblock));\n</code></pre>\n<p>seems a little awkward. Can you not just:</p>\n<pre><code>size_t frsize = (sb->end - sb - 1)*sizeof(memblock);\n</code></pre>\n<p>I'm surprised that the original version - subtracting non-void and void pointers - is even allowed.</p>\n<h2>Forever-loops</h2>\n<p>You mix styles:</p>\n<pre><code>do { } while (1);\n\nwhile (1) { }\n</code></pre>\n<p>I don't love either. The clearest to me is usually <code>while (true) { }</code>, which is possible given that you have <code>stdbool</code>.</p>\n<p>In the first case it shouldn't actually be a <code>while</code> loop;</p>\n<pre><code>unsigned int ind = 0;\ndo {\n ind++;\n} while (1);\n</code></pre>\n<p>I find would be cleaner as</p>\n<pre><code>for (unsigned int ind = 0;; ind++)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T02:52:30.393",
"Id": "480071",
"Score": "0",
"body": "Thank you very much for the reply! I've replaced the do-while loop with a for loop as per your suggestion, along with trimming the includes and getting rid of printf. As for everything being in the header, for me that's simply a prototyping method. It's easy to separate code once its written, but its faster to just write it in one place and then separate it at the end imho. Also, since the question was looking for any advice for performance optimizations, do you have any comments about that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T02:54:04.633",
"Id": "480073",
"Score": "1",
"body": "Unfortunately I do not see any obvious optimizations. Have you profiled?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T03:07:28.717",
"Id": "480075",
"Score": "0",
"body": "I have! Currently almost all of the performance overhead is from the mmap in bbinit. Would mremap be faster if I just expand/contract my memory region?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T09:42:06.033",
"Id": "480100",
"Score": "1",
"body": "The correct way to spell \"forever\" in C is `for (;;)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T11:11:33.423",
"Id": "480104",
"Score": "1",
"body": "@CodyGray : it's a matter of perosnal preference, the for has been long considered such because it was use in a very popluar C book, the author themselves said there was no difference and it's a matter of personnal preference. See the answer there : https://stackoverflow.com/questions/20186809/endless-loop-in-c-c"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T17:09:33.533",
"Id": "480147",
"Score": "1",
"body": "In addition to Reinderen's very excellent input, a doubly-linked list is not _personally_ how I would choose to manage my memory allocations. And the only reason `prev` is there at all, it looks like, is so that you can patch the linked list back together following a deletion? Feh. Use an array as an allocation table, or something. Or maybe one array per `bblk`, fixed-size. The table size will limit the amount of fragmentation any one block can handle, but arguably that's a _feature_ rather than a bug."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T17:50:33.330",
"Id": "480151",
"Score": "0",
"body": "@FeRD - that belongs in a separate answer, perhaps with a little justification."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T23:21:25.447",
"Id": "480181",
"Score": "0",
"body": "@Walfrat That's true: it is a matter of *style*. Therefore, it's a combination of personal preference and also precedent (which dictates familiarity and thus readability). There's a strong precedent for `for (;;)`, even though the various forms are equivalent. I have a strong *personal* preference for `for (;;)`, but that's more because I have a strong personal preference for rewriting *most* loops as `for` loops (which is always possible; `for` and `do`/`while` are just different ways of writing the same thing)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T07:51:00.787",
"Id": "480399",
"Score": "0",
"body": "I do also use for by default and only fallback to while/do while in the case where they're needed. And in fact I might get quite annoyed if I would meet people using while/do..while instead of for (for something else than infinite loop). Because if I see a while, i'm assuming we're doing something else than another simple walking through a collection."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T02:42:26.577",
"Id": "244545",
"ParentId": "244543",
"Score": "5"
}
},
{
"body": "<blockquote>\n<p>... looking for help speeding up some code</p>\n</blockquote>\n<p><strong>Functional concern</strong></p>\n<p>I see no provisional to insure the allocation meets universal alignment as <code>malloc()</code> does. This is a potential fatal error. Also research <code>max_align_t</code>.</p>\n<blockquote>\n<p><code>7.22.3 Memory management functions</code> The pointer returned if the allocation succeeds is\nsuitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement ...</p>\n</blockquote>\n<p>Even super aligning the <code>size</code> a bit more, like to a multiple of 16 or 32 can result in less fragmentation, effecting faster matches after <code>lfree()</code> for later allocations.</p>\n<hr />\n<p>Rest is minor stuff.</p>\n<hr />\n<p><strong>Avoid mis-alignment</strong></p>\n<p>Certainly a pointer and <code>size_t</code> may have the same size and alignment needs, but what if they do not?</p>\n<p>Although a <code>struct *</code> could be narrower on some unicorn platform, the reverse is more likely: the pointer wider and performs better aligned well.</p>\n<pre><code>typedef bblock* bb;\nstruct bblk {\n size_t ind;\n bb next;\n size_t occ;\n char mem[PAGESIZE - (sizeof(size_t) + sizeof(bb) + sizeof(size_t))];\n} __attribute__((packed));\n</code></pre>\n<p>In general, put the widest members first and like with like.</p>\n<pre><code>typedef bblock* bb;\nstruct bblk {\n bb next; // First\n size_t ind;\n size_t occ;\n char mem[PAGESIZE - (sizeof(bb) + sizeof(size_t) + sizeof(size_t))];\n} __attribute__((packed));\n</code></pre>\n<p>In general this applies to <code>struct smmblk</code> too, but only benefits in rare implementations where <code>struct *</code> narrower than <code>void *</code>.</p>\n<pre><code>struct smmblk {\n void* end; // void * certainly widest object point when objects pointer sizes differ.\n mb prev;\n mb next;\n bb bblk;\n bool free;\n} __attribute__((packed));\n</code></pre>\n<p><strong>Set aside <code>packed</code></strong></p>\n<p>It is not portable and tends to make data that is memory space efficient at the cost of speed.</p>\n<p><strong><code>free(NULL)</code> is OK yet not <code>lfree(NULL)</code></strong></p>\n<p>Consider adding an internal <code>NULL</code> test to allow users that same latitude as <code>free()</code>.</p>\n<hr />\n<p><strong>Hiding pointer types</strong></p>\n<p><code>typedef bblock* bb;</code> and later use of <code>bb</code> hides that fact <code>bb</code> is a pointer and makes deciphering the code and ideas for improvements more challenging.</p>\n<p><strong>Avoid UB</strong></p>\n<p><code>void *</code> addition is UB (or IDB) and distracts from performance analysis. Consider <code>unsigned char *</code> or <code>char *</code>.</p>\n<pre><code>// ((void*)sb) + sizeof(memblock)\n((unsigned char*) sb) + sizeof memblock\n\nvoid* a\n// mb sb = a - sizeof(memblock);\n// mb sb = (mb) ((unsigned char *)a - sizeof(memblock));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T03:19:16.980",
"Id": "480076",
"Score": "0",
"body": "I was planning to implement the alignment for allocation at a later point - agree it is important feature. I've also implemented the check for free(NULL). The hidden pointer types are only until I feel that this code is in a decent enough state to separate into a .c/.h file and be 'done' ish. As for the ```packed```, I was going to get rid of it, but when I did, I profiled again and lost some performance. Ideas? I find that very confusing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T03:44:41.467",
"Id": "480077",
"Score": "1",
"body": "@LevKnoblock The performance of allocation is highly dependent on the nature of allocations and free scenarios. A string heavy application vs. a heavy link list versus multi-precision math math can give a inconsistent performance ranking between implementations. \"lost some performance\" sounds too minor. Look to avoiding worst case scenarios (reduce [big O](https://en.wikipedia.org/wiki/Big_O_notation)) and strive for general performance."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T03:04:28.143",
"Id": "244549",
"ParentId": "244543",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T01:20:19.813",
"Id": "244543",
"Score": "4",
"Tags": [
"performance",
"c",
"memory-management"
],
"Title": "Malloc and free"
}
|
244543
|
<p>I've been trying to make a C# version of my <a href="https://codereview.stackexchange.com/questions/244432/java-reflection-based-csv-parser">Java CSV Parser</a> using C# specific idioms.</p>
<p>Here is the full code:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace CSV
{
/// <inheritdoc />
public sealed class ParseException : Exception
{
/// <inheritdoc />
public ParseException()
{
}
/// <inheritdoc />
public ParseException(string message, Exception inner) : base(message, inner)
{
}
}
/// <summary>
/// This Exception is raised when a type <c>T</c> is not supported by <see cref="Convert.ChangeType(object?,Type)"/>
/// nor has a custom parser been registered via <see cref="Parsers.RegisterParser{T}(Converter{string,T})"/> for the type.
/// </summary>
public sealed class NoSuchParserException : Exception
{
/// <inheritdoc />
public NoSuchParserException()
{
}
/// <inheritdoc />
public NoSuchParserException(Type t) : base($"There are no supported parsers for {t}")
{
}
}
/// <summary>
/// This attribute may be applied to any property of a class or struct to indicate that the custom name should
/// be matched against the headers of the CSV file instead of the name of the attribute
/// </summary>
///
/// <example>
/// <c>[CSV.PropertyName("value")] public int Num { get; set; }</c>
/// </example>
[AttributeUsage(AttributeTargets.Property)]
public sealed class PropertyNameAttribute : Attribute
{
/// <summary>
/// The name of the property.
/// </summary>
public string Name { get; }
/// <summary>
/// Initializes a new instance of <see cref="PropertyNameAttribute"/> with the specified property name.
/// </summary>
/// <param name="name">The name of the property.</param>
public PropertyNameAttribute(string name) => Name = name;
}
/// <summary>
/// A struct for accessing the map of parsers used by <see cref="Parser{TRow}"/>
/// </summary>
public readonly struct Parsers
{
internal static readonly Dictionary<Type, Converter<string, object>> Dict =
new Dictionary<Type, Converter<string, object>>();
/// <summary>
/// Globally registers a parser for <typeparamref name="T"/>, overriding any parser which may exist for the type
/// </summary>
/// <param name="parser">a <c>Converter</c> from a string to an arbitrary type <c>T</c></param>
/// <typeparam name="T">a type to make available for parsing into</typeparam>
public static void RegisterParser<T>(Converter<string, T> parser)
{
object CovarianceCaster(string s) => parser(s);
Dict[typeof(T)] = CovarianceCaster;
}
}
/// <summary>
/// This class allows CSV text strings to be conveniently and easily parsed into an Enumerable sequence of objects of type <c>TRow</c>
/// </summary>
///
/// <para>
/// By default, CSV.Parser supports parsing all types supported by <see cref="Convert.ChangeType(object?,Type)"/>
/// Parsers for other types may be added via <see cref="Parsers.RegisterParser{T}(Converter{string,T})"/>.
/// </para>
///
/// <example>
/// Suppose there exists the following struct <c>Foo</c>:
/// <code>
/// public struct Foo
/// {
/// [CSV.PropertyName("Value")] public float X { get; set; }
/// public string Name { get; set; }
/// }
/// </code>
/// Given a <see cref="TextReader"/> whose contents are
/// <code>
/// Name,Value
/// hello,3.14
/// world
/// </code>
/// each line can be parsed into a <c>Foo</c> object using
/// <code>
/// var csv = new CSV.Parser(reader)
/// foreach (var foo in csv) Console.WriteLine(foo);
/// </code>
/// </example>
///
/// <typeparam name="TRow">
/// a type that satisfies the following properties:
/// <list type="bullet">
/// <item>It has a no-argument constructor (satisfies the <c>new()</c> constraint)</item>
/// <item>Any property which should be affected should have an accessor</item>
/// </list>
/// </typeparam>
public class Parser<TRow> : IEnumerable<TRow> where TRow : new()
{
private readonly TextReader _reader;
private readonly string _delimiter;
private readonly List<string> _headers;
/// <summary>
/// Creates a new CSV.Parser instance from the specified <c>reader</c> whose lines may be parsed into <c>TRow</c> instances
/// </summary>
/// <param name="reader">a <c>TextReader</c> containing N lines of text, each line containing M data fields
/// separated by a <c>delimiter</c></param>
/// <param name="delimiter">the delimiter to use</param>
public Parser(TextReader reader, string delimiter = ",")
{
_reader = reader;
_delimiter = delimiter;
_headers = _reader.ReadLine()?.Split(delimiter).ToList();
}
/// <summary>
/// Ignores the specified next number of lines. Useful for possible inclusion of metadata in the CSV data.
/// </summary>
/// <param name="numberOfLines">the number of lines to skip</param>
/// <returns>this CSV.Parser instance</returns>
public Parser<TRow> Skip(int numberOfLines)
{
for (var i = 0; i < numberOfLines; i++) { _reader.ReadLine(); }
return this;
}
/// <summary>
/// Parses the next line of the associated <see cref="TextReader"/> into a <c>TRow</c> object
/// </summary>
/// <returns>The parsed TRow object</returns>
/// <exception cref="ParseException">There is no valid parser for one of the types of the fields of
/// <typeparamref name="TRow"/>, or a parser threw an Exception while parsing</exception>
public TRow ReadLine()
{
var line = _reader.ReadLine();
if (line == null) return default;
var split = line.Split(_delimiter);
object row = new TRow();
foreach (var prop in typeof(TRow).GetProperties().Where(p => p.CanWrite))
{
var attr = prop.GetCustomAttribute<PropertyNameAttribute>();
var name = attr == null ? prop.Name : attr.Name;
var idx = _headers.IndexOf(name);
if (idx >= split.Length) continue;
var parsed = idx == -1 ? null : TryParse(split[idx].Trim(' ', '\"'), prop.PropertyType);
prop.SetValue(row, parsed);
}
return (TRow) row;
}
private static object TryParse(string s, Type t)
{
if (Parsers.Dict.ContainsKey(t))
{
try
{
return Parsers.Dict[t].Invoke(s);
}
catch (Exception e)
{
throw new ParseException($"The parser for {t} failed", e);
}
}
try
{
return s != "" ? Convert.ChangeType(s, t) : null;
}
catch
{
throw new NoSuchParserException(t);
}
}
/// <summary>
/// Returns an <see cref="IEnumerator{T}"/> by repeatedly invoking <see cref="Parser{TRow}.ReadLine()"/>.
/// </summary>
/// <returns>an <see cref="IEnumerator{T}"/> of all the parsed rows</returns>
public IEnumerator<TRow> GetEnumerator()
{
for (var row = ReadLine(); !row.Equals(default(TRow)); row = ReadLine())
{
yield return row;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
</code></pre>
<p>My primary concerns are idiomatically implementing exception handling. In particular, I was wondering if</p>
<ul>
<li><code>NoSuchParserException</code> should be removed and use <code>ParseException</code> as a catch all Exception for the class</li>
<li>my implementation of <code>TryParse</code> could be improved / designed better</li>
</ul>
<p>I was also wondering how I should go about the case where the number of properties in <code>TRow</code> is not equal to the number of headers in the CSV data. I'm not sure if I should ignore the extraneous headers or properties, add an Enum option, or always throw an Exception.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T06:54:25.057",
"Id": "480089",
"Score": "0",
"body": "Sorry but I don't get it. Do you want to port and redesign the CSV parser at the same time? What is your question?"
}
] |
[
{
"body": "<p>The idiomatic <code>TryParse</code> signature is <code>public bool TryParse(string input, out T result)</code>. It should never throw; that's what regular <code>Parse</code> is for. Return <code>true</code> if it succeeds and <code>false</code> otherwise, with <code>result</code> being set to the parsed value or <code>default</code> respectively. If you really do want to distinguish between the cases "there exists a converter but the string simply couldn't be parsed" and "there doesn't even exist a converter for that type", then I suppose you can keep those exceptions, but I'd still like to see some way of indicating whether or not the parse succeeded given there exists a parser for that type. null is not a particularly strong indicator since it's conceivable that someone might want to encode null in their CSV file.</p>\n<p>XML documentation is a good habit to get into so I'm glad to see that. I would add a note to the docs for <code>ReadLine</code> indicating that it'll return <code>default(TRow)</code> when it hits the end of the text reader.</p>\n<p>Which brings me to something that sticks out, and that's the end-of-text-reader condition: your mechanism for that is to return the default value of <code>TRow</code> from <code>ReadLine</code>. What happens if <code>TRow</code> is a value type and I happen to read a line that's intended to populate an instance of <code>TRow</code> with default values? For example, if <code>TRow</code> is <code>Point</code> and my CSV line is <code>0,0</code>, it looks like the parser enumerator will end prematurely. Perhaps <code>ReadLine</code> should return a flag indicating whether something was actually read or not. Or maybe define a <code>TryReadLine</code> in the same manner as <code>TryParse</code> which returns a bool indicating whether it worked.</p>\n<p>You will never need to instantiate <code>Parsers</code> so it should be a <code>static class</code> instead of a <code>readonly struct</code>.</p>\n<p>If you're not using the new C# 8.0 nullable references, then you should be throwing <code>ArgumentNullException</code>s in the Parser constructor if any of those parameters are null.</p>\n<p><code>_headers</code> can be null but you're not checking for null anywhere; although I suppose you can reason that it will always be non-null in the parts where it's actually used, in which case I'd document that with an assertion.</p>\n<p>You will read a lot of wisdom saying that premature optimization is the root of all evil, but here is a case where it's possibly warranted:</p>\n<pre><code>foreach (var prop in typeof(TRow).GetProperties().Where(p => p.CanWrite))\n</code></pre>\n<p>Reflection is super slow and the properties associated with <code>TRow</code> will not change during runtime, so you can cache the result of <code>typeof(TRow).GetProperties()</code>. Likewise for <code>prop.GetCustomAttribute<PropertyNameAttribute>()</code>. It's up to you/your stakeholders whether your current solution is fast enough. If it isn't, look into caching those things.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T15:09:41.443",
"Id": "244836",
"ParentId": "244544",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T01:25:19.867",
"Id": "244544",
"Score": "3",
"Tags": [
"c#",
"parsing",
"error-handling",
"csv",
"reflection"
],
"Title": "C# Reflection-based CSV Parser"
}
|
244544
|
<p>I have written a method which will return the size 16 List every time. If the input List has size less than 16, the remaining list object will be filled with default values. Is there any way to remove the if and for condition from the <code>enrichAddress</code> method?.</p>
<pre><code>@Component
public class TestService{
public List<TestB> enrichAddress(List<TestA> cardAccountDetails) {
if (CollectionUtils.isEmpty(cardAccountDetails)) return Collections.emptyList();
List<TestB> testBList = cardAccountDetails.stream().map(AccountService::buildAddress).collect(Collectors.toList());
if (testBList.size() < 16) {
int accountCounts = testBList.size();
for (; accountCounts < 16; accountCounts++) {
testBList.add(buildDefaultAddress());
}
}
return testBList;
}
private TestA buildDefaultAddress() {
TestA testA = new TestA();
testA.setA("NONE");
testA.setAccS("TEST_STATUS");
testA.setAccT("TEST_ACCOUNT_TYPE");
testA.setADes("");
return testA;
}
private static TestA buildAddress(TestB testB) {
TestA testA = new TestA();
testA.setDes(testB.getDes());
testA.setAcc(testB.getAcN());
testA.setAccSt(testB.getAccS());
testA.setAccT(testB.getAcCT());
testA.setAc(testB.getAct());
return testA;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T05:01:33.453",
"Id": "480080",
"Score": "2",
"body": "\"if\": just leave it out, then the loop will iterate 0 times. \"for\": not without making the code an unreadable mess."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T06:43:33.610",
"Id": "480086",
"Score": "0",
"body": "aside - you are not really handling the more than 16 cases either, related to a stricter requirement *return the size 16 List every time*"
}
] |
[
{
"body": "<p>As mtj already mentioned in the comment, adding stream trickery to fulfill this need only makes the code less readable. Streams are nifty, exciting and popular but they are not always the right tool for the job. Sometimes a plain loop is still the best choice.</p>\n<p>The common pattern in padding a collection (well, most often it's a string that gets padded) to certain size is to use a while loop. It has least amount of excess variables and code and the syntax communicates intent quite naturally ("while size is less than 16, do this"). But this still only tells that you are intentionally padding the collection to 16 elements. You also need to document in comments the reason <em>why</em> you are padding the collection to 16 elements.</p>\n<pre><code>List<Address> addresses = cardAccountDetails\n .stream()\n .map(AccountService::buildAddress)\n .collect(Collectors.toList());\n\nwhile (addresses.size() < 16) {\n addresses.add(buildDefaultAddress());\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T05:53:17.010",
"Id": "244554",
"ParentId": "244548",
"Score": "3"
}
},
{
"body": "<p>While I do agree with the others that a loop is the simpler solution in this situation, I'd nevertheless like demonstrate a <code>Stream</code> solution, because IMO the noted disadvantages are not due to streams and functional programming in general, but due to Java's limited concept and implementations of streams.</p>\n<p>A functional way would be extend the stream of converted addresses with an "infinite" stream of default addresses and then cut that stream off at 16:</p>\n<pre><code>Stream<Address> addressStream = cardAccountDetails.stream().map(AccountService::buildAddress);\nStream<Address> defaultAddressStream = Stream.generate(AccountService::buildDefaultAddress);\n\nreturn Stream.concat(addressStream, defaultAddressStream).limit(16).collect(Collectors.toList());\n</code></pre>\n<p>If you are interested in more realistic functional programming you could try one of several functional libraries which allow a more concise and readable syntax. For example with <a href=\"https://vavr.io\" rel=\"nofollow noreferrer\">vavr.io</a>:</p>\n<pre><code>return Stream.ofAll(cardAccountDetails) // Creates a io.vavr.collections.Stream\n .map(AccountService::buildAddress)\n .extend(AccountService::buildDefaultAddress)\n .take(16)\n .collect(Collectors.toList()); // Converts back to a regular Java List \n</code></pre>\n<p>Instead of converting back to a Java <code>List</code> you could just use vavr colletions through out your project.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T09:04:15.390",
"Id": "244604",
"ParentId": "244548",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244554",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T03:00:33.130",
"Id": "244548",
"Score": "3",
"Tags": [
"java",
"stream",
"hash-map"
],
"Title": "Set default value for remaining size of list by use of Java 8 and Stream"
}
|
244548
|
<p>I have design a model for product apps. This is the first time I am trying to create a product's database schema and then model it in Django. My code handles the following:</p>
<ol>
<li>A product type can have multiple products and each product type can have certain attributes in common. Examples of product types can be clothing, accessories and bags.</li>
<li>A product can have zero or more attributes, like color, size and material.</li>
<li>Each attribute will have multiple values.</li>
<li>A product can have multiple combination of variants and each variant has their own stock quantity and price.</li>
</ol>
<pre><code>from django.db import models
from django.utils.text import slugify
from mptt.managers import TreeManager
from mptt.models import MPTTModel
class ProductType(models.Model):
name = models.CharField(max_length=150, help_text="type of product. ex - accessories, clothing")
slug = models.SlugField(max_length=150, unique=True)
is_shipping_required = models.BooleanField(default=True)
class Meta:
ordering = ("slug",)
app_label = "product"
def __str__(self):
return self.name
class Category(MPTTModel):
name = models.CharField(max_length=128)
slug = models.SlugField(max_length=128)
description = models.TextField(blank=True)
# description_json = JSONField(blank=True, default=dict)
parent = models.ForeignKey(
"self", null=True, blank=True, related_name="children", on_delete=models.CASCADE
)
objects = models.Manager()
tree = TreeManager()
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
def __str__(self):
return self.name
class Product(models.Model):
product_type = models.ForeignKey(
ProductType, related_name="products", on_delete=models.CASCADE
)
name = models.CharField(max_length=128)
slug = models.SlugField()
description = models.TextField(blank=True)
category = models.ForeignKey(
Category,
related_name="products",
on_delete=models.SET_NULL,
null=True,
blank=True,
)
article_number = models.CharField(max_length=30)
class Meta:
verbose_name = "product"
verbose_name_plural = "products"
ordering = ("name",)
constraints = [
models.UniqueConstraint(
fields=["article_number", "slug"], name="unique article number and slug")
]
def __str__(self):
return f'{self.name} - {self.article_number}'
class Attribute(models.Model):
name = models.CharField(max_length=200, blank=True)
description = models.TextField(blank=True)
def __str__(self):
return self.name
class AttributeValue(models.Model):
attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE)
value = models.CharField(max_length=200, blank=True)
description = models.TextField(blank=True)
def __str__(self):
return self.value
class ProductAttributeValue(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
attribute_value = models.ForeignKey(AttributeValue, on_delete=models.CASCADE)
class ProductTypeAttributeValue(models.Model):
product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE)
attribute_value = models.ForeignKey(AttributeValue, on_delete=models.CASCADE)
class ProductVariant(models.Model):
sku = models.CharField(max_length=255, unique=True)
name = models.CharField(max_length=255, blank=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
track_inventory = models.BooleanField(default=True)
def __str__(self):
return self.sku
class ProductVariantValues(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
variant = models.ForeignKey(ProductVariant, on_delete=models.CASCADE)
value = models.ForeignKey(ProductAttributeValue, on_delete=models.CASCADE)
stock = models.PositiveIntegerField(default=0)
price = models.DecimalField(decimal_places=2, max_digits=6)
class CollectionProduct(models.Model):
collection = models.ForeignKey(
"Collection", related_name="collectionproduct", on_delete=models.CASCADE
)
product = models.ForeignKey(
Product, related_name="collectionproduct", on_delete=models.CASCADE
)
class Meta:
unique_together = (("collection", "product"),)
def get_ordering_queryset(self):
return self.product.collectionproduct.all()
class Collection(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=255, unique=True)
products = models.ManyToManyField(
Product,
blank=True,
related_name="collections",
through=CollectionProduct,
through_fields=("collection", "product"),
)
description = models.TextField(blank=True)
class Meta:
ordering = ("slug",)
def __str__(self):
return self.name
</code></pre>
<p>Due to my lack of experience with databases I am not quite sure if the design is sound. Can anyone verify if there is any room for improvement for the relationships between product, product variants and attributes? I especially would like to see how how it can be designed in a better way. For example relationships, like <code>ForeignKey</code> or <code>ManyToManyField</code>, normalization, query complexity and scalability.</p>
<p>Update</p>
<p>I have this on repl as well</p>
<p><a href="https://repl.it/@tushantk/HumiliatingInterestingMarketing#product/models.py" rel="nofollow noreferrer">https://repl.it/@tushantk/HumiliatingInterestingMarketing#product/models.py</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T20:35:12.337",
"Id": "480173",
"Score": "0",
"body": "Please include your `import`s"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T00:22:17.380",
"Id": "480183",
"Score": "0",
"body": "@Reinderien. Thanks for your comment. I have included the import's and also the link where I have this code running."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T08:30:23.643",
"Id": "244556",
"Score": "3",
"Tags": [
"python",
"database",
"django"
],
"Title": "Product inventory database with attributes and variants"
}
|
244556
|
<p>Is there a better way to transform some expression to AST using Boost.Spirit?
I have built it, but I think it's messy and can be simplified a lot.
Code is also available on <a href="https://godbolt.org/z/VXHXLY" rel="noreferrer">Godbolt</a>.</p>
<pre><code>#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
namespace ast {
struct unary_operator;
struct binary_operator;
struct expression {
typedef boost::variant<
double,
std::string,
boost::recursive_wrapper<unary_operator>,
boost::recursive_wrapper<binary_operator>,
boost::recursive_wrapper<expression>
> type;
expression() {
}
template<typename Expr>
expression(const Expr &expr)
: expr(expr) {
}
expression &operator+=(expression rhs);
expression &operator-=(expression rhs);
expression &operator*=(expression rhs);
expression &operator/=(expression rhs);
expression &and_(expression rhs);
expression &or_(expression rhs);
expression &equals(expression rhs);
expression &not_equals(expression rhs);
expression &less_than(expression rhs);
expression &less_equals(expression rhs);
expression &greater_than(expression rhs);
expression &greater_equals(expression rhs);
expression &factor(expression rhs);
expression &dot(expression rhs);
type expr;
};
struct unary_operator {
std::string op;
expression rhs;
unary_operator() {}
unary_operator(std::string op, expression rhs)
: op(std::move(op)), rhs(std::move(rhs)) {
}
};
struct binary_operator {
std::string op;
expression lhs;
expression rhs;
binary_operator() {}
binary_operator(std::string op, expression lhs, expression rhs)
: op(std::move(op)), lhs(std::move(lhs)), rhs(std::move(rhs)) {
}
};
expression &expression::operator+=(expression rhs) {
expr = binary_operator("+", std::move(expr), std::move(rhs));
return *this;
}
expression &expression::operator-=(expression rhs) {
expr = binary_operator("-", std::move(expr), std::move(rhs));
return *this;
}
expression &expression::operator*=(expression rhs) {
expr = binary_operator("*", std::move(expr), std::move(rhs));
return *this;
}
expression &expression::operator/=(expression rhs) {
expr = binary_operator("/", std::move(expr), std::move(rhs));
return *this;
}
expression &expression::and_(expression rhs) {
expr = binary_operator("&&", std::move(expr), std::move(rhs));
return *this;
}
expression &expression::or_(expression rhs) {
expr = binary_operator("||", std::move(expr), std::move(rhs));
return *this;
}
expression &expression::equals(expression rhs) {
expr = binary_operator("==", std::move(expr), std::move(rhs));
return *this;
}
expression &expression::not_equals(expression rhs) {
expr = binary_operator("!=", std::move(expr), std::move(rhs));
return *this;
}
expression &expression::less_than(expression rhs) {
expr = binary_operator("<", std::move(expr), std::move(rhs));
return *this;
}
expression &expression::less_equals(expression rhs) {
expr = binary_operator("<=", std::move(expr), std::move(rhs));
return *this;
}
expression &expression::greater_than(expression rhs) {
expr = binary_operator(">", std::move(expr), std::move(rhs));
return *this;
}
expression &expression::greater_equals(expression rhs) {
expr = binary_operator(">=", std::move(expr), std::move(rhs));
return *this;
}
expression &expression::factor(expression rhs) {
expr = binary_operator("**", std::move(expr), std::move(rhs));
return *this;
}
expression &expression::dot(expression rhs) {
expr = binary_operator(".", std::move(expr), std::move(rhs));
return *this;
}
struct printer {
void operator()(const double n) const {
std::cout << n;
}
void operator()(const std::string &s) const {
std::cout << s;
}
void operator()(const expression &ast) const {
boost::apply_visitor(*this, ast.expr);
}
void operator()(const binary_operator &expr) const {
std::cout << "op:" << expr.op << "(";
boost::apply_visitor(*this, expr.lhs.expr);
std::cout << ", ";
boost::apply_visitor(*this, expr.rhs.expr);
std::cout << ')';
}
void operator()(const unary_operator &expr) const {
std::cout << "op:" << expr.op << "(";
boost::apply_visitor(*this, expr.rhs.expr);
std::cout << ')';
}
};
struct operators {
struct and_ {
};
struct or_ {
};
struct equals {
};
struct not_equals {
};
struct less_than {
};
struct less_equals {
};
struct greater_than {
};
struct greater_equals {
};
struct factor {
};
struct dot {
};
expression &operator()(expression &lhs, expression rhs, and_) const {
return lhs.and_(std::move(rhs));
}
expression &operator()(expression &lhs, expression rhs, or_) const {
return lhs.or_(std::move(rhs));
}
expression &operator()(expression &lhs, expression rhs, equals) const {
return lhs.equals(std::move(rhs));
}
expression &operator()(expression &lhs, expression rhs, not_equals) const {
return lhs.not_equals(std::move(rhs));
}
expression &operator()(expression &lhs, expression rhs, less_than) const {
return lhs.less_than(std::move(rhs));
}
expression &operator()(expression &lhs, expression rhs, less_equals) const {
return lhs.less_equals(std::move(rhs));
}
expression &operator()(expression &lhs, expression rhs, greater_than) const {
return lhs.greater_than(std::move(rhs));
}
expression &operator()(expression &lhs, expression rhs, greater_equals) const {
return lhs.greater_equals(std::move(rhs));
}
expression &operator()(expression &lhs, expression rhs, factor) const {
return lhs.factor(std::move(rhs));
}
expression &operator()(expression &lhs, expression rhs, dot) const {
return lhs.dot(std::move(rhs));
}
};
}
namespace qi = boost::spirit::qi;
struct expectation_handler {
template<typename Iterator>
void operator()(Iterator first, Iterator last, const boost::spirit::info &info) const {
std::stringstream msg;
msg << "Expected " << info << " at \"" << std::string(first, last) << "\"";
throw std::runtime_error(msg.str());
}
};
template<typename Iterator>
struct grammar : qi::grammar<Iterator, ast::expression(), qi::ascii::space_type> {
grammar()
: grammar::base_type(expression) {
variable = qi::lexeme[qi::alpha >> *(qi::alnum | '_')];
expression = logical.alias() > qi::eoi;
logical = equality[qi::_val = qi::_1]
>> *(
((qi::lit("&&") > equality[op(qi::_val, qi::_1, ast::operators::and_{})]) |
(qi::lit("||") > equality[op(qi::_val, qi::_1, ast::operators::or_{})]))
);
equality = relational[qi::_val = qi::_1]
>> *(
((qi::lit("==") > relational[op(qi::_val, qi::_1, ast::operators::equals{})]) |
(qi::lit("!=") > relational[op(qi::_val, qi::_1, ast::operators::not_equals{})]))
);
relational = additive[qi::_val = qi::_1]
>> *(
((qi::lit("<") > relational[op(qi::_val, qi::_1, ast::operators::less_than{})]) |
(qi::lit("<=") > relational[op(qi::_val, qi::_1, ast::operators::less_equals{})]) |
(qi::lit(">") > relational[op(qi::_val, qi::_1, ast::operators::greater_than{})]) |
(qi::lit(">=") > relational[op(qi::_val, qi::_1, ast::operators::greater_equals{})]))
);
additive = multiplicative[qi::_val = qi::_1]
>> *(
((qi::lit("+") > multiplicative[qi::_val += qi::_1]) |
(qi::lit("-") > multiplicative[qi::_val -= qi::_1]))
);
multiplicative = factor[qi::_val = qi::_1]
>> *(
((qi::lit("*") > factor[qi::_val *= qi::_1]) |
(qi::lit("/") > factor[qi::_val /= qi::_1]))
);
factor = primary[qi::_val = qi::_1]
>> *((qi::lit("**")) > primary[op(qi::_val, qi::_1, ast::operators::factor{})]);
primary =
qi::double_[qi::_val = qi::_1]
| ('(' > expression[qi::_val = qi::_1] > ')')
>> *(qi::char_('.') > variable[qi::_val = op(qi::_val, qi::_1, ast::operators::dot{})])
| variable[qi::_val = qi::_1]
>> *(qi::char_('.') > variable[qi::_val = op(qi::_val, qi::_1, ast::operators::dot{})]);
qi::on_error<qi::fail>(
expression,
boost::phoenix::bind(boost::phoenix::ref(err_handler), qi::_3, qi::_2, qi::_4));
}
qi::rule<Iterator, ast::expression(), qi::ascii::space_type> expression, logical, equality, relational, additive, multiplicative, factor, unary, binary, primary;
qi::rule<Iterator, std::string()> variable;
boost::phoenix::function<ast::operators> op;
expectation_handler err_handler;
};
int main(int argc, const char *argv[]) {
std::string input("2 + 5 + t.a");
auto it_begin(input.begin()), it_end(input.end());
grammar<decltype(it_begin)> parser;
ast::expression expression;
qi::phrase_parse(it_begin, it_end, parser, qi::ascii::space, expression);
ast::printer printer;
printer(expression);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T01:58:53.720",
"Id": "480184",
"Score": "0",
"body": "I have always preferred Lex/yacc the syntax seems a lot cleaner."
}
] |
[
{
"body": "<p>I'll narrate this in the order I "discover" your code. Then I'll present some tweaks which I think mattered the most in the end.</p>\n<p>I'm liking a lot of what you've done.</p>\n<ol>\n<li><p>A few names could (should?) be improved. E.g. <code>ast::operators</code> does nothing to suggest its purpose. It's a lazy factory for binary operator expressions.</p>\n<p>So, name it <code>make_binary</code> or similar.</p>\n<p>Same with the <code>phoenix::function<></code> wrapper that wraps it. <code>op</code> in the semantic action doesn't express what happens there very well.</p>\n</li>\n<li><p>Instead of having the <code>op</code> (alias <code>make_binary</code>) actor be side-effectful on the _val argument, consider making it return a different value. Then everything can become immutable and the semantic action better expresses intent:</p>\n<pre><code>rule = expr [ _val = foo(_val, _1, _2, _3) ];\n</code></pre>\n<p>Expresses that _val is updated to something created from the given parameters.</p>\n</li>\n<li><p>At the level of the grammar, things don't look "tidy". A lot of it could be improved by simply <code>using namespace qi::labels</code>, and getting rid of redundant <code>qi::lit()</code> wrappers, which changes e.g.</p>\n<pre><code>logical = equality[qi::_val = qi::_1]\n >> *(\n ((qi::lit("&&") > equality[op(qi::_val, qi::_1, ast::operators::and_{})]) |\n (qi::lit("||") > equality[op(qi::_val, qi::_1, ast::operators::or_{})]))\n );\n</code></pre>\n<p>into</p>\n<pre><code>using ast::operators;\nusing namespace qi::labels;\n\nlogical = equality[_val = _1]\n >> *(\n (("&&" > equality[op(_val, _1, operators::and_{})]) |\n ("||" > equality[op(_val, _1, operators::or_{})]))\n );\n</code></pre>\n</li>\n<li><p>You check for <code>eoi</code> in your grammar (Good for you!). However, it's put inside a recursed rule:</p>\n<pre><code>expression = logical.alias() > qi::eoi;\n</code></pre>\n<p>This means that <code>(a+b)*3</code> would never parse, because <code>)</code> is found where <code>eoi</code> is required. Fix it by putting <code>eoi</code> on the top level.</p>\n</li>\n<li><p>You have a skipper at the grammar level, which means people have to pass in the correct skipper. If they don't, they can wreck the grammar. Instead, make the skipper internal so you control it, and the interface is easier to use (correctly):</p>\n<pre><code>start = qi::skip(qi::ascii::space) [ expression ];\n</code></pre>\n<p>Usage:</p>\n<pre><code>if (qi::parse(it_begin, it_end, parser, expression)) {\n</code></pre>\n<p>Or perhaps:</p>\n<pre><code>if (qi::parse(it_begin, it_end, parser > qi::eoi, expression)) {\n</code></pre>\n</li>\n<li><p>I realize that the driver code (<code>main</code>) might be out of scope for your review, but I'll show you the missing error-handling, because it can be pretty subtle w.r.t. partial parses:</p>\n<pre><code>int main() {\n ast::printer printer;\n grammar<std::string::const_iterator> parser;\n\n for (std::string const input : {\n "2 + 5 + t.a",\n "(2 + 5) + t.a", // note the removed eoi constraint\n "2 + 5 * t.a",\n "2 * 5 - t.a",\n "partial match",\n "uhoh *",\n })\n try {\n std::cout << "----- " << std::quoted(input) << " ---- \\n";\n auto it_begin(input.begin()), it_end(input.end());\n\n ast::expression expression;\n if (qi::parse(it_begin, it_end, parser, expression)) {\n printer(expression);\n std::cout << std::endl;\n } else {\n std::cout << "Not matched\\n";\n }\n\n if (it_begin != it_end) {\n std::string tail(it_begin, it_end);\n std::cout << "Remaining unparsed input: " << std::quoted(tail) << "\\n";\n }\n } catch(std::exception const& e) {\n std::cout << "Exception: " << std::quoted(e.what()) << "\\n";\n }\n}\n</code></pre>\n</li>\n<li><p>Note that the expectations will not give useful messages unless you named your rules.</p>\n<pre><code>Exception: Expected <unnamed-rule> at ""\n</code></pre>\n<p>The idiomatic way to name them is to use the DEBUG macros:</p>\n<pre><code>BOOST_SPIRIT_DEBUG_NODES(\n (start)\n (expression)(logical)(equality)\n (relational)(additive)(multiplicative)\n (factor)(unary)(binary)(primary)\n (variable)\n )\n</code></pre>\n<p>Now:</p>\n<pre><code>Exception: Expected <factor> at ""\n</code></pre>\n<blockquote>\n<p>Intermission: superficial changes to here: <strong><a href=\"http://coliru.stacked-crooked.com/a/be341801f70758e1\" rel=\"nofollow noreferrer\">Live On Coliru</a></strong></p>\n</blockquote>\n</li>\n<li><p>In the printer there's a lot of repetition (<code>apply_visitor(*this</code>...) and it's slightly less than readable due to <code>operator()</code>. My preference is to relay to a <code>call</code> or <code>apply</code> function</p>\n</li>\n<li><p>Also in the printer, don't hardcode the output stream. One day(TM) you will want to format to a string. Or <code>std::cerr</code>, or a file</p>\n<blockquote>\n<p>Combining these notes on the printer: <strong><a href=\"http://coliru.stacked-crooked.com/a/3d0a027e41d2a8b8\" rel=\"nofollow noreferrer\">Live On Coliru</a></strong></p>\n<pre><code>struct printer {\n std::ostream& _os;\n\n template <typename T> std::ostream& operator()(T const& v) const\n { return call(v); }\n\n private:\n std::ostream& call(expression const& ast) const {\n return boost::apply_visitor(*this, ast.expr);\n }\n\n std::ostream& call(binary_operator const& expr) const {\n _os << "op:" << expr.op << "(";\n call(expr.lhs) << ", ";\n return call(expr.rhs) << ')';\n }\n\n std::ostream& call(unary_operator const& expr) const {\n _os << "op:" << expr.op << "(";\n return call(expr.rhs) << ')';\n }\n\n template <typename Lit>\n std::ostream& call(Lit const& v) const { return _os << v; }\n};\n</code></pre>\n</blockquote>\n</li>\n<li><p>The logical extension of this is to make it an actual <a href=\"https://en.cppreference.com/w/cpp/io/manip\" rel=\"nofollow noreferrer\">output manipulator</a>:</p>\n<pre><code> std::cout << "Parsed: " << fmt_expr{expression} << std::endl;\n</code></pre>\n<blockquote>\n<p>Again, <strong><a href=\"http://coliru.stacked-crooked.com/a/6fa6027d9de65693\" rel=\"nofollow noreferrer\">Live On Coliru</a></strong>, also simplified the <code>printer</code> visitor again:</p>\n<pre><code>std::ostream& call(binary_operator const& expr) const {\n return _os\n << "op:" << expr.op\n << "(" << fmt_expr{expr.lhs}\n << ", " << fmt_expr{expr.rhs} << ')';\n}\n</code></pre>\n</blockquote>\n</li>\n<li><p>In the AST you store the actual operator dynamically, as a string. It seems to me that there is not a lot of value to encode the operator statically just for all the ast-building overloads (<code>ast::operator::operator()</code> as well as all the delegated members of <code>ast::expr</code>). Instead, just pass a string everytime?</p>\n<p>Now the builder namespace can vanish, the asymmetrical factory members, and the whole phoenix function is grammar-local:</p>\n<pre><code>struct make_binary_f {\n ast::binary_operator operator()(ast::expression lhs, ast::expression rhs, std::string op) const {\n return { op, lhs, rhs };\n }\n};\nboost::phoenix::function<make_binary_f> make;\n</code></pre>\n<blockquote>\n<p>Another in-between station <strong><a href=\"http://coliru.stacked-crooked.com/a/21fd38b724e13fc1\" rel=\"nofollow noreferrer\">Live On Coliru</a></strong></p>\n<h3>ACHIEVEMENT UNLOCKED</h3>\n<p>Code down 113 lines of code (now 218 instead of 331 lines of code)</p>\n</blockquote>\n</li>\n<li><p>Random spot:</p>\n<pre><code>variable = qi::lexeme[qi::alpha >> *(qi::alnum | '_')];\n</code></pre>\n<p><code>'_'</code> is equivalent to <code>qi::lit('_')</code>, not <code>qi::char_('_')</code> so this would remove all underscores. Either use the char_, or use <code>raw[]</code> to directly construct the argument from source iterators.</p>\n</li>\n<li><p>Now we're getting into details: instead of <code>[_val=_1]</code> we can use automatic attribute propagation (see <a href=\"https://stackoverflow.com/questions/8259440/boost-spirit-semantic-actions-are-evil\">https://stackoverflow.com/questions/8259440/boost-spirit-semantic-actions-are-evil</a> and <a href=\"https://www.boost.org/doc/libs/1_73_0/libs/spirit/doc/html/spirit/qi/reference/nonterminal/rule.html#spirit.qi.reference.nonterminal.rule.expression_semantics\" rel=\"nofollow noreferrer\"><code>operator %=</code> rule init</a>).</p>\n</li>\n<li><p>Factor out more common subexpressions. Together with previous bullet:</p>\n<pre><code>primary\n = qi::double_[_val = _1]\n | ('(' > expression[_val = _1] > ')')\n >> *("." > variable[_val = make(_val, _1, ".")])\n | variable[_val = _1]\n >> *("." > variable[_val = make(_val, _1, ".")]);\n</code></pre>\n<p>Becomes:</p>\n<pre><code>primary %= qi::double_\n | (('(' > expression > ')') | variable)\n >> *("." > variable[_val = make(_val, _1, ".")])\n ;\n</code></pre>\n</li>\n<li><p>Lift variant type outside <code>expression</code> so you can implement the recursive types before <code>expression</code>. Also, consider <code>expression</code> deriving from the variant (<a href=\"https://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">LSK</a>). In your case, there is no real need for nested expressions because the unary/binary nodes impose order already. So your entire AST can be:</p>\n<pre><code>struct unary_operator;\nstruct binary_operator;\n\ntypedef boost::variant<\n double,\n std::string,\n boost::recursive_wrapper<unary_operator>,\n boost::recursive_wrapper<binary_operator>\n> expr_variant;\n\nstruct expression : expr_variant {\n using expr_variant::expr_variant;\n using expr_variant::operator=;\n};\n\nstruct unary_operator { expression rhs; std::string op; } ;\nstruct binary_operator { expression lhs; expression rhs; std::string op; } ;\n</code></pre>\n</li>\n<li><p>Move <code>expectation_handler</code> inside the grammar class (it's of no use to anything else), and optionally modernize it with phoenix::function? Regardless, since the functor is stateless, no need to <code>ref</code> (and certainly not <code>ref</code> instead of <code>cref</code>):</p>\n<pre><code>qi::on_error<qi::fail>(\n expression,\n boost::phoenix::bind(expectation_handler{}, _3, _2, _4));\n</code></pre>\n<p>Actually, just make it</p>\n<pre><code>auto handler = [](Iterator first, Iterator last, const boost::spirit::info &info) {\n std::stringstream msg;\n msg << "Expected " << info << " at \\"" << std::string(first, last) << "\\"";\n throw std::runtime_error(msg.str());\n};\n\nqi::on_error<qi::fail>(\n expression,\n boost::phoenix::bind(handler, _3, _2, _4));\n</code></pre>\n</li>\n<li><p>Minor nit: use <a href=\"https://en.cppreference.com/w/cpp/io/manip/quoted\" rel=\"nofollow noreferrer\"><code>std::quoted</code></a> instead of "fake" quoting :)</p>\n</li>\n<li><p>Late brainwave, you can extract the bulk of that semantic action:</p>\n<pre><code>auto make_bin =\n _val = px::bind(make_<ast::binary_expr>{}, _val, _2, _1);\n</code></pre>\n<p>As long as all the limbs are stateless/by value, that's not a problem (contrast with <a href=\"https://stackoverflow.com/questions/22023779/assigning-parsers-to-auto-variables/22027181#22027181\">https://stackoverflow.com/questions/22023779/assigning-parsers-to-auto-variables/22027181#22027181</a> though!). Now just make the operators expose attributes:</p>\n<pre><code>expression %= equality\n >> *(\n (qi::string("&&") > equality)[make_bin] |\n (qi::string("||") > equality)[make_bin]\n );\n\nequality %= relational\n >> *(\n (qi::string("==") > relational)[make_bin] |\n (qi::string("!=") > relational)[make_bin]\n );\n\nrelational %= additive\n >> *(\n (qi::string("<") > relational)[make_bin] |\n (qi::string("<=") > relational)[make_bin] |\n (qi::string(">") > relational)[make_bin] |\n (qi::string(">=") > relational)[make_bin]\n );\n\nadditive %= multiplicative\n >> *(\n (qi::string("+") > multiplicative)[make_bin] |\n (qi::string("-") > multiplicative)[make_bin]\n );\n\nmultiplicative %= factor\n >> *(\n (qi::string("*") > factor)[make_bin] |\n (qi::string("/") > factor)[make_bin]\n );\n\nfactor %= primary\n >> *(\n (qi::string("**") > primary)[make_bin]\n );\n\nprimary %= qi::double_\n | (('(' > expression > ')') | variable)\n >> *(qi::string(".") > variable)[make_bin]\n ;\n</code></pre>\n</li>\n<li><p>Actually, just checked and <code>phoenix::construct</code> can do aggregates:</p>\n<pre><code>auto make_bin =\n _val = boost::phoenix::construct<ast::binary_expr>(_1, _val, _2);\n</code></pre>\n</li>\n<li><p>Also dropped the unused <code>unary_*</code> machinery, moved the IO manipulator into <code>io</code> namespace (instead of <code>ast</code>) and reintroduced <code>eoi</code> checking in the <code>main</code> driver...</p>\n</li>\n<li><p>Heck, with some c++17 you can combine the branches of each production:</p>\n<pre><code>auto op = [](auto... sym) { return qi::copy((qi::string(sym) | ...)); };\n\nexpression %= equality >> *(op("&&","||") > equality)[make_bin];\nequality %= relational >> *(op("==","!=") > relational)[make_bin];\nrelational %= additive >> *(op("<","<=",">",">=") > relational)[make_bin];\nadditive %= multiplicative >> *(op("+","-") > multiplicative)[make_bin];\nmultiplicative %= factor >> *(op("*","/") > factor)[make_bin];\nfactor %= primary >> *(op("**") > primary)[make_bin];\n</code></pre>\n</li>\n</ol>\n<h2>Full Demo, 103 Lines Of Code</h2>\n<p>Only just didn't manage to bring it under 100 LoC, but I added more test cases in the process.</p>\n<ul>\n<li><p><strong><a href=\"https://wandbox.org/permlink/n6Sd1a0JCnzRo5Hr\" rel=\"nofollow noreferrer\">Live Demo On Wandbox</a></strong></p>\n</li>\n<li><p><strong><a href=\"https://godbolt.org/z/RCs8MU\" rel=\"nofollow noreferrer\">Live Demo On Compiler Explorer</a></strong></p>\n</li>\n<li><p><strong><a href=\"http://coliru.stacked-crooked.com/a/3f9afaad41463243\" rel=\"nofollow noreferrer\">Live Demo On Coliru</a></strong> (<em>where I found out that <code>phoenix::construct<></code> for aggregates requires either GCC or recent boost or both, so added a constructor</em>)</p>\n</li>\n</ul>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n#include <iostream>\n#include <iomanip>\nnamespace qi = boost::spirit::qi;\n\nnamespace ast {\n struct binary_expr;\n\n typedef boost::variant<\n double,\n std::string,\n boost::recursive_wrapper<binary_expr>\n > expr_variant;\n\n struct expression : expr_variant {\n using expr_variant::expr_variant;\n using expr_variant::operator=;\n };\n\n struct binary_expr {\n binary_expr(std::string op, expression lhs, expression rhs)\n : op(std::move(op)), lhs(std::move(lhs)), rhs(std::move(rhs)) {}\n std::string op; expression lhs; expression rhs;\n };\n}\n\nnamespace io {\n struct fmt_expr { // io manipulator\n ast::expression const& _ref;\n friend std::ostream& operator<<(std::ostream& os, fmt_expr manip);\n };\n\n struct formatter_visitor {\n std::ostream& _os;\n template <typename T> std::ostream& operator()(T const& v) const\n { return call(v); }\n\n private:\n std::ostream& call(ast::expression const& v) const {\n return boost::apply_visitor(*this, v);\n }\n\n std::ostream& call(ast::binary_expr const& expr) const {\n return _os << "op:" << expr.op\n << "(" << fmt_expr{expr.lhs} << ", " << fmt_expr{expr.rhs} << ')';\n }\n\n template <typename Lit>\n std::ostream& call(Lit const& v) const { return _os << v; }\n };\n\n std::ostream& operator<<(std::ostream& os, fmt_expr manip) {\n return formatter_visitor{os}(manip._ref);\n }\n}\n\ntemplate<typename Iterator>\nstruct grammar : qi::grammar<Iterator, ast::expression()> {\n grammar() : grammar::base_type(start) {\n using namespace qi::labels;\n\n auto make_bin = _val = boost::phoenix::construct<ast::binary_expr>(_1, _val, _2);\n auto op = [](auto... sym) { return qi::copy((qi::string(sym) | ...)); };\n\n expression %= equality >> *(op("&&","||") > equality)[make_bin];\n equality %= relational >> *(op("==","!=") > relational)[make_bin];\n relational %= additive >> *(op("<","<=",">",">=") > relational)[make_bin];\n additive %= multiplicative >> *(op("+","-") > multiplicative)[make_bin];\n multiplicative %= factor >> *(op("*","/") > factor)[make_bin];\n factor %= primary >> *(op("**") > primary)[make_bin];\n \n variable = qi::lexeme[qi::alpha >> *(qi::alnum | qi::char_('_'))];\n primary %= qi::double_ | (('(' > expression > ')') | variable)\n >> *(op(".") > variable)[make_bin];\n \n start = qi::skip(qi::ascii::space) [ qi::eps > expression ] > qi::eoi;\n\n qi::on_error<qi::fail>(start, boost::phoenix::bind([](auto first, auto last, auto const& info) {\n std::stringstream msg;\n msg << "Expected " << info << " at " << std::quoted(std::string(first, last));\n throw std::runtime_error(msg.str());\n }, _3, _2, _4));\n\n BOOST_SPIRIT_DEBUG_NODES((expression)(equality)(relational)(additive)\n (multiplicative)(factor)(unary)(binary)(primary)(variable))\n }\n private:\n qi::rule<Iterator, ast::expression()> start;\n qi::rule<Iterator, ast::expression(), qi::ascii::space_type> expression, equality, relational, additive, multiplicative, factor, unary, binary, primary;\n qi::rule<Iterator, std::string()> variable; // lexeme\n};\n\nint main() {\n using io::fmt_expr;\n grammar<std::string::const_iterator> parser;\n\n for (std::string const s : { "2 + 5 + t.a", "(2 + 5) + t.a", "2 + 5 * t.a",\n "2 * 5 - t.a", "partial match", "uhoh *", "under_scores", "" })\n try {\n ast::expression expression;\n qi::parse(s.begin(), s.end(), parser, expression);\n std::cout << std::quoted(s) << " -> " << fmt_expr{expression} << "\\n";\n } catch(std::exception const& e) {\n std::cout << "Exception: " << e.what() << "\\n";\n }\n}\n</code></pre>\n<p>Prints</p>\n<pre><code>"2 + 5 + t.a" -> op:+(op:+(2, 5), op:.(t, a))\n"(2 + 5) + t.a" -> op:+(op:+(2, 5), op:.(t, a))\n"2 + 5 * t.a" -> op:+(2, op:*(5, op:.(t, a)))\n"2 * 5 - t.a" -> op:-(op:*(2, 5), op:.(t, a))\nException: Expected <eoi> at " match"\nException: Expected <factor> at ""\n"under_scores" -> under_scores\n</code></pre>\n<h2>Beyond Scope</h2>\n<p>The things I'll consider beyond the scope are related to your grammar/ast semantics.</p>\n<ol>\n<li><p>Operator precedence is a bit noisy. What you'd like to have is some meta data that allows you to "just combine" the binary operands and have the correct precedence emerge, like so:</p>\n<pre><code>expression %= primary\n >> *(\n (binop > expression) [_val = make_bin(_1, _val, _2)]\n );\n</code></pre>\n<p>I've applied this strategy on an <a href=\"https://chat.stackoverflow.com/transcript/210289?m=49164574#49164574\">extended chat</a> at <a href=\"https://stackoverflow.com/a/60846101/85371\">this answer</a> and the resulting code is on github: <a href=\"https://github.com/sehe/qi-extended-parser-evaluator\" rel=\"nofollow noreferrer\">https://github.com/sehe/qi-extended-parser-evaluator</a></p>\n</li>\n<li><p>Consider using X3 if you have C++14 support. The compile times will be much lower.</p>\n</li>\n</ol>\n\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T18:29:02.663",
"Id": "480155",
"Score": "0",
"body": "Wow... I didn't expect SO detailed code review. I'm mobile now and can't play with this code, but can you describe a little bit more about #11, please? And thank you for this code review, I really appreciate it and learned a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T18:31:33.957",
"Id": "480156",
"Score": "0",
"body": "I think #11 will become pretty clear when you have the opportunity to look at the demos side-by-side. No hurry :) Cheers"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T17:28:59.147",
"Id": "244579",
"ParentId": "244557",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244579",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T08:47:33.850",
"Id": "244557",
"Score": "6",
"Tags": [
"c++",
"boost"
],
"Title": "Using Boost.Spirit to transform expression to AST"
}
|
244557
|
<p>I've been doing some research around how to best make use of the WebP images (with fallback) in React. Most solutions point to something similar to what I've written below. That means if I have a lot of images I have to export the same image twice in <code>assets.js</code> (both PNG and WebP), import twice and provide two <code>Image</code> props for the same image.</p>
<p>This feels very inefficient. Is this an uncommon way of working with images? Is there a better way for working with images that live locally?</p>
<p><code>assets.js</code> - where I collect all my assets and export them as strings. Imagine this list being really lengthy.</p>
<pre><code>export { default as image1 } from "./assets/image-1.png";
export { default as image1Webp } from "./assets/image-1.webp";
</code></pre>
<p>In the file I import the assets I need for that page</p>
<pre><code>import {
image1,
image1Webp
} from "./assets";
</code></pre>
<p><code>The component + props</code></p>
<pre><code><Image
src={image1Webp}
fallback={image1}
alt="Lorem"
/>
</code></pre>
<p><code>Image.js</code> component</p>
<pre><code>const Image = ({
src,
fallback,
type = 'image/webp',
...delegated
}) => {
return (
<picture>
<source srcSet={src} type={type} />
<img src={fallback} {...delegated} />
</picture>
);
};
</code></pre>
<hr />
<p>Some things I've tried:</p>
<p>Generally the recommended way is to add images to a React project is to use <code>require(img/path)</code>. So I tried things like appending <code>.png</code> or <code>.webp</code> to the base URL, inside the <code>Image</code> component. so I only need to define one string and then the component handles the splitting.</p>
<p>e.g. pseudocode:</p>
<pre><code>export const toWEBP = (src) => {
const location = src.split(".")
return `${location}.webp`
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T12:32:58.460",
"Id": "480916",
"Score": "0",
"body": "You aren’t using webpack or a similar server-side tool to transpile/package the code are you? And do all image file names have a similar pattern, such that the names could be put into an array, e.g. `[“image-1”, “image-2”...]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T12:42:00.153",
"Id": "480917",
"Score": "1",
"body": "I'm using `create-react-app` as a starting point. And as far as I'm concerned they don't expose webpack settings"
}
] |
[
{
"body": "<p>It would be great if the code could be simplified using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Import\" rel=\"nofollow noreferrer\">dynamic imports</a>. I haven't tried this myself but if the image names could be put into an array then something like the following might work, where the exported images are set as properties on an object that can be exported. When <a href=\"https://stackoverflow.com/a/52957110/1575353\">this SO answer to <em>Create a loop to import files dynamically in React</em></a> was written only Chrome and Safari supported that feature but since then it appears that Edge and Firefox now offer support as well.</p>\n<pre><code>const images = {};\nconst nums = [1, 2];\nfor (const format of ['png', 'webp']) {\n for (const num of nums) {\n const key = `image${num}` + format === 'webp' ? 'webp' : '';\n images[key] = await import( `./assets/image-${num}.${format}`);\n }\n}\n</code></pre>\n<p>But according to the Hacks blog post by Jason Orendorff <a href=\"https://hacks.mozilla.org/2015/08/es6-in-depth-modules/\" rel=\"nofollow noreferrer\"><em>ES6 In Depth: Modules</em></a></p>\n<blockquote>\n<p>For a dynamic language, JavaScript has gotten itself a surprisingly static module system.</p>\n<ul>\n<li>All flavors of <code>import</code> and <code>export</code> are allowed only at toplevel in a module. There are no conditional imports or exports, and you can’t use <code>import</code> in function scope.</li>\n<li>All exported identifiers must be explicitly exported by name in the source code. You can’t programmatically loop through an array and export a bunch of names in a data-driven way.</li>\n</ul>\n</blockquote>\n<p>So the function code above could be exported in an async function:</p>\n<pre><code>export async function getImages() {\n const images = {};\n //...set keys on images\n return images;\n}\n</code></pre>\n<p>Then that function can be imported:</p>\n<pre><code>import { getImages } from './assets.js';\n</code></pre>\n<p>But to use that function it would need to be run in an async function:</p>\n<pre><code>(async () => {\n const images = await getImages();\n //use images\n})();\n</code></pre>\n<p>Other approaches are listed in answers to <a href=\"https://forum.freecodecamp.org/t/importing-images-in-react/206974\" rel=\"nofollow noreferrer\">this similar post on freecodecamp.org</a> - e.g. from <a href=\"https://forum.freecodecamp.org/t/importing-images-in-react/206974/4\" rel=\"nofollow noreferrer\">this answer by Dan Couper</a>:</p>\n<blockquote>\n<p>One pretty simple solution:</p>\n</blockquote>\n<blockquote>\n<pre><code>// images.js\nconst images = [\n { id: 1, src: './assets/image01.jpg', title: 'foo', description: 'bar' },\n { id: 2, src: './assets/image02.jpg', title: 'foo', description: 'bar' },\n { id: 3, src: './assets/image03.jpg', title: 'foo', description: 'bar' },\n { id: 4, src: './assets/image04.jpg', title: 'foo', description: 'bar' },\n { id: 5, src: './assets/image05.jpg', title: 'foo', description: 'bar' },\n ...etc\n];\nexport default images;\n</code></pre>\n</blockquote>\n<blockquote>\n<pre><code>// MyComponent.js\nimport images from './images'\n//...snip\n{ images.map(({id, src, title, description}) => <img key={id} src={src} title={title} alt={description} />)\n</code></pre>\n<p>You’re basically writing a database of images that match the ones in assets.<br><br>\nThen you can be clever in images.js to pull the correct prefix based on the environment if you want. There will be a WebPack plugin that kinda does this as well if you have a google around (you want it to take a directory of files and generate an iterable set of paths to them).<br><br>\nThe <code>import</code> as described is more for importing one-off images (logos etc) rather than importing lots of images from a directory.</p>\n</blockquote>\n<hr />\n<p>Regarding the pseudocode at the end of the post:</p>\n<blockquote>\n<pre><code>export const toWEBP = (src) => {\n const location = src.split(".")\n return `${location}.webp`\n}\n</code></pre>\n</blockquote>\n<p>if <code>src</code> contained an extension (e.g. <code>png</code>) then <code>webp</code> would be appended to that existing extension. One option would be to use <code>pop</code> to remove the existing extension and also push <code>webp</code> onto the array before using it in the return value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T16:59:55.410",
"Id": "481129",
"Score": "0",
"body": "Thanks Sam for looking into this. I love all these suggestions. I was having trouble getting the async/await stuff to work in React, even though it seems like the solution is mostly aimed towards a fixed name pattern e.g. `image-1.png, image-2.png` etc. What if the images have all different names? \n\nAnd what if the images are more sporadically placed (like an article) and not mapped in `map`. Mapping/looping all the images in one go is fairly trivial. It’s when you want to load the images at will, thats when I start to struggle to find a dry solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T17:11:10.637",
"Id": "481132",
"Score": "0",
"body": "Even if the images have different names, would those be consistent between the formats, e.g. `code.png` and `code.webp`? There is [another answer by Dan in that that thread](https://forum.freecodecamp.org/t/importing-images-in-react/206974/6) that might offer inspiration about async loading..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T17:25:14.127",
"Id": "481134",
"Score": "0",
"body": "Yes the name would still be consistent between the formats. I got the async working, Now I'm getting in the console.log: `default: \"/static/media/monomesh-red2.4b122a66.webp\"`. Now I've got to figure out how it can work with different name patterns."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T18:48:40.657",
"Id": "245011",
"ParentId": "244559",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T09:19:14.710",
"Id": "244559",
"Score": "5",
"Tags": [
"javascript",
"ecmascript-6",
"react.js"
],
"Title": "Working with images in multiple formats"
}
|
244559
|
<p>My custom hook <code>useTyper.js</code> ended up as a <strong>bit of a mess</strong> and hard to read.</p>
<p>It's mimicking a nested for-loop but using <code>React.useRef</code>s to hold on to the indexes between renders. The indexes are the current positions of the outer and inner loop, those often named <code>i</code> and <code>j</code> in traditional nested for loops.</p>
<p>Here's a <a href="https://codesandbox.io/s/gracious-turing-obice" rel="noreferrer">fancy code sandbox</a> for the mess below.</p>
<p>One thing I'm particularly unhappy with is the naming of <code>stringIdx</code> and <code>stringsIdx</code>. Any suggestion for a change?</p>
<p><code>useTyper.js</code></p>
<pre><code>import React from "react";
import useInterval from "./useInterval.js";
/**
* A simple typewriter that prints strings, one character after another
* @param {Array<string>} strings - Array of strings to type
* @param {function<string>} set - A useState setter to update the current string value
* @param {number} defaultDelay - Delay between updates
*/
const useTyper = (strings, set, defaultDelay = 100) => {
const [delay, setDelay] = React.useState(defaultDelay);
// index counters, normally named i and j if this were an imperative loop
const stringIdx = React.useRef(0);
const stringsIdx = React.useRef(0);
const textTyper = () => {
const currentString = strings[stringsIdx.current];
set(currentString.substr(0, stringIdx.current + 1));
if (stringIdx.current > currentString.length) {
// Done with string
stringsIdx.current += 1;
stringIdx.current = 0;
if (stringsIdx.current > strings.length - 1) {
setDelay(null); // Ended.
}
}
stringIdx.current += 1;
};
useInterval(textTyper, delay);
};
export default useTyper;
</code></pre>
<p>For completion, this is the <code>useInterval</code> hook being used by <code>useTyper</code>.
It can be referenced from <a href="https://overreacted.io/making-setinterval-declarative-with-react-hooks/" rel="noreferrer">one of Dan Abramovs blog posts</a>.<br />
<code>useInterval.js</code></p>
<pre><code>import React from 'react';
const useInterval = (callback, delay) => {
const savedCallback = React.useRef();
// Remember the latest callback.
React.useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
React.useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => {
clearInterval(id);
};
}
}, [delay]);
};
export default useInterval;
</code></pre>
<p>Here is how the <code>useTyper</code> hook can be used.</p>
<pre><code>import React, { useState } from "react";
import "./styles.css";
import useTyper from "./hooks/useTyper.js";
export default function App() {
const [placeHolder, setPlaceHolder] = useState("");
const placeHolders = [
"First input suggestion",
"Second input suggeston",
"Creativity flows... ",
"Alright, lets leave it here."
];
useTyper(placeHolders, setPlaceHolder);
return (
<div className="App">
<div className="container">
<input
id="formElement"
autoComplete="off"
autoFocus
size="20"
type="text"
placeholder={placeHolder}
/>
</div>
</div>
);
}
</code></pre>
<p>Again, here's the link to the <a href="https://codesandbox.io/s/gracious-turing-obice" rel="noreferrer">code sandbox</a>.</p>
|
[] |
[
{
"body": "<p>Looks to be fairly clean code.</p>\n<h1>Suggestions</h1>\n<ol>\n<li>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice\" rel=\"nofollow noreferrer\">string::slice</a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring\" rel=\"nofollow noreferrer\">string::substring</a> versus <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr\" rel=\"nofollow noreferrer\">string::substr</a>. <code>substr</code> isn't deprecated but also isn't recommended for use.</li>\n</ol>\n<blockquote>\n<p>Warning: Although <code>String.prototype.substr(…)</code> is not strictly\ndeprecated (as in "removed from the Web standards"), it is considered\na <strong>legacy function</strong> and should be avoided when possible. It is not part\nof the core JavaScript language and may be removed in the future. If\nat all possible, use the <code>substring()</code> method instead.</p>\n</blockquote>\n<pre><code>setCurrentString(currentString.slice(0, currentStringIndex.current + 1));\n</code></pre>\n<ol start=\"2\">\n<li>Provide clearer parameter names, i.e. <code>stringArray</code> versus just <code>strings</code>, and <code>setString</code> or <code>setCurrentString</code> versus <code>set</code>. <code>set</code> alone can be confusing as it isn't very descriptive, i.e. "is it a mathematical set?" By naming a function with verbNoun it is clearer to a reader <em>what</em> it is <em>and</em> what it does.</li>\n</ol>\n<pre><code>const useTyper = (stringsArray, setCurrentString, defaultDelay = 100) => {\n</code></pre>\n<ol start=\"3\">\n<li><code>stringIdx</code> and <code>stringsIdx</code> can cause mental gymnastics looking for the 's' to differentiate the two. Isolated from one another the names <em>aren't</em> terrible, but when used together within the same function it is more demanding. The names <em>should</em> also align closer to the variable they indicate an index for. Based on the previous parameter naming suggestion I recommend <code>stringArrayIndex</code> and <code>currentStringIndex</code>.</li>\n<li>You also appear to do an extra iteration on the <code>currentString</code> with the conditional test <code>currentStringIndex.current > currentString.length</code>. You can increment to the next string when the current string's index is equal to the length, <code>currentStringIndex.current >= currentString.length</code>.</li>\n<li>Similar conditional test for checking for the end of the strings array, when the index is. greater then <em>or equal</em> to the length you can quit. <code>stringArrayIndex.current >= stringArray.length</code></li>\n</ol>\n<pre><code>const useTyper = (stringArray, setCurrentString, defaultDelay = 100) => {\n const [delay, setDelay] = React.useState(defaultDelay);\n // index counters, normally named i and j if this were an imperative loop\n const currentStringIndex = React.useRef(0);\n const stringArrayIndex = React.useRef(0);\n\n const textTyper = () => {\n const currentString = stringArray[stringArrayIndex.current];\n\n setCurrentString(currentString.slice(0, currentStringIndex.current + 1));\n\n if (currentStringIndex.current >= currentString.length) {\n // Done with string\n stringArrayIndex.current += 1;\n currentStringIndex.current = 0;\n if (stringArrayIndex.current >= stringArray.length) {\n setDelay(null); // Ended.\n }\n }\n currentStringIndex.current += 1;\n };\n\n useInterval(textTyper, delay);\n};\n</code></pre>\n<p>Good job, nice hook.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T07:49:30.203",
"Id": "480398",
"Score": "1",
"body": "Excellent feedback! I ended up with [this codesandbox](https://codesandbox.io/s/usetyper-after-codereview-civxs) with your exact suggestions, _but_: I removed the `+ 1` in the call to `setCurrentString` since it made the subsequent strings start with two characters printed instead of one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T16:14:02.903",
"Id": "480433",
"Score": "1",
"body": "@HenrikSN Ah, good catch, I hadn't noticed that and likely thought it was my machine. I hadn't messed with the timer delay at all."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T17:41:25.420",
"Id": "244581",
"ParentId": "244560",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "244581",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T09:34:57.630",
"Id": "244560",
"Score": "7",
"Tags": [
"javascript",
"react.js"
],
"Title": "React custom hooks using refs as index counters"
}
|
244560
|
<p>The code below returns the smallest perfect square that can be added to a number <code>n</code> to result in a perfect square. It works perfectly fine but I need it to run faster.</p>
<pre><code>def solve n
(1..n).each do |i|
i = i**2 + n
return i -= n if (Math.sqrt(i) % 1).zero?
end
-1
end
p solve(13) #36
# because 36 is the smallest perfect square that can be added to 13 to form a perfect square => 13 + 36 = 49
p solve(3) #= 1 # 3 + 1 = 4, a perfect square
p solve(12) #= 4 # 12 + 4 = 16, a perfect square
p solve(9) #= 16
p solve(4) #= -1`
</code></pre>
|
[] |
[
{
"body": "<p>I can see a few changes you can do in your code.<br />\nFirst one, save the calculated square and use it in the next iteration:</p>\n<pre><code>def solve2(n)\n # Start with an initial zero value\n pow = 0\n (1..n).each do |i|\n # This is the same as i**2, but using the square previously calculated.\n # Google squares and pascal triangle to more insight about this, but\n # in terms of cpu usage, this is faster.\n pow = pow + (i - 1) * 2 + 1\n r = pow + n\n return r -= n if (Math.sqrt(r) % 1).zero?\n end\n -1\nend\n</code></pre>\n<p>And yes, it's not a big improvement, but it works. Trying in a worst case scenario, where no value is found so it must check every different iteration:</p>\n<pre><code>irb(main):250:0> require 'benchmark'\n=> false\nirb(main):251:0>\nirb(main):252:0> Benchmark.bm do |x|\nirb(main):253:1* x.report { solve 50_000_002 }\nirb(main):254:1> x.report { solve2 50_000_002 }\nirb(main):255:1> end\n user system total real\n 9.072362 0.029596 9.101958 ( 9.783397)\n 8.491063 0.030566 8.521629 ( 9.159671) # ~600ms faster than the previous one, yay!\n</code></pre>\n<p>Next thing, instead of iterating between <code>1</code> and <code>n</code>, you need to iterate only integer values between <code>Math.sqrt(1**2 + n)</code> and <code>Math.sqrt(n**2 + n)</code>. For example, using the current code with the same <code>50_000_002</code> value of the benchmark:</p>\n<pre><code>irb(main):358:0> Math.sqrt(1**2 + 50_000_002)\n=> 7071.068023997506 # 1st iteration, for sure this will fail with ( % 1).zero?\nirb(main):359:0> Math.sqrt(2**2 + 50_000_002)\n=> 7071.068236129531 # 2nd one still with decimals\nirb(main):360:0> Math.sqrt(3**2 + 50_000_002)\n=> 7071.068589682892 # and so on...\nirb(main):361:0> Math.sqrt(4**2 + 50_000_002)\n=> 7071.069084657567\nirb(main):362:0> Math.sqrt(5**2 + 50_000_002)\n=> 7071.069721053526\n</code></pre>\n<p>as you can see, for the first values of the iteration, you're getting pretty much the same integer value with only decimals of difference. Eventually you'll be close to get an integer value much further in the 114th iteration:</p>\n<pre><code>irb(main):392:0> Math.sqrt(114**2 + 50_000_002)\n=> 7071.986849535285\nirb(main):393:0> Math.sqrt(115**2 + 50_000_002)\n=> 7072.003040157718 # that was close, but not enough to get a integer. Keep trying...\n</code></pre>\n<p>So checking all those 114 values were useless, because their results weren't even integers. After a while, reaching the last values, you still don't get a single integer value:</p>\n<pre><code>irb(main):394:0> Math.sqrt(50_000_000**2 + 50_000_002)\n=> 50000000.500000015\nirb(main):395:0> Math.sqrt(50_000_001**2 + 50_000_002)\n=> 50000001.50000001\nirb(main):396:0> Math.sqrt(50_000_002**2 + 50_000_002)\n=> 50000002.5\n</code></pre>\n<p>Then, the problem was to check float values when we need to check only when values have no decimals. In other words, instead of iterate between <code>1</code> and <code>50_000_002</code>, you must iterate between <code>7072</code> (ceiling value for result of <code>Math.sqrt(1**2 + 50_000_002)</code>, taken from your first previous iteration) and <code>50_000_002</code> (floor result of <code>Math.sqrt(50_000_002**2 + 50_000_002)</code>, your last iteration, which at the end is the same value as <code>n</code>).<br />\nWhy using this new perspective? mostly because <code>Math.sqrt</code> is an expensive operation compared with <code>+</code>, <code>-</code> or <code>*</code> (or even <code>**</code> if the <code>solve2</code> improvement hasn't been applied). I'll try to explain as much as I can in the code:</p>\n<pre><code>def solve3(n)\n # Lowest square root result. This will be the starting point \n lowest_sqrt = Math.sqrt(1 + n).ceil\n # then getting first i value to compare. This is the last time using\n # Math.sqrt\n i = Math.sqrt(lowest_sqrt**2 - n).to_i\n # Keeping a flag, which will be the value to return later\n flag = i\n # Initial values for perfect square, where will be used the base value from\n # previous iteration (that's why i - 1) to make the power replacement as in\n # solve2\n pow = (i - 1)**2\n # and result after adding the n value.\n res = sq(pow, i) + n\n loop do\n pow = sq(pow, i)\n # When square and result are the same, that's our lowest perfect square\n return flag**2 if res == pow\n\n # In case result is lower, result must be recalculated with new square\n # value.\n if res < pow\n flag = i\n res = pow + n\n end\n \n i += 1\n break if i > n\n end\n -1\nend\n\n# pascal triangle trick\ndef sq(pow, i)\n pow + (i - 1) * 2 + 1\nend\n</code></pre>\n<p>This is a significant improvement compared with previous implementations:</p>\n<pre><code>irb(main):908:0> Benchmark.bm do |x|\nirb(main):909:1* x.report { solve 50_000_002 }\nirb(main):910:1> x.report { solve2 50_000_002 }\nirb(main):911:1> x.report { solve3 50_000_002 }\nirb(main):912:1> end\n user system total real\n 9.077371 0.036185 9.113556 ( 10.015861)\n 8.486830 0.026608 8.513438 ( 9.090664)\n 4.709684 0.012402 4.722086 ( 4.925373)\n</code></pre>\n<p>And I think there's still space to improve the code. I have the feeling there are some useless comparisons in the loop that can be avoided, but I've spent a while explaining all this, so I'll leave that to you :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T10:20:14.957",
"Id": "480410",
"Score": "0",
"body": "I really appreciate the time you took to explain all this to a newbie. However, When running the improved code, I am finding some failing texts, like 17 should return 64 instead of -1. My approach was to square all the (i's) so as to get the perfect squares and comparing which first squared number would return a perfect square. I really appreciate your effort man."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T05:53:49.740",
"Id": "480883",
"Score": "0",
"body": "If you have a solution, please share it as an answer. Cheers"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T09:25:49.573",
"Id": "244703",
"ParentId": "244561",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T10:41:19.933",
"Id": "244561",
"Score": "3",
"Tags": [
"ruby",
"time-limit-exceeded",
"mathematics"
],
"Title": "Finding the lowest perfect square that can be added to a number to make another perfect square"
}
|
244561
|
<p>I am developing a workflow to perform a variety of operations on raster dataset using rasterio. My previous workflow involved lots of I/O when performing such operations on raster files. I would like to change the workflow so to process raster data in-memory. I am using <code>rasterio.MemoryFile()</code> class to achieve that. Here some of my code:</p>
<pre><code>@contextmanager
def mem_file(arr, metadata, *to_del_arr):
"""
Create and yield a Datareader using a numpy array
and raster metadata
"""
with rasterio.MemoryFile() as memfile:
with memfile.open(**metadata) as src: # Open as DatasetWriter
if arr.ndim == 2:
src.write_band(1, arr)
else:
src.write(arr.astype(metadata['dtype']))
for arr in to_del_arr:
del arr
with memfile.open() as src: # Reopen as DatasetReader
yield src
@contextmanager
def resample_raster(src, scale=2):
"""
resample raster
"""
t = src.transform
# rescale the metadata
transform = rasterio.Affine(t.a / scale, t.b, t.c, t.d, t.e / scale, t.f)
height = src.height * scale
width = src.width * scale
new_meta = copy.deepcopy(src.meta)
new_meta.update(transform=transform, driver='GTiff', height=height,
width=width)
# resampling
arr = src.read(resampling=rasterio.enums.Resampling.nearest)
return mem_file(arr, new_meta, arr)
@contextmanager
def create_raster_mask(src, vals):
"""
create a raster mask
"""
arr = src.read()
mask_arr = np.ma.MaskedArray(arr, np.in1d(arr, vals))
new_meta = copy.deepcopy(src.meta)
new_meta.update(driver='GTiff', nbits=1)
return mem_file(mask_arr.mask, new_meta, arr, mask_arr)
@contextmenager
def another_operation(src):
pass
</code></pre>
<p>The idea is to chain this operations together to build a workflow. Right now I can do that like so:</p>
<pre><code>
if __name__ == "__main__":
with rasterio.open("tests/T37MBN_20190628T073621_SCL_20m.jp2") as src:
print(src.meta)
with resample_raster(src) as resampled:
print(resampled.meta)
with create_raster_mask(resampled, [3,7,8,9,10]) as mask:
print(mask.meta)
</code></pre>
<p>But I would like to avoid such nested structure and have something more like:</p>
<pre><code>if __name__ == "__main__":
with rasterio.open("tests/T37MBN_20190628T073621_SCL_20m.jp2") as src:
final = create_raster_mask(resample_raster(src))
print(final.meta)
</code></pre>
<p>Is there a way I can achieve that?
Thanks</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T11:23:46.253",
"Id": "244563",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Chain operations on raster data"
}
|
244563
|
<p>I usually use c++ so it may not be best practice for c.<br />
This is a stack based toy vm and as a result it is very primitive, and it has no bitwise
instructions<br />
64k might be a bit overkill for a toy vm.<br />
coding is hard</p>
<pre><code>#include <stdio.h>
#include "vm.h"
int main() {
Vm *vm = new_vm();
i32 buffer[] = {
0x00000A01, /* push 0x0A(\n) */
0x00004301, /* push 0x43(C) */
0x00004201, /* push 0x42(B) */
0x00004101, /* push 0x41(A) */
0x00000009, /* output */
0x00000002, /* pop */
0x00000009,
0x00000002,
0x00000009,
0x00000002,
0x00000009,
0x00000000 /* halt */
};
for (int i = 0; i < sizeof(buffer); i++) {
vm->mem[vm->pc+i] = buffer[i];
}
run_vm(vm);
free_vm(vm);
return 0;
}
</code></pre>
<p>vm.h</p>
<pre><code>#ifndef VM_H_
#define VM_H_
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
typedef uint32_t i32; /* other numbers */
typedef int32_t si32; /* stack pointer */
typedef unsigned char byte;
typedef struct {
i32 mem[0xffff]; /* approx. 64k */
si32 sp;
i32 pc;
i32 raw;
byte opc;
i32 param;
bool running;
} Vm;
Vm *new_vm();
void reset_vm(Vm *vm);
void free_vm(Vm *vm);
void run_vm(Vm *vm);
#endif
</code></pre>
<p>vm.c</p>
<pre><code>#include <stdio.h>
#include "vm.h"
Vm *new_vm() {
Vm *ret = (Vm*)malloc(sizeof(Vm));
ret->pc = 1024; /* add space for the stack */
ret->sp = -1;
ret->running = true;
return ret;
}
void reset_vm(Vm *vm) {
vm->running = true;
for (int i = 0; i < 0xffff; i++) {
vm->mem[i] = 0;
}
vm->sp = -1;
vm->pc = 1024;
}
void free_vm(Vm *vm) {
free(vm);
vm = NULL;
}
static void fetch(Vm *vm) {
vm->raw = vm->mem[vm->pc++];
}
static void decode(Vm *vm) {
/* style of opcode
* 24 bits for parameter
* a byte for the opcode
*/
vm->opc = vm->raw & 0xff;
vm->param = (vm->raw & 0xffffff00) >> 8;
}
static void execute(Vm *vm) {
switch(vm->opc) {
case 0x00: /* halt */
vm->running = false;
printf("Halt\n");
break;
case 0x01: /* push */
vm->mem[++vm->sp] = vm->param;
break;
case 0x02: /* pop */
vm->mem[vm->sp--] = 0;
break;
case 0x03: /* store */
vm->mem[ vm->mem[vm->sp - 1] ] = vm->mem[vm->sp];
break;
case 0x04: /* load */
vm->mem[vm->sp + 1] = vm->mem[ vm->mem[vm->sp] ];
++vm->sp;
break;
case 0x05: /* add */
vm->mem[vm->sp + 1] = vm->mem[vm->sp] + vm->mem[vm->sp - 1];
++vm->sp;
break;
case 0x06: /* sub */
vm->mem[vm->sp + 1] = vm->mem[vm->sp - 1] - vm->mem[vm->sp];
++vm->sp;
break;
case 0x07: /* mul */
vm->mem[vm->sp + 1] = vm->mem[vm->sp] * vm->mem[vm->sp - 1];
++vm->sp;
break;
case 0x08: /* div */
vm->mem[vm->sp + 1] = vm->mem[vm->sp - 1] / vm->mem[vm->sp];
++vm->sp;
break;
case 0x09: /* outc */
printf("%c", vm->mem[vm->sp]);
break;
case 0x0A: /* inpc */
vm->mem[++vm->sp] = getchar();
break;
}
}
void run_vm(Vm *vm) {
while(vm->running) {
fetch(vm);
decode(vm);
execute(vm);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T10:09:37.903",
"Id": "480197",
"Score": "0",
"body": "Minor: Use `foo(void);` when declaring a function that takes no arguments, as `foo();` declares a function with unspecified parameters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-28T18:04:05.173",
"Id": "486949",
"Score": "0",
"body": "You might want to look at the questions that are linked to this question, they are based on this question and one of the answers."
}
] |
[
{
"body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Be careful with array lengths</h2>\n<p>The memory allocation for the virtual machine is currently this:</p>\n<pre><code>i32 mem[0xffff]; /* approx. 64k */\n</code></pre>\n<p>While there is no intrinsic problem with this declaration or the comment, it means that memory locations 0 through 0xfffe are valid, but memory location 0xffff is not. That's not inconsistent with the code, but it's an odd choice. Also, see the next suggestion.</p>\n<h2>Avoid <code>magic numbers</code></h2>\n<p>As mentioned above, the number <code>0xffff</code> is used in both the header and in the <code>.c</code> file. Because it's quite important, I'd suggest that it would be better if it were a named value. Similarly, such numbers as 1024 could be named constants. So if, for example, you wanted to change the memory size to be exactly 64K, it would be easier if you only had to change the value in one place rather than hunting for the constant in multiple places in the code and then having to decide whether this particular 0xffff referred to the memory size or something else.</p>\n<h2>Provide a <code>default</code> case</h2>\n<p>What happens if the VM encounters an unknown instruction? At the moment it's silently ignored. It might be better to flag it as an error and one way to accomplish that nicely would be to add a <code>default</code> case to the <code>switch</code> statement.</p>\n<h2>Pass the buffer to the VM directly</h2>\n<p>Instead of having <code>main</code> reach into the VM and manipulate its internal data directly, I'd suggest a better approach might be to provide a version of <code>new_vm()</code> that takes a pointer and length so that it can do the copying instead.</p>\n<h2>Consider adding flags</h2>\n<p>Real processors typically have a set of flags, such as a Zero or Negative flag, as well as Overflow and Carry. As you expand your virtual machine, you will find those additions important as you start adding things such as conditional jumps or looping instructions.</p>\n<h2>Consider a data-centric approach</h2>\n<p>The code is generally clear and easy to read and understand as it is written. That's great! I would suggest that it might be easier to keep that readability as the code is enhanced and expanded if the opcodes and operations are structured into an array of data. This is likely to make it easier to add or modify instructions and to write assembler and disassembler enhancements if you're interested in doing that. The current approach, however, has the advantage of lookup speed for instructions since typical compilers generate very efficient code for <code>switch</code> statements.</p>\n<h2>Let the compiler generate code</h2>\n<p>It's not wrong to put <code>return 0;</code> at the end of <code>main</code> and some people prefer it for stylistic reasons. I prefer to omit it since it's guaranteed that the compiler will generate the equivalent code by itself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T14:13:21.003",
"Id": "244570",
"ParentId": "244566",
"Score": "6"
}
},
{
"body": "<p><strong>Missing Error Checking</strong></p>\n<blockquote>\n<p>I usually use c++ so it may not be best practice for c.</p>\n</blockquote>\n<p>In C++ when memory allocation fails in <code>new</code> an exception is thrown, this is not the case in the C programming language when using <code>malloc()</code>, <code>calloc()</code> or <code>realloc()</code>. An additional check is required after any memory allocation call. The check is to see if the memory returned is <code>NULL</code> or not, if the allocation fails references through the pointer are Unknown Behavior.</p>\n<pre><code>Vm *new_vm() {\n Vm *ret = (Vm*)malloc(sizeof(Vm));\n if (!ret)\n {\n fprintf(stderr, "Allocation of the Virtual Machine failed.\\n");\n return ret;\n }\n \n ret->pc = 1024; /* add space for the stack */\n ret->sp = -1;\n ret->running = true;\n return ret;\n}\n</code></pre>\n<p>In <code>main()</code>:</p>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include "vm.h"\n\nint main() {\n Vm *vm = new_vm();\n if (vm == NULL)\n {\n fprintf(stderr, "Exiting Toy Virtual Machine.\\n");\n return EXIT_FAILURE;\n }\n i32 buffer[] = {\n 0x00000A01, /* push 0x0A(\\n) */\n 0x00004301, /* push 0x43(C) */\n 0x00004201, /* push 0x42(B) */\n 0x00004101, /* push 0x41(A) */\n 0x00000009, /* output */\n 0x00000002, /* pop */\n 0x00000009,\n 0x00000002,\n 0x00000009,\n 0x00000002,\n 0x00000009,\n 0x00000000 /* halt */\n };\n for (int i = 0; i < sizeof(buffer); i++) {\n vm->mem[vm->pc+i] = buffer[i];\n }\n run_vm(vm);\n free_vm(vm);\n return EXIT_SUCCESS;\n}\n</code></pre>\n<p><strong>Include Only Necessary Headers</strong><br />\nIn the code as posted, <code>stdlib.h</code> is included in <code>vm.h</code>, <code>stdlib.h</code> is not necessary in <code>main()</code>, only in <code>vm.c</code>. To reduce the scope of the header files and source files only include what is needed. Amoung other things, this will reduce compile times, and may also reduce linking problems.</p>\n<p><strong>Missing Default Case in Switch Statement</strong><br />\nIt is generally a good programming practice to have a <code>default :</code> case statement in a switch statement to handle cases that haven't been specified yet:</p>\n<pre><code>static void execute(Vm *vm) {\n switch(vm->opc) {\n default:\n fprintf(stderr, "Unknown Opcode in execute(). 0x%x\\n", vm->opc);\n return;\n case 0x00: /* halt */\n vm->running = false;\n printf("Halt\\n");\n break;\n ...\n }\n</code></pre>\n<p>Then all possible paths through the function have been implemented. This is true in either C or C++ and most other programming languages that have a <code>switch</code> statement.</p>\n<p><strong>Use an ENUM for the Opcodes</strong><br />\nThe code would be much more readable if less numeric constants and more symbolic constants were used. In C there are 2 ways to do this, to create single symbolic constants use macro definition</p>\n<pre><code>#define SYMBOL VALUE\n</code></pre>\n<p>or to use enums</p>\n<pre><code>typedef enum {\n HALT = 0x00,\n PUSH = 0x01,\n POP = 0x02,\n ...\n INPUTCHAR = 0x0A\n} OPCODE;\n\n\ntypedef struct {\n i32 mem[0xffff]; /* approx. 64k */\n si32 sp;\n i32 pc;\n\n i32 raw;\n OPCODE opc;\n i32 param;\n\n bool running;\n} Vm;\n</code></pre>\n<p><strong>Use Unsigned Types as Indexes</strong><br />\nThe stack pointer index is currently a signed integer and is initialized to -1, this is what I consider to be a bad practice since stack[-1] will cause Unknown Behavior. It would be better to use <code>size_t</code> or <code>unsigned</code> as the stack pointer index. This will force a change in a number of areas, but here is what I would recommend:</p>\n<ol>\n<li>Initialize <code>running</code> to <code>false</code> rather than true.</li>\n<li>Initialize sp to zero</li>\n<li>Only index the stack and increment the stack pointer if <code>running</code> is true</li>\n<li>At the beginning of <code>run_vm(Vm *vm)</code> before the loop set <code>running</code> to true</li>\n<li>Change the implementation of <code>reset_vm(Vm *vm)</code> to match all of the above</li>\n</ol>\n<p><strong>Type Names and Variable Names</strong><br />\nInitially I was confused about Vm, whether it was a Virtual Memory or a Virtual Machine, this was true of other variables and types as well. Well written code is self documenting and doesn't need a lot of comments, type names and variable names play a big part in this. In my opinion <code>Vm</code> should be renamed <code>VirtualMachine</code>, <code>sp</code> should be renamed <code>StackPointer</code>, <code>pc</code> should be renamed <code>ProgramCounter</code> etc.</p>\n<p><strong>Use Library Functions Where Available</strong><br />\nC++ contains <code>std::memset()</code>, and <code>memset()</code> in C predates C++. The function <code>reset_vm()</code> should use <code>memset()</code> rather than the loop it is using to reset the memory. The function <code>memset()</code> should be faster than the current loop.</p>\n<pre><code>void reset_vm(Vm *vm) {\n vm->running = true;\n memset(&vm->mem[0], 0, sizeof(*vm->mem[0]) * 0xffff);\n vm->sp = -1;\n vm->pc = 1024;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T14:51:58.510",
"Id": "244573",
"ParentId": "244566",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T12:59:06.557",
"Id": "244566",
"Score": "10",
"Tags": [
"c",
"stack",
"virtual-machine"
],
"Title": "An attempt at a toy Vm"
}
|
244566
|
<p>This is another class from my <a href="https://github.com/georgebarwood/Database" rel="nofollow noreferrer">implementation of SQL in C#</a>. It handles the execution of SQL statements, with the core method looking like this:</p>
<pre><code> void ExecuteStatements( ResultSet rs ) // Statement execution loop.
{
ResultSet = rs;
NextStatement = 0;
while ( NextStatement < Statements.Length ) Statements[ NextStatement++ ]();
}
</code></pre>
<p>Here Statements is an array of actions:</p>
<pre><code> System.Action[] Statements; // List of statements to be executed.
</code></pre>
<p>A main aim of the project is for the code to be easy to understand, so feedback on how readable and easy to understand the code is would be appreciated. A "manual" describing the SQL variant implemented is built into the program ( displayed when a menu link is clicked ), but I also <a href="https://georgebarwood.github.io/" rel="nofollow noreferrer">put a copy of the manual here</a>.</p>
<p>Here is the complete class ( block.cs in the <a href="https://github.com/georgebarwood/Database" rel="nofollow noreferrer">Github project</a> ):</p>
<pre><code>namespace SQLNS
{
using G = System.Collections.Generic;
using DBNS;
class Block : EvalEnv // Represents a batch of statements or a routine (stored function or procedure) definition.
{
public Block( DatabaseImp d, bool isFunc ) { Db = d; IsFunc = isFunc; Init(); }
public readonly DatabaseImp Db;
public readonly bool IsFunc;
// Run-time fields.
System.Action[] Statements; // List of statements to be executed.
int [] Jumps; // Resolution of the ith jumpid.
int NextStatement; // Index into Statements, can be assigned to change execution control flow.
Value FunctionResult; // Holds result if block is a function.
// Type information.
public ColInfo Params; // Types of routine parameters.
public DataType ReturnType; // Function return type.
DataType [] LocalTypes; // Types of local variables.
// Compile-time lists and maps.
G.List<System.Action> StatementList; // For building Statements.
G.List<int> JumpList; // For building Jumps.
public G.List<DataType> LocalTypeList; // For building LocalTypes.
G.Dictionary<string,int> VarMap; // Lookup dictionary for local variables.
G.Dictionary<string,int> LabelMap; // Lookup dictionary for local labels.
int LabelUndefined = 0; // Number of labels awaiting definition.
// Statement preparation ( compile phase ).
public void Init()
{
Statements = null;
Jumps = null;
LocalTypes = null;
StatementList = new G.List<System.Action>();
JumpList = new G.List<int>();
LocalTypeList = new G.List<DataType>();
VarMap = new G.Dictionary<string,int>();
LabelMap = new G.Dictionary<string,int>();
}
public void Complete()
{
Statements = StatementList.ToArray();
Jumps = JumpList.ToArray();
LocalTypes = LocalTypeList.ToArray();
StatementList = null;
JumpList = null;
LocalTypeList = null;
VarMap = null;
LabelMap = null;
}
public void AddStatement( System.Action a ) { StatementList.Add( a ); }
public void Declare( string varname, DataType type ) // Declare a local variable.
{
VarMap[ varname ] = LocalTypeList.Count;
LocalTypeList.Add( type );
}
public int Lookup( string varname ) // Gets the number of a local variable, -1 if not declared.
{
int result; return VarMap.TryGetValue( varname, out result ) ? result : -1;
}
public int LookupJumpId( string label ) // Gets jumpid for a label.
{
int result; return LabelMap.TryGetValue( label, out result ) ? result : -1;
}
public int GetJumpId()
{
int jumpid = JumpList.Count; JumpList.Add( -1 );
return jumpid;
}
public int GetStatementId()
{
return StatementList.Count;
}
public void SetJump( int jumpid )
{
JumpList[ jumpid ] = GetStatementId();
}
public bool SetLabel( string name ) // returns true if label already defined ( an error ).
{
int sid = GetStatementId();
int jumpid = LookupJumpId( name );
if ( jumpid < 0 )
{
jumpid = JumpList.Count;
LabelMap[ name ] = jumpid;
JumpList.Add( sid );
}
else
{
if ( JumpList[ jumpid ] >= 0 ) return true;
JumpList[ jumpid ] = sid;
LabelUndefined -= 1;
}
return false;
}
public void CheckLabelsDefined( Exec e )
{
if ( LabelUndefined != 0 ) e.Error( "Undefined Goto Label" );
}
public int GetForId()
{
int forid = LocalTypeList.Count;
LocalTypeList.Add( DataType.None );
return forid;
}
public System.Action GetGoto( string name )
{
int jumpid = LookupJumpId( name );
if ( jumpid < 0 )
{
jumpid = GetJumpId();
LabelMap[ name ] = jumpid;
LabelUndefined += 1;
return () => Goto( jumpid );
}
else
{
int sid = JumpList[ jumpid ];
return () => JumpBack( sid );
}
}
// Statement execution.
Value [] InitLocals()
{
int n = LocalTypes.Length;
var result = new Value[ n ];
for ( int i = 0; i < n; i += 1 ) result[ i ] = DTI.Default( LocalTypes[ i ] );
return result;
}
void ExecuteStatements( ResultSet rs ) // Statement execution loop.
{
ResultSet = rs;
NextStatement = 0;
while ( NextStatement < Statements.Length ) Statements[ NextStatement++ ]();
}
public void ExecuteBatch( ResultSet rs )
{
Locals = InitLocals();
ExecuteStatements( rs );
}
public Value ExecuteRoutine( EvalEnv e, Exp.DV [] parms )
{
// Allocate the local variables.
var locals = InitLocals();
// Evaluate the parameters to be passed, saving them in the newly allocated local variables.
for ( int i = 0; i < parms.Length; i += 1 ) locals[ i ] = parms[ i ]( e );
// Save local state.
var save1 = Locals; var save2 = NextStatement;
Locals = locals;
if ( IsFunc )
ExecuteStatements( e.ResultSet );
else
try
{
ExecuteStatements( e.ResultSet );
}
catch ( System.Exception exception )
{
Db.SetRollback();
ResultSet.Exception = exception;
}
// Restore local state.
NextStatement = save2; Locals = save1;
return FunctionResult;
}
public void Execute( Exp.DS e ) // Execute a string expression.
{
string s = e( this );
try
{
Db.ExecuteSql( s, ResultSet );
}
catch ( System.Exception exception )
{
Db.SetRollback();
ResultSet.Exception = exception;
}
}
public void Goto( int jumpId )
{
NextStatement = Jumps[ jumpId ];
}
public void Return( Exp.DV e )
{
if ( IsFunc ) FunctionResult = e( this );
NextStatement = Statements.Length;
}
public void If( Exp.DB test, int jumpid )
{
if ( !test( this ) ) NextStatement = Jumps[ jumpid ];
}
public void JumpBack( int statementId )
{
NextStatement = statementId;
}
public void Select( TableExpression te )
{
te.FetchTo( ResultSet, this );
}
public void Set( TableExpression te, int [] assigns )
{
te.FetchTo( new SetResultSet( assigns, this ), this );
}
public void InitFor( int forid, TableExpression te, int[] assigns )
{
Locals[ forid ]._O = new ForState( te, assigns, this );
}
public void For( int forid, int breakid )
{
ForState f = (ForState) Locals[ forid ]._O;
if ( f == null || !f.Fetch() ) NextStatement = Jumps[ breakid ];
}
public void Insert( Table t, TableExpression te, int[] colIx, int idCol )
{
long lastId = t.Insert( te, colIx, idCol, this );
if ( ResultSet != null ) ResultSet.LastIdInserted = lastId;
}
public void SetMode( Exp.DL e )
{
ResultSet.SetMode( e( this ) );
}
class SetResultSet : ResultSet // Implements SET assignment of local variables.
{
int [] Assigns;
Block B;
public SetResultSet( int [] assigns, Block b )
{
Assigns = assigns;
B = b;
}
public override bool NewRow( Value [] r )
{
for ( int i=0; i < Assigns.Length; i += 1 ) B.Locals[ Assigns[ i ] ] = r[ i ];
return false; // Only one row is assigned.
}
} // end class SetResultSet
class ForState // Implements FOR statement.
{
G.IEnumerator<bool> Cursor;
Value[] Row;
int [] Assigns;
Value[] Locals;
public ForState( TableExpression te, int[] assigns, Block b )
{
Assigns = assigns;
Locals = b.Locals;
Row = new Value[ te.ColumnCount ];
Cursor = te.GetAll( Row, null, b ).GetEnumerator();
}
public bool Fetch()
{
if ( !Cursor.MoveNext() ) return false;
for ( int i = 0; i < Assigns.Length; i += 1 )
Locals[ Assigns[ i ] ] = Row[ i ];
return true;
}
} // end class ForState
} // end class Block
} // end namespace SQLNS
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T12:59:40.240",
"Id": "244567",
"Score": "3",
"Tags": [
"c#",
"sql",
"database"
],
"Title": "SQL database implementation - statement execution"
}
|
244567
|
<p>This is the first time I had to implement forget password meant for real-use so I had to cover code expiration.</p>
<p>My questions are:</p>
<ul>
<li>Is using jwt here bad in any way other than it's not the best?</li>
<li>If the above is yes: What cases does it not cover?</li>
<li>If the above is no: What would be the better way to go about it?</li>
</ul>
<p>Validations are done by validateRequest middleware and yup schema as an argument</p>
<pre><code>app.post("/users/send_verification_code", validateRequest(post_send_verification_code), async (req,res) => {
let { email } = req.body;
let code = Math.floor(100000 + Math.random() * 900000);
let token = createToken(null, { code, email }, "5h")
try {
await patchUser(email, { verification_token: token })
} catch (err) {
if (err.message === "The resource you tried to update does not exist") {
console.log("PASSING: The resource you tried to update does not exist")
}
else throw err
}
console.log("Valid for 5 hours, Your code is: ", code)
console.log("DEV: token is: ", token)
return res.json({
message: "success",
code: 201
})
})
app.post("/users/reset_password", validateRequest(post_reset_password), async (req, res) => {
let { email, code, new_password } = req.body;
let user = await findUserByEmail(email,"withVerificationCode")
if (!user) throw new ErrorHandler(404, "User not found");
let decoded;
try {
decoded = jwt.verify(user.verification_token, JWT_SECRET)
} catch (err) {
if (err.name === "TokenExpiredError")
throw new ErrorHandler(401, "Code has expired", [ "Verification code has expired."])
}
if (decoded.code !== code) throw new ErrorHandler(401,"Code is invalid");
await patchUser(user.id, { password: new_password })
return res.json({
message: "success",
code: 201
})
})
</code></pre>
<p>Use case example:</p>
<p><code>POST /users/send_verification_code</code> with</p>
<pre><code>{
"email": "john_doe@example.com"
}
</code></pre>
<p><code>POST /users/reset_password</code> with</p>
<pre><code>{
"email": "john_doe@example.com",
"new_password": "example123",
"confirm_new_password": "example123",
"code": 123456
}
</code></pre>
<p>Note:</p>
<ul>
<li>Only one verification code is valid at one time or none ( if expired or never called send_verification_code )</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T13:00:06.887",
"Id": "244568",
"Score": "1",
"Tags": [
"node.js",
"express.js",
"jwt"
],
"Title": "Reset password implementation using JWT for easier code invalidation/expiration?"
}
|
244568
|
<p>This is the 2nd iteration of a code review. The 1st iteration (completed) is at<br />
<a href="https://codereview.stackexchange.com/questions/244307/iter-1-reusable-robust-c-stdhashmpz-class-for-gmps-big-integer-type">Iter 1: Reusable, robust c++ std::hash<mpz_class> for GMP's big integer type</a></p>
<p><strong>1. Goal</strong></p>
<p>My intention is to provide a fast hashing algorithm to hash <a href="https://gmplib.org/" rel="noreferrer">GMP</a>'s big integer type <code>mpz_class</code> and <code>mpz_t</code> so I can use these types as keys for an <code>unordered_map</code>. The code shall be reusable for others.</p>
<p><strong>2. Current Approach</strong></p>
<p>Since C++17, the standard library provides the specialization <code>hash<string_view></code> which is used to produce the initial hash value.<br />
First, the magnitude data of the big integer is wrapped into a <code>string_view</code> and then its hash value is calculated using <code>hash<string_view></code>. This produces an initial hash value which only depends on the magnitude, but not on the sign, of the big integer.<br />
To keep the hashes of positive and negative big integers different, the initial hash value is scrambled once for negative big integers only.</p>
<p><strong>3. Code</strong></p>
<p>File <strong><code>hash_mpz.h</code></strong>:</p>
<pre><code>#ifndef HASH_MPZ_H_
#define HASH_MPZ_H_
#include <gmpxx.h>
namespace std {
template<> struct hash<mpz_srcptr> {
size_t operator()(const mpz_srcptr x) const;
};
template<> struct hash<mpz_t> {
size_t operator()(const mpz_t x) const;
};
template<> struct hash<mpz_class> {
size_t operator()(const mpz_class &x) const;
};
}
#endif /* HASH_MPZ_H_ */
</code></pre>
<p>File <strong><code>hash_mpz.cpp</code></strong>:</p>
<pre><code>#include "hash_mpz.h"
#include <cstddef>
#include <string_view>
constexpr size_t pi_size_t() {
if (sizeof(size_t) == 4) {
return 0xc90fdaa2; // floor(pi/4 * 2^32)
} else if (sizeof(size_t) == 8) {
return 0xc90fdaa22168c234; // floor(pi/4 * 2^64)
} else {
throw std::logic_error(
"sizeof(size_t) not supported. only 32 or 64 bits are supported. you can easily add the required code for other sizes.");
}
}
inline size_t scramble(size_t v) {
return v ^ (pi_size_t() + (v << 6) + (v >> 2));
}
namespace std {
size_t std::hash<mpz_srcptr>::operator()(const mpz_srcptr x) const {
string_view view { reinterpret_cast<char*>(x->_mp_d), abs(x->_mp_size)
* sizeof(mp_limb_t) };
size_t result = hash<string_view> { }(view);
// produce different hashes for negative x
if (x->_mp_size < 0) {
result = scramble(result);
}
return result;
}
size_t hash<mpz_t>::operator()(const mpz_t x) const {
return hash<mpz_srcptr> { }(static_cast<mpz_srcptr>(x));
}
size_t hash<mpz_class>::operator()(const mpz_class &x) const {
return hash<mpz_srcptr> { }(x.get_mpz_t());
}
}
</code></pre>
<p>File <strong><code>main.cpp</code></strong>:</p>
<pre><code>#include <iostream>
#include <gmpxx.h>
#include <unordered_map>
#include "hash_mpz.h"
using namespace std;
int main() {
mpz_class a;
mpz_ui_pow_ui(a.get_mpz_t(), 168, 16);
cout << "a : " << a << endl;
cout << "hash( a): " << (hash<mpz_class> { }(a)) << endl;
cout << "hash(-a): " << (hash<mpz_class> { }(-a)) << endl;
unordered_map<mpz_class, int> map;
map[a] = 2;
cout << "map[a] : " << map[a] << endl;
return 0;
}
</code></pre>
<p><strong>4. Question</strong></p>
<p>Is there anything which can benefit from further improvement?</p>
|
[] |
[
{
"body": "<h1>Make functions that should not be exported <code>static</code></h1>\n<p>Functions that should only be available locally should be marked <code>static</code>. This applies to <code>pi_size_t()</code> and <code>scramble()</code> in <code>hash_mpz.cpp</code>.</p>\n<h1>Avoid using <code>std::endl</code></h1>\n<p>Use <a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\"><code>"\\n"</code> instead of <code>std::endl</code></a>, the latter is equivalent to <code>"\\n"</code>, but also forces a flush of the output. This is rarely necessary, and might hurt performance, especially when writing to a file, or when standard output is redirected to a file.</p>\n<h1>Consider not <code>using namespace std</code></h1>\n<p>It's very good that you are not <code>using namespace std</code> in the header files. But consider <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">not using it at all</a>, since even if only used in <code>.cpp</code> files it can result in namespace conflicts that are hard to debug. If you do find yourself typing <code>std::</code> a lot and want to avoid it, consider only importing the names that you do use from <code>std::</code>, like so:</p>\n<pre><code>using std::cout;\nusing std::unordered_map;\n</code></pre>\n<h1>Final nitpicks</h1>\n<ul>\n<li>There's still one unnecessary <code>std::</code> inside the <code>namespace std</code> block in <code>hash_mpz.cpp</code>.</li>\n<li>You don't need <code>return 0</code> at the end of <code>main()</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T09:14:14.763",
"Id": "481213",
"Score": "0",
"body": "Regarding your sentence \"Functions that should only be available locally should be marked static.\", does \"locally\" mean \"inside of the same file\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T09:26:57.857",
"Id": "481217",
"Score": "0",
"body": "Yes. Inside the same [translation unit](https://en.wikipedia.org/wiki/Translation_unit_(programming)) to be precise."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T18:38:22.890",
"Id": "244737",
"ParentId": "244571",
"Score": "3"
}
},
{
"body": "<h2>You're not my library!</h2>\n<p>I think it unwise to add additional symbols to <code>std</code>. It's great to use a namespace for the purpose of defining a library, but it's both surprising and confusing for a third-party user to need to use <code>std</code> to get your code which is not STL code. Just make your own name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T09:00:17.423",
"Id": "481211",
"Score": "0",
"body": "Have you tried modifying the code in this way? It's not as trivial as it looks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T10:21:52.763",
"Id": "481221",
"Score": "0",
"body": "cf. https://stackoverflow.com/questions/3072248/why-arent-template-specializations-allowed-to-be-in-different-namespaces"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T19:53:18.557",
"Id": "244748",
"ParentId": "244571",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "244737",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T14:16:50.717",
"Id": "244571",
"Score": "6",
"Tags": [
"c++",
"hashcode",
"gmp"
],
"Title": "Iter 2: Reusable, robust c++ std::hash<mpz_class> for GMP's big integer type"
}
|
244571
|
<p><strong>Please ignore the comments in the code for the purpose of reviewing. I just require tips on using SOLID principles and how classes can be used in this code.Comments in the code are for mapping the image in my brain to what I want to do in words. Sorry for the mistakes in the comments of the code. I wrote them really fast.</strong></p>
<p>This is a follow-up to <a href="https://codereview.stackexchange.com/questions/243939/use-django-engine-to-fill-in-a-html-file-on-storage-no-template-and-use-weasy">Use django engine to fill in a .html file on storage (no template) and use weasyPrint to convert it to PDF</a>.</p>
<p>I followed the instructions and refactored my code as per the suggestions by @Reinderien but recently the client said to me that on the webpage there are n ID's and n different PDF's are to be returned based on which ID the user selects. Currently n=2.
I have a radio select of which the visitor can select any one of the ID's and enter the correct value of input. So basically I get the value of the radio button as <code>opt</code> and <code>value</code> as the actual ID value. Now I have to check the database to find the column which is named as <code>opt</code> and the row where value in that column is <code>value</code>.
Initially there was just one form/word_document/.html_file that was being converted to PDF but now there are three forms. I know it's easy at the moment but I think I need some ideas on whether use of <code>class</code> should be done and if so then how? I 'm really interested in refactoring this code and use SOLID principles. Surely, I 'm beginner level with design patterns and SOLID principles but it's just more and more code reviews that will make my eye catch 'how much' 'single responsibility' a function should be and if really if my function is extensible w/o modifying it. Please assume I 'm good enough at decorator,inheritance and class composition.
Also I couldn't get a way to remove the making of temporary files. There is temporary saving of the PDF made by weasyPrint.
I don't want that you code it up for me. Just few lines of explanation or a small UML diagram would be more than sufficient.</p>
<p>vars.cfg</p>
<pre><code>[FILES]
HTML_FILE_NAME_FOL=C:\Users\Dell\Desktop\gjh\formfill\media\mydoc-utf8.htm
HTML_FILE_NAME_DPID=C:\Users\Dell\Desktop\gjh\formfill\media\mydoc-utf8.htm
EXCEL_FILE_NAME=C:\Users\Dell\Desktop\gjh\formfill\media\AM2.CSV
</code></pre>
<p>forms.py</p>
<pre><code>from django import forms
class InputData(forms.Form):
opt = forms.ChoiceField(label="Enter Data:", choices=[('FOL', "Folio Number"),
('DPID', 'Dpid')
],
widget=forms.RadioSelect)
value = forms.CharField(label="Value ", widget=forms.TextInput(
attrs={'pattern': '[A-Z0-9]{0,16}'}))
</code></pre>
<p>backend.py(improved)</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
def remove_temp_file():
if os.path.exists('temp.pdf'):
os.remove('temp.pdf')
def get_config_object():
config = configparser.RawConfigParser()
config.optionxform = str
config.read('vars.cfg')
return config
config = get_config_object()
def load_custom_tags(opt):
""" TODO : Django by its nature will only convert a 'template' to HTML.
For that the file is being saved to the default location that is the template folder.
I just observed that I do now need to run this function again and again but once once similar
to like what one would do if one wants to fill the database the first time.
Is this possible anyway? I have to give the project folder to the client. He will place all the forms
paths in the cfg file.
vars.cfg
[FILES]
HTML_FILE_NAME_FOL=C:\Users\Dell\Desktop\gjh\formfill\media\mydoc-utf8.htm
HTML_FILE_NAME_DPID=C:\Users\Dell\Desktop\gjh\formfill\media\mydoc-utf8.htm
EXCEL_FILE_NAME=C:\Users\Dell\Desktop\gjh\formfill\media\AM2.CSV
"""
html = codecs.open(
config["FILES"][f"HTML_FILE_NAME_{opt.upper()}"],
encoding='utf-8').read()
if not html.startswith(r"{% load"):
html += "{% load numbersinwords %}"
with open(config["FILES"][f"HTML_FILE_NAME_{opt.upper()}"], "w", encoding="utf-8") as html_file:
html_file.write(html)
def html2pdf(row, path_form):
row = row.to_dict()
load_custom_tags()
html = render_to_string(Path(path_form).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):
remove_temp_file()
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, Path(config["FILES"][f"HTML_FILE_NAME_{opt.upper()}"]))
HTML(string=html).write_pdf("temp.pdf")
f = open("temp.pdf", "rb")
return (True, f)
return (False, f"<h1>Invalid credential {opt}: {value}</h1>")
</code></pre>
|
[] |
[
{
"body": "<h2>Configuration file paths</h2>\n<p>If possible, factor out a common path:</p>\n<pre class=\"lang-none prettyprint-override\"><code>[FILES]\nMEDIA_PATH=C:\\Users\\Dell\\Desktop\\gjh\\formfill\\media\nHTML_FILE_NAME_FOL=mydoc-utf8.htm\nHTML_FILE_NAME_DPID=mydoc-utf8.htm\nEXCEL_FILE_NAME=AM2.CSV\n</code></pre>\n<h2>Typo?</h2>\n<p><code>I do now need</code> -> <code>I do not need</code></p>\n<h2>Caching</h2>\n<blockquote>\n<p>I do [not] need to run this function again and again but once once similar\nto like what one would do if one wants to fill the database the first time.\nIs this possible anyway?</p>\n</blockquote>\n<p>Almost certainly. The easiest way to do this is check if the file exists beforehand. One risk of this approach is that it may not be thread-safe, so you may need to surround the file-check-file-write in a lock if access to that code path is multi-threaded.</p>\n<h2>Enums</h2>\n<p>Consider making an <code>Enum</code> to represent the two (?) choices for <code>opt</code> values:</p>\n<pre><code>class TagOpt(Enum):\n FOL = 'FOL'\n DPID = 'DPID'\n</code></pre>\n<p>rather than accepting it as a string.</p>\n<h2>Temporary variables</h2>\n<pre><code>config["FILES"][f"HTML_FILE_NAME_{opt.upper()}"]\n</code></pre>\n<p>should be put into a temporary variable since you write it twice; perhaps:</p>\n<pre><code>html_path = config["FILES"][f"HTML_FILE_NAME_{opt.upper()}"]\nhtml = codecs.open(html_path, encoding='utf-8').read()\nwith open(html_path, "w", encoding="utf-8") ...\n</code></pre>\n<h2>I/O costs</h2>\n<p>Depending on the load characteristics of your application, you might want to modify <code>load_custom_tags</code> to use something like an LRU cache so that a certain number of most-recently-used HTML files are kept in memory. The cost of a round trip to the hard disc might end up being inconvenient to pay.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T19:21:51.930",
"Id": "480503",
"Score": "0",
"body": "Sorry I should have explained it better but soon will with experience on how to present question better. I added those comments so that the reviewer can understand my code better. I ll just add clarification to ignore the comments. Sorry for the trouble @Reinderien"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T19:31:23.103",
"Id": "480508",
"Score": "0",
"body": "1) ENUM :where @Reinderien. In the forms.py or the backend.py? 2)Temporary variables: like temp =config[\"FILES]; temp[\"..\"]?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T19:32:59.090",
"Id": "480510",
"Score": "0",
"body": "Wow, that was some amazing info there, I didn't know that LRU cache works for file objects too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T19:34:15.240",
"Id": "480511",
"Score": "0",
"body": "_LRU cache works for file objects too_ - careful. I would not apply an LRU cache to a file handle, but that isn't what's going on here. Instead, you would apply an LRU cache to a string or enum that uniquely identifies the file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T19:35:11.743",
"Id": "480513",
"Score": "0",
"body": "_In the forms.py or the backend.py?_ - backend.py"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T19:36:26.913",
"Id": "480515",
"Score": "0",
"body": "Ya, I will put a selfie code soon. I haven't used Enum in python yet. Long ago I had used enum in c++"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T19:41:33.413",
"Id": "480517",
"Score": "0",
"body": "def main(opt, value): Here opt is a string which is the csv file's column name. Sorry I still couldn't get how to fit Enum here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T19:45:27.547",
"Id": "480519",
"Score": "0",
"body": "I really liked the method that you have told for `Caching`. How can I miss it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T06:02:00.117",
"Id": "480556",
"Score": "0",
"body": "Regarding the `Configuration file paths`, it maybe good that way but the client said to me that he will change the form. In such case it might be better to ask him to put the abs path. I made another software for him where he needed to put paths and he preferred to put abs path."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T19:16:01.090",
"Id": "244742",
"ParentId": "244575",
"Score": "3"
}
},
{
"body": "<p>No need of f strings at places required where no placeholders are there</p>\n<pre><code>return (False, f"<h1>Invalid credential :"\n " Multiple candidates exists"\n "with given credential</h1>")\n</code></pre>\n<p>should be simply</p>\n<pre><code>return (False, "<h1>Invalid credential :"\n " Multiple candidates exists"\n "with given credential</h1>")\n</code></pre>\n<p><strong>Open close Principle violated:</strong></p>\n<p>view.py is dependent on what type of response is being sent back from backend.py. This is bad since if more type of responses are to be returned like HttpResponse, FileResponse, JsonResponse the technique of True False can't be used. You need more than 0/1 in this case. This is not extensible code. The view cares about the response being sent.</p>\n<p>This should be better:</p>\n<p>view.py</p>\n<pre><code>def index(request):\n if request.method == "POST":\n form = InputData(request.POST)\n if form.is_valid():\n return backend.main(**form.cleaned_data)\n\n form = InputData()\n\n return render(request, "base/index.html", {\n 'forms': form\n })\n \n</code></pre>\n<p>backend.py</p>\n<pre><code>import os\n\nimport pandas as pd\nfrom weasyprint import HTML\n\nimport configparser\n\nfrom django.http import HttpResponse, FileResponse\nfrom django.template.loader import render_to_string\nfrom django.conf import settings\n\n# --------------load configurations----------------\n\n\ndef get_configurations():\n config = configparser.RawConfigParser()\n config.optionxform = str\n config.read('vars.cfg')\n return config\n\n\nconfig = get_configurations()\n# --------------load configurations----------------\n\n\ndef remove_temp_file():\n if os.path.exists('temp.pdf'):\n os.remove('temp.pdf')\n\n\ndef get_html(opt, row):\n\n row = row.to_dict()\n file_path = os.path.join(settings.MEDIA_ROOT,\n config["FILES"][f"HTML_FILE_NAME_{opt.upper()}"])\n return render_to_string(file_path, context=row)\n\n\ndef search_row_in_database(opt, value):\n df = pd.read_csv(os.path.join(settings.MEDIA_ROOT,\n config["FILES"]["EXCEL_FILE_NAME"]),\n dtype=str, keep_default_na=False)\n return df[df[opt] == value]\n\n\ndef get_pdf(opt, row):\n html = get_html(opt, row)\n HTML(string=html).write_pdf("temp.pdf")\n f = open("temp.pdf", "rb")\n return f\n\n\ndef main(opt, value):\n\n remove_temp_file()\n\n row = search_row_in_database(opt, value)\n\n # check if a single row with that ID exists\n if len(row) == 1:\n row = row.squeeze()\n return FileResponse(\n # opt is required to choose which html pdf is to be picked up\n get_pdf(opt, row),\n as_attachment=True,\n filename=config['DOWNLOAD']['DOWNLOAD_FILE_AS'])\n # no rows with that ID found\n elif len(row) == 0:\n return HttpResponse("<h1>Invalid credential {opt}: {value}. "\n "No user with that ID found</h1>")\n # in case of not multiple rows with that ID\n else:\n return HttpResponse("<h1>Invalid credential :"\n " Multiple candidates exists"\n "with given credential</h1>")\n</code></pre>\n<p>Since the html file is only created once the tag {% load numbersinwords %} should not be put like this.It should be put on creation of the html file manually. These tags can be stored in a readme.md often used with git. The user of the code should then read the readme and put the tag at the top of his html form rather than you doing it programmatically.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-02T21:53:13.740",
"Id": "480857",
"Score": "0",
"body": "I expect such type of answers to this question. Obviously I' m not referring to the f strings ."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-02T21:49:10.070",
"Id": "244907",
"ParentId": "244575",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T14:54:45.013",
"Id": "244575",
"Score": "3",
"Tags": [
"python",
"django"
],
"Title": "Make django, weasyprint code object oriented"
}
|
244575
|
<p>I built this code as part of a test project that was given to me by a company. They had given me a .csv file that contained over 9000 records and wanted me to build a program that would upload it to Firebase.</p>
<p>Firebase has limits on how much data can be uploaded at one time, so uploading a large <code>.json</code> file would not have been possible (I know this cause I tried).</p>
<p>Tried my luck with promises also- not sure if I did that right, but the program worked lol.</p>
<p>The code below works just fine, but I feel as though I could do better- perhaps make it cleaner?
I was working with Typescript for the first time. So if anyone has any tips on this please let me know. Typescript and I are not friends.</p>
<p>Tell me your thoughts please!</p>
<pre><code>#!/usr/bin/env node
import csv from 'csvtojson';
import program from 'commander';
import * as fs from 'fs';
import * as path from 'path';
import * as firebase from 'firebase';
import firebaseConfig from './config';
import { resolve, parse } from 'path';
const ShardingToCsv = require('sharding-to-csv').ShardingToCsv;
const filehound = require('filehound');
// Set up Arguments in Command Line
program
.version('1.0.0')
.option('-s, --src <path>', 'Path to .csv file')
.parse(process.argv);
// Initialize Firebase Config
firebase.initializeApp(firebaseConfig);
// Set DB for Referenced to firebase database
const db = firebase.database();
// If No DB Connection- let me know.
if (!db) {
console.log('No Database Detected');
}
// Because the .CSV file is to large to parse and upload, break it into 10 different pieces.
const shardFiles = () => {
// Set a Variable for the source path that the user inputs in
const srcPath = program.src;
// If no source path is entered, give this error message
if (!srcPath) {
console.log('Please provide valid path to .csv File');
}
// a Promise!
return new Promise((resolve, reject) => {
console.log('starting sharding process....');
// Shard Larger .csv Files to Smaller versions for Firebase upload
var sharding = new ShardingToCsv(srcPath, {
encoding: 'iso-8859-1',
maxFileSize: 1000000,
}).shard();
sharding.on('error', (err: any) => console.log(err), reject);
sharding.on('completed', () => {
console.log('Done Sharding, not to be confused with sharting!');
// resolve promise
resolve(sharding);
});
});
};
const fromDir = async () => {
// Await the sharding of the files
await shardFiles();
// Actions to create .json files for each shard.
// variable for shard directory
// Change this Directory per your application
const dir = './utils';
// Read Shard Directory
const files: any = fs.readdirSync(dir);
// Interate over the Files
for (const file of files) {
const rawData: any = file;
try {
// Parse .csv shards into json files using csvtojson
await csv()
.fromFile(`utils/${rawData}`)
.then((data) => {
fs.writeFile(
`./utils/${file}.json`,
JSON.stringify(data, null, 4),
(err) => {
if (err) {
throw err;
}
console.log(`created json file with ${file} name`);
}
);
});
} catch (err) {
console.log(err);
}
}
};
// New Function to upload to database
const uploadToDatabase = async () => {
// await creation of .json files
await fromDir();
filehound
.create()
.paths('./utils')
.ext('.json')
.find((err: any, jsonFiles: any) => {
if (err) {
return console.log(err);
}
const readFile = jsonFiles.map((jsonFile: any) => {
const dbItem = jsonFile;
const item: any = fs.readFileSync(dbItem);
const parsedItem = JSON.parse(item);
// console.log(parsedItem);
firebase.database().ref('funds').set({ parsedItem });
console.log('uploaded to database!');
});
});
};
uploadToDatabase();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T18:58:43.137",
"Id": "480159",
"Score": "1",
"body": "Just a question: are you uploading and downloading it as complete files, or are you reading small branches as well?Firebase database is for reading and uploading small parts but reading/updating often. Firebase firestore is for uploading and downloading big chunks at a time. And finally firebase storage is for treating it entirely as a file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T19:11:48.770",
"Id": "480162",
"Score": "2",
"body": "I was uploading to a Firebase Realtime Database a .csv file with over 9000 records. When I parsed the .csv file to Json it was around 30mb. Firebase as a 10mb Limit, so this program essentially shards to file into around 10 .csv files- parsed those to JSON( around 3mb each) and then uploads the individual files to Firestore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T19:35:21.180",
"Id": "480166",
"Score": "1",
"body": "Thx, was just checking why you didn't go for the other options, but when you want to set something big up and then access individual records is a logical reason. I, unfortunately, am a beginner in typescript/javaScript, so I cannot help you... I'm sorry"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T17:35:34.363",
"Id": "244580",
"Score": "2",
"Tags": [
"node.js",
"console"
],
"Title": "A Firebase Uploader CLI"
}
|
244580
|
<p>I am displaying the data from a json file onto a website, with recursive and iterative tables side by side. i have the iterative code working, but I have no idea on how to make it recursive.</p>
<p>Here is the code:</p>
<pre><code> $dataArray = json_decode($data, true);
if(is_array($dataArray)){ //first level
$result = "<table class='arrayTable'>";
foreach($dataArray as $key=>$val){ //second level
$result.="<tr><td class ='key'>".$key.": </td><td class ='value'>";
if(gettype($val)=="array"){
$result .= "<table class='arrayTable'>";
foreach($val as $subkey=>$subval){ //third level
$result.="<tr><td class ='key2'>".$subkey.": </td><td class ='value2'>";
if(gettype($subval)=="array"){
$result .= "<table class='arrayTable'>";
foreach($subval as $lowkey=>$lowval){ //fourth level
$result.="<tr><td class ='key3'>".$lowkey.": </td><td class ='value3'>";
if(gettype($lowval)!="array"){
$result.=$lowval."</td></tr>";
}else{
$result.="</td></tr>";
}
}
$result.="</table>";
}else{
$result.=$subval."</td></tr>";
}
}
$result.="</table>";
}else{
$result.=$val."</td></tr>";
}
}
$result.= "</table>";
}else{
echo "Not a valid format!";
}
return $result;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T03:46:17.337",
"Id": "480190",
"Score": "0",
"body": "Welcome to Code Review where we review working code you have written and make suggestions on how to improve that code. The part of the question about a recursive implementation is off-topic, the reason given will usually be `code not yet written or not working as expected'."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T10:35:16.523",
"Id": "480305",
"Score": "0",
"body": "A code review should be just that -- only analytical feedback. A complete code refactor can take much more time to write, test, and explain. If you have tried to refactor your script, but failed, then you have a Stack Overflow question. @Sam"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T17:57:59.673",
"Id": "480479",
"Score": "0",
"body": "@mickmackusa My question was removed from Stack Overflow, and the people there said to move it here."
}
] |
[
{
"body": "<ol>\n<li>Your code is a pain to read, please add early returns.</li>\n<li>To go with the point above, please follow PSR-12.</li>\n<li><code>iterative tables side by side</code>. Your code creates another table within a , so it's no exactly side by side.</li>\n</ol>\n<p>Here is how I refactored your code:</p>\n<ol>\n<li>I completed step 1 and 2.</li>\n<li>I have broken everything up into methods:</li>\n</ol>\n<pre><code><?php\n\nnamespace App;\n\nclass DisplayArrayTable\n{\n protected $result = '';\n\n /**\n * @param mixed $value\n */\n protected function setupMeaningFullName1(string $key, $data): void\n {\n $this->result .= "<tr><td class ='key'>{$key}: </td><td class ='value'>";\n\n if (!is_array($data)) {\n $this->result .= "{$data}</td></tr>";\n\n return;\n }\n\n $this->result .= "<table class='arrayTable'>";\n\n foreach ($data as $key => $value) {\n $this->setupMeaningFullName2($key, $value);\n }\n\n $this->result .= "</table>";\n }\n\n /**\n * @param mixed $value\n */\n protected function setupMeaningFullName2(string $key, $data): void\n {\n $this->result .= "<tr><td class ='key2'>{$key}: </td><td class ='value2'>";\n\n if (!is_array($data)) {\n $this->result .= "{$data}</td></tr>";\n\n return;\n }\n\n $this->result .= "<table class='arrayTable'>";\n\n foreach ($data as $key => $value) {\n $this->setupMeaningFullName2($key, $value);\n }\n\n $this->result .= "</table>";\n }\n\n /**\n * @param mixed $value\n */\n protected function setupMeaningFullName3(string $key, $data): void\n {\n $this->result .= "<tr><td class ='key3'>{$key}: </td><td class ='value3'>";\n\n if (!is_array($data)) {\n $this->result .= "{$data}</td></tr>";\n\n return;\n }\n\n $this->result .= "</td></tr>";\n }\n\n public function handle(array $data): string\n {\n foreach ($data as $key => $value) {\n $this->setupMeaningFullName1($key, $value);\n }\n\n return "<table class='arrayTable'>{$this->result}</table>";\n }\n}\n</code></pre>\n<ol start=\"3\">\n<li>I have identified the pattern and further refactored your code</li>\n</ol>\n<pre><code><?php\n\nnamespace App;\n\nclass DisplayArrayTable\n{\n const MAX_ITERATIONS = 3;\n protected $currentIteration = 1;\n protected $result = '';\n\n /**\n * @param mixed $value\n */\n protected function iteration(string $key, $data): void\n {\n $this->result .= "<tr><td class ='key'>{$key}: </td><td class ='value'>";\n\n if (!is_array($data)) {\n $this->result .= "{$data}</td></tr>";\n\n return;\n }\n\n if ($this->currentIteration === static::MAX_ITERATIONS) {\n $this->result .= '</td></tr>';\n \n return;\n }\n\n $this->result .= '<table class="arrayTable">';\n\n foreach ($data as $key => $value) {\n $this->currentIteration++;\n\n $this->setupMeaningFullName2($key, $value);\n }\n\n $this->result .= '</table>';\n }\n\n public function handle(array $data): string\n {\n foreach ($data as $key => $value) {\n $this->iteration($key, $value);\n }\n\n return "<table class='arrayTable'>{$this->result}</table>";\n }\n}\n</code></pre>\n<ol start=\"4\">\n<li>Performed further refactoring to improve iteration method</li>\n</ol>\n<pre><code><?php\n\nnamespace App;\n\nclass DisplayArrayTable\n{\n const MAX_ITERATIONS = 3;\n protected $currentIteration = 1;\n protected $result = '';\n\n public function handle(array $data): string\n {\n foreach ($data as $key => $value) {\n $this->iteration($key, $value);\n }\n\n return "<table class='arrayTable'>{$this->result}</table>";\n }\n\n /**\n * @param mixed $value\n */\n protected function iteration(string $key, $data): void\n {\n $this->result .= "<tr>\n <td class ='key'>{$key}: </td>\n <td class ='value'>";\n\n if (!is_array($data)) {\n $this->result .= "{$data}</td></tr>";\n\n return;\n }\n\n if ($this->currentIteration === static::MAX_ITERATIONS) {\n $this->result .= '</td></tr>';\n \n return;\n }\n\n $this->setupNewTable($data);\n }\n\n protected function setupNewTable(array $data): void \n { \n $this->result .= '<table class="arrayTable">';\n\n foreach ($data as $key => $value) {\n $this->currentIteration++;\n\n $this->iteration($key, $value);\n }\n\n $this->result .= '</table>';\n }\n}\n</code></pre>\n<p>So, all you need to do now is call this call and pass in a valid array</p>\n<pre><code>use App\\DisplayArrayTable;\n\n...\n\n$dataArray = json_decode($data, true);\n\nif ($dataArray && is_array($dataArray)) {\n $html = (new DisplayArrayTable)->handle($dataArray);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T10:13:39.990",
"Id": "244607",
"ParentId": "244582",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T17:54:17.933",
"Id": "244582",
"Score": "0",
"Tags": [
"php",
"recursion",
"iteration"
],
"Title": "Recursively displaying json data on website"
}
|
244582
|
<p>I wrote this code where division can be done without using C's builtin operator:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <math.h>
int idiv(int a, int b) {
return a * (pow(b, -1));
}
int main(void) {
/* 15/3 is 5 */
printf("%d\n", idiv(15, 3));
return 0;
}
</code></pre>
<p>Is there anything I could do to make this code faster? I benchmarked it with the division operator and it was more than 10x faster.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T19:28:35.847",
"Id": "480165",
"Score": "0",
"body": "You can do this with integers rather than floating-point, see https://libdivide.com/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T19:49:10.647",
"Id": "480167",
"Score": "1",
"body": "To be facetious, you could use inline assembly that uses the machine's divide instruction without using the \"C built-in operator\" and this would meet the requirement at face value. Why are you doing this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T19:53:09.097",
"Id": "480168",
"Score": "0",
"body": "@Reinderien -- The ARM architecture does not necessarily have a builtin division instruction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T19:53:49.797",
"Id": "480169",
"Score": "1",
"body": "Sure, but you didn't specify which architecture you're on, or whether this needs to be portable. This question is littered with unknowns."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T19:54:50.550",
"Id": "480170",
"Score": "0",
"body": "@Reinderien -- No this does not need to be portable-- it needs to work efficiently on ARM."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T19:57:58.020",
"Id": "480171",
"Score": "0",
"body": "If you've proven that your ARM compiler can render `/` as an efficient division, can you show what assembly it generates, and/or the output listing? There's a pretty good chance that it's calling into a runtime function, and there's not a very good chance at all that you can do better than what it's doing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T20:56:32.187",
"Id": "480175",
"Score": "0",
"body": "If you are targetting an ARM CPU without a DIV instruction, then you should still be able to write `a / b` in C and get working code. The compiler takes care of converting your code into whatever instructions are necessary to get the desired result. Ensure you enable compiler optimizations, so that the compiler will try to generate optimal code for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T21:00:42.940",
"Id": "480176",
"Score": "0",
"body": "@G.Sliepen -- I know, but I don't want to rely on libgcc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T21:06:56.187",
"Id": "480177",
"Score": "0",
"body": "But now you are relying on libm for `pow()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T21:42:51.553",
"Id": "480179",
"Score": "0",
"body": "@G.Sliepen -- Yeah I got lazy and decided I would make my own `pow` later :)"
}
] |
[
{
"body": "<p>It is unclear what toolchain do you use and what is target processor. However, I can guess about performance degradation. <code>pow</code> function usually works with floating point values. Moreover, most probably power with negitive exp will also use division.\nI compiled following code with ARM gcc 8.2 with -O3 flag:</p>\n<pre><code>#include <math.h>\n\nint idiv(int a, int b) {\n return a * (pow(b, -1));\n}\n\nint idiv2(int a, int b) {\n\n return a/b;\n}\n</code></pre>\n<p>I've got following assebly listing:</p>\n<pre><code>idiv:\n push {r4, r5, r6, lr}\n mov r6, r0\n mov r0, r1\n bl __aeabi_i2d\n mov r2, r0\n mov r3, r1\n mov r0, #0\n ldr r1, .L4\n bl __aeabi_ddiv\n mov r4, r0\n mov r0, r6\n mov r5, r1\n bl __aeabi_i2d\n mov r2, r0\n mov r3, r1\n mov r0, r4\n mov r1, r5\n bl __aeabi_dmul\n bl __aeabi_d2iz\n pop {r4, r5, r6, pc}\n.L4:\n .word 1072693248\nidiv2:\n push {r4, lr}\n bl __aeabi_idiv\n pop {r4, pc}\n</code></pre>\n<p>From assebly code the reson of performance problems is obvious. And we still dependent on ABI.\nIf you want to have code that uses only assebly instructions? then you can implement integer division with "shift and subtract". Or you can google for some open source implementation of it. For example I found one <a href=\"https://github.com/OP-TEE/optee_os/blob/master/lib/libutils/isoc/arch/arm/arm32_aeabi_divmod.c\" rel=\"nofollow noreferrer\">here</a>. Here is slightly modified example from <a href=\"https://gist.github.com/ichenq/4243253\" rel=\"nofollow noreferrer\">here</a>:</p>\n<pre><code>void unsigned_divide(unsigned int dividend,\n unsigned int divisor,\n unsigned int *quotient,\n unsigned int *remainder )\n{\n unsigned int t, num_bits;\n unsigned int q, bit, d;\n int i;\n\n *remainder = 0;\n *quotient = 0;\n\n if (divisor == 0)\n return;\n\n if (divisor > dividend) {\n *remainder = dividend;\n return;\n }\n\n if (divisor == dividend) {\n *quotient = 1;\n return;\n }\n\n num_bits = 32;\n\n while (*remainder < divisor) {\n bit = (dividend & 0x80000000) >> 31;\n *remainder = (*remainder << 1) | bit;\n d = dividend;\n dividend = dividend << 1;\n num_bits--;\n }\n\n /* The loop, above, always goes one iteration too far.\n To avoid inserting an "if" statement inside the loop\n the last iteration is simply reversed. */\n dividend = d;\n *remainder = *remainder >> 1;\n num_bits++;\n\n for (i = 0; i < num_bits; i++) {\n bit = (dividend & 0x80000000) >> 31;\n *remainder = (*remainder << 1) | bit;\n t = *remainder - divisor;\n q = !((t & 0x80000000) >> 31);\n dividend = dividend << 1;\n *quotient = (*quotient << 1) | q;\n if (q) {\n *remainder = t;\n }\n }\n} /* unsigned_divide */\n\n#define ABS(x) ((x) < 0 ? -(x) : (x))\n\nvoid signed_divide(int dividend,\n int divisor,\n int *quotient,\n int *remainder )\n{\n unsigned int dend, dor;\n unsigned int q, r;\n\n dend = ABS(dividend);\n dor = ABS(divisor);\n unsigned_divide( dend, dor, &q, &r );\n\n /* the sign of the remainder is the same as the sign of the dividend\n and the quotient is negated if the signs of the operands are\n opposite */\n *quotient = q;\n if (dividend < 0) {\n *remainder = -r;\n if (divisor > 0)\n *quotient = -q;\n }\n else { /* positive dividend */\n *remainder = r;\n if (divisor < 0)\n *quotient = -q;\n }\n\n} /* signed_divide */\n</code></pre>\n<p>You can take any, verify it and optimize it according to your needs. Generalized functions are usually more complicated than specialized.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T13:22:14.447",
"Id": "244659",
"ParentId": "244585",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244659",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T19:06:20.227",
"Id": "244585",
"Score": "1",
"Tags": [
"performance",
"c",
"mathematics",
"benchmarking"
],
"Title": "C - Division from scratch"
}
|
244585
|
<h2> Introduction </h2>
As a programming exercise I recently wrote this automatic differentiation library based on <a href="https://en.wikipedia.org/wiki/Automatic_differentiation#Forward_accumulation" rel="nofollow noreferrer">forward accumulation</a>. It should offer a simple way to create mathematical functions whose directional derivatives can be computed. For example:
<pre><code>#include <iostream>
#include "autodiff.h"
int main()
{
mx::Var x, y;
mx::SField f = mx::sqrt(mx::pow(x,2)+mx::pow(y,2));
f.setVariables({&x, &y});
std::cout << f({3.0, 4.0}) << std::endl; //prints 5
std::cout << f.derivative({-1.0, 0.0}, x) << std::endl; //prints -1
return 0;
}
</code></pre>
<p>It basically works as follows:</p>
<p>The class <code>SField</code> (scalar field) holds a <code>vector</code> of <code>Var</code> pointers and a pointer to the top node of an expression tree consisting of <code>Node</code>s:</p>
<ul>
<li><code>ConstNode</code>'s just hold a constant value. They are created when an <code>SField</code> is initialized from a double.</li>
<li><code>VarNode</code>s hold the value of the variable objects (<code>Var</code>) they correspond to.</li>
<li><code>UnOp</code>and <code>BinOp</code> hold pointers to basic mathematical operations (<code>BaseUnOp</code> and <code>BaseBinOp</code>) like addition and multiplication but also exponential and trigonometric functions. They also point to one or two input nodes which can be any of the node types in this list.</li>
</ul>
<p>The objects of type <code>BaseUnOp</code> and <code>BaseBinOp</code> contain function pointers to the (hard coded) partial derivatives of the elementary operations. From this, the derivative can be computed by repeatedly applying the chain rule while traversing the expression tree. The base operation objects also contain the methods for combining two <code>SField</code>'s (i.e. connecting the expression graphs).</p>
<p>The <code>setVariable</code> methods are necessary to specify in which order the variables shall be assigned when evaluating the function or its derivative.</p>
<h2>Code</h2>
autodiff.h
<pre><code>#ifndef AUTODIFF_H_INCLUDED
#define AUTODIFF_H_INCLUDED
#include <memory>
#include <vector>
namespace mx
{
class SField;
class Var;
namespace IMPLEMENTATION
{
class Node;
class VarNode;
class ConstNode;
class UnOp;
class BinOp;
class BaseUnOp;
class BaseBinOp;
}
class SField
{
friend IMPLEMENTATION::BaseUnOp;
friend IMPLEMENTATION::BaseBinOp;
private:
std::shared_ptr<IMPLEMENTATION::Node> start_Node;
std::vector<Var*> var_ptrs;
SField(std::shared_ptr<IMPLEMENTATION::Node> head_node) : start_Node(head_node) {}
SField(std::shared_ptr<IMPLEMENTATION::Node> head_node, const std::vector<Var*>& Var_ptrs)
: start_Node(head_node), var_ptrs(Var_ptrs) {}
public:
SField(const double& const_val);
SField() : SField(0) {}
SField(Var& x);
SField(std::vector<Var>& Var_ptrs) : SField() {setVariables(Var_ptrs);}
void setVariables(const std::vector<Var*>& Var_ptrs) {this->var_ptrs = Var_ptrs;}
void setVariables(std::vector<Var>& vars);
double operator()(const std::vector<double>&) const;
double operator()(const double&) const;
double derivative(const std::vector<double>&, const std::vector<double>&) const;
double derivative(const std::vector<double>&, const Var&) const;
double derivative(const double&, const double&) const;
double valueAtLastPosition() const;
SField& operator+=(const SField&);
SField& operator*=(const SField&);
SField& operator-=(const SField&);
SField& operator/=(const SField&);
};
class Var
{
friend SField;
private:
std::shared_ptr<IMPLEMENTATION::VarNode> vn;
public:
Var();
};
namespace IMPLEMENTATION
{
class Node
{
public:
mutable double value;
virtual double eval() const = 0;
virtual double derive() const = 0;
};
class VarNode : public Node
{
public:
double value_dot;
VarNode() = default;
double eval() const {return value;}
double derive() const {return value_dot;}
};
class ConstNode : public Node
{
public:
ConstNode(const double& const_val) {value = const_val;}
ConstNode() : ConstNode(0.0) {}
double eval() const {return value;}
double derive() const {return 0.0;}
};
class UnOp : public Node
{
private:
const BaseUnOp& f;
std::shared_ptr<Node> g;
public:
UnOp() = delete;
UnOp(const BaseUnOp& operation, std::shared_ptr<Node> input);
double eval() const;
double derive() const;
};
class BinOp : public Node
{
private:
const BaseBinOp& f;
std::shared_ptr<Node> g;
std::shared_ptr<Node> h;
public:
BinOp() = delete;
BinOp(const BaseBinOp& operation, std::shared_ptr<Node> input1, std::shared_ptr<Node> input2);
double eval() const;
double derive() const;
};
class BaseUnOp
{
typedef double fn(const double&);
private:
const fn* f;
public:
BaseUnOp() = delete;
BaseUnOp(fn* fun, fn* deriv) : f(fun), dfdx(deriv){}
double operator()(const double& x) const {return f(x);}
SField operator()(const SField& f) const;
const fn* dfdx;
};
class BaseBinOp
{
typedef double fn(const double&, const double&);
private:
const fn* f;
public:
BaseBinOp() = delete;
BaseBinOp(fn* fun, fn* x_deriv, fn* y_deriv) : f(fun), dfdx(x_deriv), dfdy(y_deriv){}
double operator()(const double& x, const double& y) const {return f(x,y);}
SField operator()(const SField&, const SField&) const;
const fn* dfdx;
const fn* dfdy;
};
///////////////////////////////////////////////////////////////////////////////////////////////
//LIST OF BASE OPERATIONS//////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
constexpr double b_add (const double& x, const double& y);
constexpr double b_add_del_x (const double& x, const double& y);
constexpr double b_add_del_y (const double& x, const double& y);
constexpr double b_multiply (const double& x, const double& y);
constexpr double b_multiply_del_x (const double& x, const double& y);
constexpr double b_multiply_del_y (const double& x, const double& y);
constexpr double b_subtract (const double& x, const double& y);
constexpr double b_subtract_del_x (const double& x, const double& y);
constexpr double b_subtract_del_y (const double& x, const double& y);
constexpr double b_divide (const double& x, const double& y);
constexpr double b_divide_del_x (const double& x, const double& y);
constexpr double b_divide_del_y (const double& x, const double& y);
double b_power (const double& x, const double& y);
double b_pow_del_x (const double& x, const double& y);
double b_pow_del_y (const double& x, const double& y);
double b_sqrt (const double& x);
double b_sqrt_del (const double& x);
constexpr double b_negate (const double& x);
constexpr double b_negate_del (const double& x);
double b_sin (const double& x);
double b_cos (const double& x);
double b_cos_del (const double& x);
double b_tan (const double& x);
double b_tan_del (const double& x);
double b_exp (const double& x);
double b_log (const double& x);
double b_log_del (const double& x);
}
///////////////////////////////////////////////////////////////////////////////////////////////
//GLOBAL BASE OPERATION OBJECTS////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
extern const IMPLEMENTATION::BaseBinOp add;
extern const IMPLEMENTATION::BaseBinOp multiply;
extern const IMPLEMENTATION::BaseBinOp subtract;
extern const IMPLEMENTATION::BaseBinOp divide;
extern const IMPLEMENTATION::BaseBinOp pow;
extern const IMPLEMENTATION::BaseUnOp sqrt;
extern const IMPLEMENTATION::BaseUnOp negation;
extern const IMPLEMENTATION::BaseUnOp sin;
extern const IMPLEMENTATION::BaseUnOp cos;
extern const IMPLEMENTATION::BaseUnOp tan;
extern const IMPLEMENTATION::BaseUnOp exp;
extern const IMPLEMENTATION::BaseUnOp log;
//OPERATOR OVERLOADING
SField operator+(const SField& f, const SField& g);
SField operator*(const SField& f, const SField& g);
SField operator-(const SField& f, const SField& g);
SField operator/(const SField& f, const SField& g);
SField operator-(const SField& f);
}
#endif // AUTODIFF_H_INCLUDED
</code></pre>
<br>
<p>autodiff.cpp</p>
<pre><code>#include "autodiff.h"
#include <cmath>
#include <cassert>
namespace mx
{
///////////////////////////////////////////////////////////////////////////////////////////////
//SFIELD///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
SField::SField(const double& const_val) : start_Node(new IMPLEMENTATION::ConstNode(const_val)) {}
SField::SField(Var& x) : start_Node(x.vn)
{
var_ptrs.push_back(&x);
}
void SField::setVariables(std::vector<Var>& vars)
{
var_ptrs.clear();
auto end = vars.end();
for (auto it = vars.begin(); it != end; ++it)
{
var_ptrs.push_back(&(*it));
}
}
double SField::operator()(const std::vector<double>& position) const
{
unsigned N = position.size();
assert(N == var_ptrs.size());
for (unsigned i = 0; i != N; ++i)
{
var_ptrs[i]->vn->value = position[i];
}
return start_Node->eval();
}
double SField::operator()(const double& position) const
{
return this->operator()(std::vector<double>{position});
}
double SField::derivative(const std::vector<double>& position, const std::vector<double>& direction) const
{
unsigned N = var_ptrs.size();
assert(N == position.size());
assert(N == direction.size());
for (unsigned i = 0; i != N; ++i)
{
var_ptrs[i]->vn->value = position[i];
var_ptrs[i]->vn->value_dot = direction[i];
}
return start_Node->derive();
}
double SField::derivative(const std::vector<double>& position, const Var& var_ptr) const
{
unsigned N = var_ptrs.size();
assert(N == position.size());
for (unsigned i = 0; i != N; ++i)
{
var_ptrs[i]->vn->value = position[i];
var_ptrs[i]->vn->value_dot = 0.0;
}
var_ptr.vn->value_dot = 1.0;
return start_Node->derive();
}
double SField::derivative(const double& position, const double& direction) const
{
return this->derivative(std::vector<double>{position},std::vector<double>{direction});
}
double SField::valueAtLastPosition() const
{
return start_Node->value;
}
SField& SField::operator+=(const SField& g) {return *this = *this+g;}
SField& SField::operator*=(const SField& g) {return *this = *this*g;}
SField& SField::operator-=(const SField& g) {return *this = *this-g;}
SField& SField::operator/=(const SField& g) {return *this = *this/g;}
///////////////////////////////////////////////////////////////////////////////////////////////
//VAR//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
Var::Var() : vn(new IMPLEMENTATION::VarNode()) {}
namespace IMPLEMENTATION
{
///////////////////////////////////////////////////////////////////////////////////////////////
//NODE/////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
//CONSTNODE////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
//UNOP/////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
UnOp::UnOp(const BaseUnOp& operation, std::shared_ptr<Node> input) : f(operation), g(input)
{
value = operation(input->value);
}
double UnOp::eval() const
{
return f(g->eval());
}
double UnOp::derive() const
{
const double& g_dot = g->derive();
value = f(g->value);
return f.dfdx(g->value)*g_dot;
}
///////////////////////////////////////////////////////////////////////////////////////////////
//BINOP////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
BinOp::BinOp(const BaseBinOp& operation, std::shared_ptr<Node> input1, std::shared_ptr<Node> input2): f(operation), g(input1), h(input2)
{
value = operation(input1->value, input2->value);
}
double BinOp::eval() const
{
return f(g->eval(),h->eval());
}
double BinOp::derive() const
{
const double& g_dot = g->derive();
const double& h_dot = h->derive();
value = f(g->value, h->value);
return ((g_dot == 0.0) ? 0.0 : f.dfdx(g->value, h->value)*g_dot)
+((h_dot == 0.0) ? 0.0 : f.dfdy(g->value, h->value)*h_dot);
}
///////////////////////////////////////////////////////////////////////////////////////////////
//BASEUNOP/////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
SField BaseUnOp::operator()(const SField& f) const
{
std::shared_ptr<UnOp> op_ptr(new UnOp(*this, f.start_Node));
return SField(op_ptr, f.var_ptrs);
}
///////////////////////////////////////////////////////////////////////////////////////////////
//BASEBINOP////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
SField BaseBinOp::operator()(const SField& f, const SField& g) const
{
std::shared_ptr<BinOp> op_ptr(new BinOp(*this, f.start_Node, g.start_Node));
return SField(op_ptr, f.var_ptrs);
}
///////////////////////////////////////////////////////////////////////////////////////////////
//LIST OF BASE OPERATIONS//////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
constexpr double b_add (const double& x, const double& y) {return x+y;}
constexpr double b_add_del_x (const double& x, const double& y) {return 1.0;}
constexpr double b_add_del_y (const double& x, const double& y) {return 1.0;}
constexpr double b_multiply (const double& x, const double& y) {return x*y;}
constexpr double b_multiply_del_x (const double& x, const double& y) {return y;}
constexpr double b_multiply_del_y (const double& x, const double& y) {return x;}
constexpr double b_subtract (const double& x, const double& y) {return x-y;}
constexpr double b_subtract_del_x (const double& x, const double& y) {return 1.0;}
constexpr double b_subtract_del_y (const double& x, const double& y) {return -1.0;}
constexpr double b_divide (const double& x, const double& y) {return x/y;}
constexpr double b_divide_del_x (const double& x, const double& y) {return 1.0/y;}
constexpr double b_divide_del_y (const double& x, const double& y) {return -x/(y*y);}
double b_pow (const double& x, const double& y) {return std::pow(x,y);}
double b_pow_del_x (const double& x, const double& y) {return y*std::pow(x,y-1);}
double b_pow_del_y (const double& x, const double& y) {return (x == 0) ? 0 : std::pow(x,y)*std::log(x);}
double b_sqrt (const double& x) {return std::sqrt(x);}
double b_sqrt_del (const double& x) {return 0.5/std::sqrt(x);}
constexpr double b_negate (const double& x) {return -x;}
constexpr double b_negate_del (const double& x) {return -1.0;}
double b_sin (const double& x) {return std::sin(x);}
double b_cos (const double& x) {return std::cos(x);}
double b_cos_del (const double& x) {return -std::sin(x);}
double b_tan (const double& x) {return std::tan(x);}
double b_tan_del (const double& x) {double t = std::tan(x); return 1.0+t*t;}
double b_exp (const double& x) {return std::exp(x);}
double b_log (const double& x) {return std::log(x);}
double b_log_del (const double& x) {return 1.0/x;}
}
///////////////////////////////////////////////////////////////////////////////////////////////
//GLOBAL BASE OPERATION OBJECTS////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
const IMPLEMENTATION::BaseBinOp add(IMPLEMENTATION::b_add, IMPLEMENTATION::b_add_del_x, IMPLEMENTATION::b_add_del_y);
const IMPLEMENTATION::BaseBinOp multiply(IMPLEMENTATION::b_multiply, IMPLEMENTATION::b_multiply_del_x, IMPLEMENTATION::b_multiply_del_y);
const IMPLEMENTATION::BaseBinOp subtract(IMPLEMENTATION::b_subtract, IMPLEMENTATION::b_subtract_del_x, IMPLEMENTATION::b_subtract_del_y);
const IMPLEMENTATION::BaseBinOp divide(IMPLEMENTATION::b_divide, IMPLEMENTATION::b_divide_del_x, IMPLEMENTATION::b_divide_del_y);
const IMPLEMENTATION::BaseBinOp pow(IMPLEMENTATION::b_pow, IMPLEMENTATION::b_pow_del_x, IMPLEMENTATION::b_pow_del_y);
const IMPLEMENTATION::BaseUnOp sqrt(IMPLEMENTATION::b_sqrt, IMPLEMENTATION::b_sqrt_del);
const IMPLEMENTATION::BaseUnOp negation(IMPLEMENTATION::b_negate, IMPLEMENTATION::b_negate_del);
const IMPLEMENTATION::BaseUnOp sin(IMPLEMENTATION::b_sin, IMPLEMENTATION::b_cos);
const IMPLEMENTATION::BaseUnOp cos(IMPLEMENTATION::b_cos, IMPLEMENTATION::b_cos_del);
const IMPLEMENTATION::BaseUnOp tan(IMPLEMENTATION::b_tan, IMPLEMENTATION::b_tan_del);
const IMPLEMENTATION::BaseUnOp exp(IMPLEMENTATION::b_exp, IMPLEMENTATION::b_exp);
const IMPLEMENTATION::BaseUnOp log(IMPLEMENTATION::b_log, IMPLEMENTATION::b_log_del);
//OPERATOR OVERLOADS
SField operator+(const SField& f, const SField& g) {return add(f,g);}
SField operator*(const SField& f, const SField& g) {return multiply(f,g);}
SField operator-(const SField& f, const SField& g) {return subtract(f,g);}
SField operator/(const SField& f, const SField& g) {return divide(f,g);}
SField operator-(const SField& f) {return negation(f);}
}
</code></pre>
<h2>Questions</h2>
I would be thankful if someone could comment on whether or not I was able to achieve the following goals (and of course if not, what I can improve):
<ol>
<li>Code structure, style and readability: Is the code comprehensible? Are there many bad practices?</li>
<li>User Interface I: I tried to make adequate use of data encapsulation, in the sense that the user of the library has only access to those features he should, neither more nor less.</li>
<li>User Interface II: The library should be user-friendly. I think I achieved that overall (probably not that hard with only two classes that the user has access to), but I wonder if there is a better way to set the order of the variables. At the moment one can either use <code>setVariable</code> or already start with the corresponding constructor and afterwards only use compound operators (e.g. <code>+=</code>) to change the <code>SField</code>. This is allowed because (e.g.) the sum of two <code>SField</code> contains only the <code>Var</code> pointers of the left operand.</li>
<li><code>const</code> correctness and appropriate use of other keywords like <code>mutable</code>, <code>constexpr</code>, <code>friend</code>,...</li>
<li>Performance: Although I could avoid many unnecessary <code>eval</code> calls (in comparison to a prior version of this library) by caching the <code>value</code> in each node, I guess there are still ways to make the computation of the derivative more efficient.</li>
</ol>
<p>Since performance requirements always depend on the application, I want to explain what I intend to do with the library:<br>
I already used it to build a solver for arbitrary Hamiltonian systems and in particular computed the dynamics of a three-body system. I want to expand the library by vector fields and matrices and do more complicated physics simulations. As long as I don't want to simulate tens of thousands of particles I guess this should be possible even for real-time simulations.<br>
I also plan to create a neural network class with the gradient descent being based on this library. I think here I will need at least <span class="math-container">\$10^4-10^5\$</span> variables (weights) already for simpler applications (e.g. training the <a href="http://yann.lecun.com/exdb/mnist/" rel="nofollow noreferrer">MNIST</a> set).<br>
Do you think it is reasonable to use this library for those purposes? Of course, I could use a professional AD library, but since all I do is intended entirely for learning purposes and fun I think it is better to reuse my own code whenever possible.</p>
<p>Since this is my first question on SE, please don't hesitate to point out flaws in the question itself (too long, too broad, missing important details, inappropriate tags etc.).</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T19:28:03.173",
"Id": "244587",
"Score": "4",
"Tags": [
"c++",
"performance",
"user-interface"
],
"Title": "Small Automatic Differentiation Library"
}
|
244587
|
<p>I'm posting my code for a LeetCode problem copied here. If you have time and would like to review, please do so. Thank you!</p>
<h3>Problem</h3>
<blockquote>
<ul>
<li><p>There is a box protected by a password. The password is a sequence of n digits where each digit can be one of the first k digits 0, 1,
..., k-1.</p>
</li>
<li><p>While entering a password, the last n digits entered will automatically be matched against the correct password.</p>
</li>
<li><p>For example, assuming the correct password is "345", if you type "012345", the box will open because the correct password matches the
suffix of the entered password.</p>
</li>
<li><p>Return any password of minimum length that is guaranteed to open the box at some point of entering it.</p>
</li>
</ul>
</blockquote>
<h3>Accepted Code</h3>
<pre><code>#include <vector>
#include <string>
class Solution {
int n;
int k;
int value;
std::vector<std::vector<bool>> visited;
std::string base_sequence;
public:
std::string crackSafe(int n, int k) {
if (k == 1) {
return std::string(n, '0');
}
this->n = n;
this->k = k;
value = 1;
for (int index = 0; index < n - 1; index++) {
value *= k;
}
visited.resize(value, std::vector<bool>(k, false));
depth_first_search(0);
return base_sequence + base_sequence.substr(0, n - 1);
}
private:
// Depth first search the neighbor value
void depth_first_search(int neighbor) {
for (int index = 0; index < k; index++) {
if (!visited[neighbor][index]) {
visited[neighbor][index] = true;
depth_first_search((neighbor * k + index) % value);
base_sequence.push_back('0' + index);
}
}
}
};
</code></pre>
<h3>Reference</h3>
<p>LeetCode has a template for answering questions. There is usually a class named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename.</p>
<ul>
<li><p><a href="https://leetcode.com/problems/cracking-the-safe/" rel="nofollow noreferrer">Problem</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/cracking-the-safe/discuss/" rel="nofollow noreferrer">Discuss</a></p>
</li>
<li><p><a href="https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm" rel="nofollow noreferrer">Bellman Ford algorithm</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<h2>Constant members</h2>\n<p><code>n</code> and <code>k</code> can be constant, so long as</p>\n<ul>\n<li>you remove them from being parameters to <code>crackSafe</code></li>\n<li>you add them as parameters to a constructor</li>\n<li>the constructor uses inline initialization syntax, i.e. <code>n(n)</code></li>\n</ul>\n<p>Basically, your two member functions should - in their current form - be bare functions outside of a class, since the class member variables only really have transient meaning. For this to make sense as a class, <code>n</code> and <code>k</code> would only make sense as "permanent" attributes per instance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T20:20:02.123",
"Id": "244589",
"ParentId": "244588",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244589",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T19:47:53.177",
"Id": "244588",
"Score": "3",
"Tags": [
"c++",
"beginner",
"algorithm",
"programming-challenge",
"c++17"
],
"Title": "LeetCode 753: Cracking the Safe"
}
|
244588
|
<p>I am creating a Python 3.8 script that executes a series of tests that reads and writes information to and from a CAN bus network. I'm using the python-can and the cantools packages. I've managed to transmit and receive data with small functions individually without issue.</p>
<p>I feel I'm not creating the proper "Pythonic" script architecture that allows my script to use all functions, instances and variables between modules.</p>
<p><strong>Intended architecture goal:</strong></p>
<ul>
<li><code>main.py</code> - contains the CAN bus transmit and receive functions, performs initialization and cycles through each test case located in the <code>test_case.py</code> module.</li>
<li><code>test_case.py</code> - stores all test cases. Where each test case is a
stand alone function. Each test case must be an isolated function so that if one test needs to be removed or a new test added the script won't break. Additionally, there will likely be dozens maybe hundreds of test cases.
So I'd like to keep them isolated to one module for code cleanliness.</li>
<li><code>test_thresholds.py</code> - would keep all the pass/fail threshold variables
that each test case in <code>test_case.py</code> will refer to.</li>
</ul>
<p>Problems / Questions:</p>
<ol>
<li><p><code>main.py</code> instantiates a CAN bus object <code>bus = can.Bus(bustype='pcan', channel='PCAN_USBBUS1', bitrate=500000)</code> this object is required for the transmit and receive functions. Because the transmit and receive functions are in <code>main.py</code>, this wasn't a problem until I tried to execute a test case in the <code>test_case.py</code> module which references the transmit and receive functions in <code>main.py</code></p>
<p>Once I attempted to execute a test case an error occurred stating that the <code>receive()</code> function being called from the <code>test_case.py</code> module <code>NameError: name 'bus' is not defined</code> I understand this as <code>test_case.py</code> does not know what the <code>bus</code> instance is. This problem also occurs with my <code>can</code> instances. I have <code>from main import *</code> in my <code>test_case.py</code> I know this is bad but I am not sure how else <code>test_cases.py</code> will use the transmit and receive functions along with the <code>bus</code> and <code>can</code> instances</p>
<p><em><strong>How can I share that instances between modules? What are the best practices here?</strong></em> I have tried to go over several posts on Stack Overflow regarding passing objects (I think that's what my problem is) but none of them seem to answer what I'm looking for.</p>
</li>
<li><p><em><strong>Is my architecture design acceptable? I'm new to designing larger scripts and I want to make sure I am doing it effectively/proper so that it can scale.</strong></em></p>
</li>
</ol>
<p><strong>Note</strong>: I've cut down a lot of my code to make it more readable here. It may not run if you try it.</p>
<p><code>main.py</code></p>
<pre><code>import can
import cantools
import test_cases.test_cases # import all test cases
import time
# sending a single CAN message
def single_send(message):
try:
bus.send(message)
except can.CanError:
print("Message NOT sent")
# receive a message and decode payload
def receive(message, signal):
_counter = 0
try:
while True:
msg = bus.recv(1)
try:
if msg.arbitration_id == message.arbitration_id:
message_data = db.decode_message(msg.arbitration_id, msg.data)
signal_data = message_data.get(signal)
return signal_data
except AttributeError:
_counter += 1
if _counter == 5:
print("CAN Bus InActive")
break
finally:
if _counter == 5:
# reports false if message fails to be received
return False
def main():
for name, tests in test_cases.test_cases.__dict__.items():
if name.startswith("tc") and callable(tests):
tests()
if __name__ == "__main__":
bus = can.Bus(bustype='pcan', channel='PCAN_USBBUS1', bitrate=500000)
db = cantools.db.load_file('C:\\Users\\tw\\Desktop\\dbc_file.dbc')
verbose_log = open("verbose_log.txt", "a")
main()
bus.shutdown()
verbose_log.close()
</code></pre>
<p><code>test_case.py</code></p>
<pre><code>from test_thresholds.test_thresholds import *
from main import * # to use the single_send and receive functions in main
def tc_1():
ct = receive(0x300, 'ct_signal') # this is where the issue occurs. receive expects the bus instance
message = can.Message(arbitration_id=0x303, data=1)
if (ct > ct_min) and (ct < ct_max):
verbose_log.write("PASS")
else:
verbose_log.write("FAIL")
</code></pre>
<p><code>test_thresholds.py</code></p>
<pre><code>ct_min = 4.2
ct_max = 5.3
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T22:07:59.797",
"Id": "480180",
"Score": "2",
"body": "\"I've cut down a lot of my code to make it more readable here. It may not run if you try it.\" Please undo that, your current code is very small, and including all of your code unmodified is always best on Code Review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T11:11:23.607",
"Id": "480201",
"Score": "1",
"body": "Can you add an example where you use the `receive` function? It is not clear to me why that function needs to take a message to receive?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T15:42:45.107",
"Id": "480430",
"Score": "1",
"body": "@Graipher the `receive` function is used in `tc_1`. Its is supposed to take the message ID and the signal as args. Then return the value of the signal at that given instant"
}
] |
[
{
"body": "<p><strong>Protected Variables</strong></p>\n<p>Underscore is used to mark a variable <code>protected</code> in python classes</p>\n<pre><code>_counter = 0\n</code></pre>\n<p>should be</p>\n<pre><code>counter = 0\n</code></pre>\n<p><strong>Use of min_<foo<max_ is permitted in python</strong></p>\n<pre><code> if (ct > ct_min) and (ct < ct_max):\n</code></pre>\n<p>can be</p>\n<pre><code> if ct_min < ct < ct_max:\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T15:46:34.550",
"Id": "480329",
"Score": "0",
"body": "I read this second one in some PEP few months ago. Can someone remind me which PEP was that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T15:52:57.753",
"Id": "480331",
"Score": "0",
"body": "I don't know that it's in a PEP, but: https://docs.python.org/3/reference/expressions.html#comparisons"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T15:55:38.503",
"Id": "480332",
"Score": "0",
"body": "Thanks for the help @Reinderien ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T16:27:49.613",
"Id": "480438",
"Score": "0",
"body": "@VisheshMangla thank you. I have corrected `_counter`, I originally mistook the meaning for the `_`. I've also corrected the `if` statement condition as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T16:30:22.217",
"Id": "480441",
"Score": "0",
"body": "Nice work. See `Time for some Examples` here ->https://www.studytonight.com/python/access-modifier-python."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T15:26:36.350",
"Id": "244616",
"ParentId": "244590",
"Score": "2"
}
},
{
"body": "<h2>In-band error signalling</h2>\n<pre><code>return signal_data\n# ...\n# reports false if message fails to be received\nreturn False\n</code></pre>\n<p>is problematic. You're forcing the caller of this code to understand that the return value has at least two different types: boolean or whatever "signal data" is.</p>\n<p>The Python way to approach this is to use exceptions. Rather than (say) re-throw <code>AttributeError</code>, it would probably make more sense to throw your own exception type.</p>\n<p>Also, the logic around retry counts is a little convoluted. You should be able to assume that if the loop has ended without returning, it has failed. Also, don't increment the counter yourself. In other words,</p>\n<pre><code>for attempt in range(5):\n msg = bus.recv(1)\n try:\n if msg.arbitration_id == message.arbitration_id:\n message_data = db.decode_message(msg.arbitration_id, msg.data)\n signal_data = message_data.get(signal)\n return signal_data\n except AttributeError:\n pass\n\nraise CANBusInactiveError()\n</code></pre>\n<p>I would go a step further. My guess is that <code>msg</code> - if it fails - does not have the <code>arbitration_id</code> attribute. So - rather than attempting to catch <code>AttributeError</code> - either:</p>\n<ul>\n<li>call <code>hasattr</code>, or</li>\n<li>(preferably) call <code>isinstance</code>.</li>\n</ul>\n<h2>Context management</h2>\n<p>Put this:</p>\n<pre><code>verbose_log = open("verbose_log.txt", "a")\nverbose_log.close()\n</code></pre>\n<p>in a <code>with</code>.</p>\n<h2>Hard-coded paths</h2>\n<pre><code>'C:\\\\Users\\\\tw\\\\Desktop\\\\dbc_file.dbc'\n</code></pre>\n<p>should - at least - go into a constant variable. Better would be to get it from a command-line argument, a conf file or an env var.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T16:10:00.670",
"Id": "480334",
"Score": "0",
"body": "I have never used or seen simply try and finally(i.e., try without except). I read the docs and they said that if try gets an error the error is eventually raised after finally. Is try with finally actually useful anywhere?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T16:11:22.837",
"Id": "480335",
"Score": "0",
"body": "@VisheshMangla yes. Most commonly when you need the effect of a context manager but one is not implemented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T16:17:02.233",
"Id": "480336",
"Score": "0",
"body": "Oh, I didn't know that context managers are coded inside. I used `with` statement blindly with any function that has `.open()` and `.close()` up till this point. This was when I know `with` is nothing but try: except from the python docs. Thanks for the info @Reinderien."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T16:24:08.953",
"Id": "480435",
"Score": "0",
"body": "@Reinderien thank you for your input. I've corrected the hard-code path to a constant variable. I've never set a path based on a command line argument, conf file or env var."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T16:26:05.293",
"Id": "480437",
"Score": "0",
"body": "@Reinderien I'm not sure how to use the context manager to mange the file when I need to \"pass\" the file object to other modules in my script. Each time I perform a test_case function in my `test_case.py` they will write to the file. So that's why I established the file without the context manager"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T16:28:46.527",
"Id": "480439",
"Score": "0",
"body": "A few things. First, if you can trust that use of `verbose_log` is solely used during the execution of `main`, then a `with` is still safe, and the symbol created from the `with` will still be a global (given your current usage)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T16:30:12.927",
"Id": "480440",
"Score": "0",
"body": "However, the much saner way to do this is - don't open the file yourself; use `FileHandler` and the built-in logging system from https://docs.python.org/3.8/library/logging.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T19:20:10.587",
"Id": "480501",
"Score": "0",
"body": "@Reinderien after reading on the logging module I can see why its so much better. Thank you. Regarding my first question, do you know how I can pass the `bus` instance between `main.py` and `test_thresholds.py`? The issue is that `receive()` is called in `test_thresholds` and `receive` must refer to the `bus` instance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T19:24:37.360",
"Id": "480506",
"Score": "0",
"body": "Why would `test_thresholds.py` need a `bus` instance at all? You've only shown the initialization of two constant variables that do not need it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T19:36:19.257",
"Id": "480514",
"Score": "0",
"body": "@Reinderien `test_thresholds.py` has the function `tc_1'. That function calls on `receive()` which is located in `main.py'. `receive()` must know the `bus` instance in order for `msg = bus.recv(1)` to function. So I think I must change `revieve()` to take `bus` as an input"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T19:37:03.350",
"Id": "480516",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/110031/discussion-between-reinderien-and-tim51)."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T16:01:23.110",
"Id": "244665",
"ParentId": "244590",
"Score": "3"
}
},
{
"body": "<p>Not familiar with CAN yet so just one suggestion:</p>\n<p>Get rid of those <code>print</code> statements, use the <a href=\"https://docs.python.org/3/library/logging.html\" rel=\"nofollow noreferrer\">logging</a> module instead. See also here: <a href=\"https://docs.python.org/3/howto/logging.html#logging-basic-tutorial\" rel=\"nofollow noreferrer\">Basic Logging Tutorial</a> and here: <a href=\"https://docs.python.org/3/howto/logging-cookbook.html#logging-cookbook\" rel=\"nofollow noreferrer\">Logging Cookbook</a>\nSome benefits:</p>\n<ul>\n<li>being able to write to multiple destinations: console + text files in different formats if desired</li>\n<li>increase or reduce verbosity at will</li>\n<li>keep a permanent record of program activity (and exceptions !)</li>\n</ul>\n<p>It's easy to miss console output and not having a persistent, timestamped log makes it more difficult to track bugs or investigate incidents.</p>\n<p>If your application is mission-critical/ unattended you could send logging output to a dedicated <strong>log collector</strong>, which could generate alerts when warning/error messages are emitted, or when your application crashes for some reason.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T22:51:17.933",
"Id": "244684",
"ParentId": "244590",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244665",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T21:34:16.040",
"Id": "244590",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"unit-testing"
],
"Title": "CAN Bus testing"
}
|
244590
|
<p>For my project, I've written a naive C implementation of Direct3D convolution with periodic padding on the input. Unfortunately, since I'm new to C, the performance isn't so good.</p>
<p>By convention, all the matrices (image, kernel, result) are stored in column-major fashion. This is why I loop through them in such way so they are closer in memory. As I heard this would help.</p>
<p>I know the implementation is very naive. But since it's written in C, I was hoping the performance would be good, but instead it's a little disappointing. I tested it with image of size <span class="math-container">\$100^3\$</span> and kernel of size <span class="math-container">\$10^3\$</span> which totals ~1GFLOPS if you only count the multiplication and addition. This took ~7s which I believe is way below the capability of a typical CPU.</p>
<p>Could the performance be optimized in this routine?
I'm open to anything that could help, with just a few things if you could consider:</p>
<ol>
<li><p>The problem I'm working on can be big. Image's size can be 200 by 200 by 200 whilst the kernel's size can be 50 by 50 by 50 or even larger. I understand that one way of optimizing this is by converting this problem into a matrix multiplication problem and use the blas GEMM routine, but I'm afraid memory could not hold such a big matrix</p>
</li>
<li><p>Due to the nature of the problem I would prefer direct convolution instead of FFTConvolve, since my model is developed with direct convolution in mind. My impression of FFTconvolve is that it gives slightly different result than direct convolve, especially for rapidly changing image. A discrepancy I'm trying to avoid.
That said, I'm in no way an expert in this. so if you have a great implementation based on FFTconvolve and / or my impression on FFTconvolve is totally biased, I would really appreciate if you could help me out.</p>
</li>
<li><p>The input images are assumed to be periodic, so periodic padding is necessary</p>
</li>
<li><p>I understand that utilizing blas / SIMD or other lower level ways would definitely help a lot here. but since I'm a newbie here I don't really know where to start. I would really appreciate if you help pointing me to the right direction if you have experience in these libraries,</p>
</li>
</ol>
<pre><code>int mod(int a, int b)
{
// calculate mod to get the correct index with periodic padding
int r = a % b;
return r < 0 ? r + b : r;
}
void convolve3D(const double *image, const double *kernel, const int imageDimX, const int imageDimY, const int imageDimZ, const int kernelDimX, const int kernelDimY, const int kernelDimZ, double *result)
{
int imageSize = imageDimX * imageDimY * imageDimZ;
int kernelSize = kernelDimX * kernelDimY * kernelDimZ;
int i, j, k, l, m, n;
int kernelCenterX = (kernelDimX - 1) / 2;
int kernelCenterY = (kernelDimY - 1) / 2;
int kernelCenterZ = (kernelDimZ - 1) / 2;
int xShift,yShift,zShift;
int outIndex, outI, outJ, outK;
int imageIndex = 0, kernelIndex = 0;
// Loop through each voxel
for (k = 0; k < imageDimZ; k++){
for ( j = 0; j < imageDimY; j++) {
for ( i = 0; i < imageDimX; i++) {
kernelIndex = 0;
// for each voxel, loop through each kernel coefficient
for (n = 0; n < kernelDimZ; n++){
for ( m = 0; m < kernelDimY; m++) {
for ( l = 0; l < kernelDimX; l++) {
// find the index of the corresponding voxel in the output image
xShift = l - kernelCenterX;
yShift = m - kernelCenterY;
zShift = n - kernelCenterZ;
outI = mod ((i - xShift), imageDimX);
outJ = mod ((j - yShift), imageDimY);
outK = mod ((k - zShift), imageDimZ);
outIndex = outK * imageDimX * imageDimY + outJ * imageDimX + outI;
// calculate and add
result[outIndex] += kernel[kernelIndex]* image[imageIndex];
kernelIndex++;
}
}
}
imageIndex ++;
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T00:56:03.463",
"Id": "480276",
"Score": "0",
"body": "[as discussed](https://stackoverflow.com/questions/62603086/optimization-of-3d-direct-convolution-implementation-in-c#comment110709682_62603086) on the Stack Overflow version of this question, `%` is very slow with divisors that aren't compile-time constants. Replacing that with a conditional add (assuming it can't wrap more than once) sped up the whole thing by 20%. (Compiling with `-O3` with an unknown compiler on unknown hardware, presumably not `-march=native` or `-ffast-math`.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T01:14:37.420",
"Id": "480278",
"Score": "0",
"body": "Does this compile? `kernelIndex` is declared, and later incremented, but never used anywhere. `stencil` and `stencilIndex` is only referenced, never declared or defined. Are they supposed to be `kernel` and `kernelIndex`? Requests for reviews of [broken code](https://codereview.meta.stackexchange.com/a/3650/9683) are off-topic here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T04:07:11.227",
"Id": "480386",
"Score": "0",
"body": "@scottbb ah, yes, I changed it from stencil to kernel when copying my code, and missed some... I have corrected the typo"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T09:26:22.723",
"Id": "480407",
"Score": "0",
"body": "Some \"little\"... `for (n = 0, zShift = - kernelCenterZ; n < kernelDimZ; n++, zShift++){` and the next 2 loops also. You can remove the 3 substractions in the inner body. They were calculated too often."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T09:33:32.793",
"Id": "480408",
"Score": "0",
"body": "`outK` and `outJ` don't need to be allways recalculated in the inner loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T17:12:15.537",
"Id": "480465",
"Score": "0",
"body": "@Holger Yes! Thanks a lot for pointing those out! with those adjustment, it is now 50% faster!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T22:30:13.170",
"Id": "244591",
"Score": "4",
"Tags": [
"performance",
"c",
"memory-management",
"simd"
],
"Title": "3D Direct Convolution Implementation in C"
}
|
244591
|
<pre><code>from bs4 import BeautifulSoup
import requests
import re
import datetime
metal_translation = {"Aluminium": "Aluminio", "Copper": "Cobre", "Zinc": "Zinc", "Nickel": "Níquel", "Lead": "Plomo", "Tin": "Estaño",
"Aluminium Alloy": "Aleación de Aluminio", "Cobalt": "Cobalto", "Gold*": "Oro*", "Silver*": "Plata*",
"Steel Scrap**": "Chatarra de Acero", "NASAAC": "NASAAC", "Steel Rebar**": "Varilla de Acero"}
def get_metal_values():
names = []
prices = []
metals = requests.get('https://www.lme.com/').text
soup = BeautifulSoup(metals, 'lxml')
metal_table = soup.find("table", attrs={"class": "ring-times"})
metal_table_names, metal_table_prices = metal_table.tbody.find_all("th"), metal_table.tbody.find_all("td")
for name in metal_table_names:
names.append(name.text.replace("LME ", ""))
for price in metal_table_prices:
prices.append(price.text.strip())
return names, prices
def get_peso_conversion():
peso = requests.get('https://themoneyconverter.com/USD/MXN').text
soup1 = BeautifulSoup(peso, 'lxml')
conversion = soup1.find("div", class_="cc-result").text
rate = re.search("\d{2}\.\d{4}", conversion).group()
return rate
def get_time():
date = datetime.datetime.now()
time = (f'{date.day}/{date.month}/{date.year} | {date.hour}:{date.minute}')
return time
def convert_values():
names, prices = get_metal_values()
rate = get_peso_conversion()
metal_data = dict(zip(names, prices))
for k, v in metal_data.items():
v = (float(v.replace(",", "")) * float(rate))
v = ("%.2f" % v)
k = metal_translation[k]
print(f'{k}: {v} $')
def program_run():
print("Metal Prices by ETHAN HETRICK")
print("================================================")
print(f'{get_time()} | 1 USD = {get_peso_conversion()} MXN\n')
print("Precios de metales de London Metal Exchange: (Por tonelada métrica, *Por onza Troy)\n")
convert_values()
print("================================================")
program_run()
input("\nEscribe 'x' para terminar.\n")
EXAMPLE OUTPUT:
Metal Prices by ETHAN HETRICK
================================================
26/6/2020 | 18:28 | 1 USD = 23.0622 MXN
Precios de metales de London Metal Exchange: (Por tonelada métrica, *Por onza Troy)
Aluminio: 36484.40 $
Cobre: 138038.80 $
Zinc: 47438.95 $
Níquel: 293097.50 $
Plomo: 41004.59 $
Estaño: 391826.78 $
Aleación de Aluminio: 27997.51 $
NASAAC: 27444.02 $
Cobalto: 657272.70 $
Oro*: 40711.70 $
Plata*: 410.74 $
Chatarra de Acero: 6065.36 $
Varilla de Acero: 9720.72 $
================================================
Escribe 'x' para terminar.
</code></pre>
<p>My fiances father owns a metal recycling business in Mexico City, Mexico which requires him to do a lot of calculations when negotiating with clients. Since he was doing this by hand, I decided to automate this for him. I used London Metal Exchange, which is his preferred site to get the current prices, for the metal prices and also got the exchange rate for USD to MXN and applied that as well. I also needed to translate everything to spanish so I used a dictionary. This is my first time utilizing webscraping and the datetime module so any advice to make this program run more efficiently or make the code more concise is much appreciated!</p>
|
[] |
[
{
"body": "<h2>Check for failure</h2>\n<pre><code>metals = requests.get('https://www.lme.com/').text\n</code></pre>\n<p>should be</p>\n<pre><code>response = requests.get('https://www.lme.com/')\nresponse.raise_for_status()\nmetals = response.text\n</code></pre>\n<h2>String literals don't need parens</h2>\n<pre><code>date = datetime.datetime.now()\ntime = (f'{date.day}/{date.month}/{date.year} | {date.hour}:{date.minute}')\n</code></pre>\n<p>would only need parens if it spans multiple lines.</p>\n<p>Also, <code>date</code> shouldn't be called <code>date</code> for a couple of reasons:</p>\n<ul>\n<li>it shadows <code>datetime.date</code>, and</li>\n<li>it has a time, not just a date.</li>\n</ul>\n<p>Finally: try using <a href=\"https://docs.python.org/3/library/datetime.html#datetime.datetime.strftime\" rel=\"noreferrer\"><code>strftime</code></a> rather than extracting the time's individual components to render a string.</p>\n<h2>No intermediate dict</h2>\n<pre><code>metal_data = dict(zip(names, prices))\nfor k, v in metal_data.items():\n</code></pre>\n<p>The only reason you'd want to do this is if you're deeply concerned that there are duplicates, which this would remove. If there are no duplicates, then simply</p>\n<pre><code>for k, v in zip(names, prices):\n</code></pre>\n<h2>Combine format strings</h2>\n<pre><code> v = ("%.2f" % v)\n k = metal_translation[k]\n print(f'{k}: {v} $')\n</code></pre>\n<p>can be</p>\n<pre><code>print(f'{metal_translation[k]}: {v:.2f}')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T02:37:03.560",
"Id": "480186",
"Score": "0",
"body": "Thanks! I just updated the post ( : . @Reinderien"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T02:38:22.417",
"Id": "480187",
"Score": "0",
"body": "I have rolled this back. Rather than editing your existing post, if you are satisfied with the amount of feedback you've received, please make a new one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T02:56:31.950",
"Id": "480188",
"Score": "0",
"body": "sure thing! I'll do that right away."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T10:15:26.283",
"Id": "480198",
"Score": "2",
"body": "@Reinderien I saw this on the sidebar on another question and logged in to upvote. 3 years with Python and I had no clue you could format floats inside of formatted strings and use `zip` without `dict`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T00:09:44.443",
"Id": "244593",
"ParentId": "244592",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "244593",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T23:38:15.740",
"Id": "244592",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"beautifulsoup"
],
"Title": "Webscraping application that collects metal prices and converts them from USD to MXN real-time using BeautifulSoup"
}
|
244592
|
<p><strong>Question:</strong> was using <code>get_dummies</code> a good choice for converting categorical strings?</p>
<p>I used <code>get_dummies</code> to convert categorical variables into dummy / indicator variables for a cold start recommender system. It's only using category type information and some basic limited choices.</p>
<p>The code works and the output seems good. This is my first data science project, which is for fun. I kind of put this together from reading documentation and searching Stack Overflow. I plan on making it a hybrid recommender system soon by adding sentiment analysis and topic classification. Both of which I also recently finished.</p>
<p>To check another character just Input a different character name in <code>userInput</code>. The full notebook and Excel sheet for import are on <a href="https://github.com/taylorjohn/Simple_RecSys/blob/master/dnd-rec.ipynb" rel="nofollow noreferrer">my GitHub</a>.</p>
<p>I would be grateful if someone could comment on whether or not I was able to achieve the following goals (and of course if not, what I can improve):</p>
<ul>
<li>Code structure,</li>
<li>Style and readability: Is the code comprehensible?</li>
<li>Are there any bad practices?</li>
</ul>
<p>These are the attributes in my code:</p>
<ul>
<li><p>Character's name (must be unique)</p>
</li>
<li><p>herotype (must be one of following choices)</p>
<ul>
<li>Bard</li>
<li>Sorcerer</li>
<li>Paladin</li>
<li>Rogue</li>
<li>Druid</li>
<li>Sorcerer</li>
</ul>
</li>
<li><p>weapons (can have one or multiple of following choices)</p>
<ul>
<li>Dagger</li>
<li>sling</li>
<li>club</li>
<li>light crossbow</li>
<li>battleaxe</li>
<li>Greataxe</li>
</ul>
</li>
<li><p>spells (can have one or multiple of following choices)</p>
<ul>
<li>Transmutation</li>
<li>Enchantment</li>
<li>Necromancy</li>
<li>Abjuration</li>
<li>Conjuration</li>
<li>Evocation</li>
</ul>
</li>
</ul>
<h1>Input and Output</h1>
<p><strong>Get Another Recommendation</strong><br />
You just input the username 'Irv' to another one like 'Zed Ryley' etc</p>
<pre><code>userInput = [
{'name':'Irv', 'rating':1}
</code></pre>
<p><strong>The results</strong><br />
come back formatted like this</p>
<pre><code> name herotype weapons spells
28 Irv Sorcerer light crossbow Conjuration
9 yac Sorcerer Greataxe Conjuration, Evocation, Transmutation
18 Traubon Durthane Sorcerer light crossbow Evocation, Transmutation, Necromancy
8 wuc Sorcerer light crossbow, battleaxe Necromancy
1 niem Sorcerer light crossbow, battleaxe Necromancy
23 Zed Ryley Sorcerer sling Evocation
</code></pre>
<p><strong>For comparison</strong></p>
<p>Here are the scores which show how it ranks the results.</p>
<pre><code>
In [5]:
recommendationTable_df.head(6)
Out[5]:
28 1.000000
9 0.666667
18 0.666667
8 0.666667
1 0.666667
23 0.333333
dtype: float64
</code></pre>
<h1>Code</h1>
<pre><code>#imports
import pandas as pd
import numpy as np
df = pd.read_excel('dnd-dataframe.xlsx', sheet_name=0, usecols=['name', 'weapons','herotype','spells'])
df.head(30)
</code></pre>
<pre><code>
dummies1 = df['weapons'].str.get_dummies(sep=',')
dummies2 = df['spells'].str.get_dummies(sep=',')
dummies3 = df['herotype'].str.get_dummies(sep=',')
genre_data = pd.concat([df, dummies1,dummies2, dummies3], axis=1)
userInput = [
{'name':'Irv', 'rating':1} #Their is no rating system being used so by default rating is set to 1
]
inputname = pd.DataFrame(userInput)
inputId = df[df['name'].isin(inputname['name'].tolist())]
#Then merging it so we can get the name. It's implicitly merging spells it by name.
inputname = pd.merge(inputId, inputname)
#Dropping information we won't use from the input dataframe
inputname = inputname.drop('weapons',1).drop('spells',1).drop('herotype',1)
#Filtering out the names from the input
username = genre_data[genre_data['name'].isin(inputname['name'].tolist())]
#Resetting the index to avoid future issues
username = username.reset_index(drop=True)
#Dropping unnecessary issues due to save memory and to avoid issues
userGenreTable = username.drop('name',1).drop('weapons',1).drop('spells',1).drop('herotype',1)
#Dot product to get weights
userProfile = userGenreTable.transpose().dot(inputname['rating'])
genreTable = genre_data.copy()
genreTable = genreTable.drop('name',1).drop('weapons',1).drop('spells',1).drop('herotype',1)
</code></pre>
<pre><code>#Multiply the genres by the weights and then take the weighted average
recommendationTable_df = ((genreTable*userProfile).sum(axis=1))/(userProfile.sum())
#Sort our recommendations in descending order
recommendationTable_df = recommendationTable_df.sort_values(ascending=False)
#df.loc[df.index.isin(recommendationTable_df.head(3).keys())] #adjust the value of 3 here
df.loc[recommendationTable_df.head(6).index, :]
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T02:41:36.637",
"Id": "244595",
"Score": "7",
"Tags": [
"python",
"beginner",
"numpy",
"pandas"
],
"Title": "Using get_dummies to create a Simple Recommender System - Cold Start"
}
|
244595
|
<pre><code>from bs4 import BeautifulSoup
import requests
import re
import datetime
metal_translation = {"Aluminium": "Aluminio", "Copper": "Cobre", "Zinc": "Zinc", "Nickel": "Níquel", "Lead": "Plomo", "Tin": "Estaño",
"Aluminium Alloy": "Aleación de Aluminio", "Cobalt": "Cobalto", "Gold*": "Oro*", "Silver*": "Plata*",
"Steel Scrap**": "Chatarra de Acero", "NASAAC": "NASAAC", "Steel Rebar**": "Varilla de Acero"}
def get_metal_values():
names = []
prices = []
response = requests.get('https://www.lme.com/')
response.raise_for_status()
metals = response.text
soup = BeautifulSoup(metals, 'lxml')
metal_table = soup.find("table", attrs={"class": "ring-times"})
metal_table_names, metal_table_prices = metal_table.tbody.find_all("th"), metal_table.tbody.find_all("td")
for name in metal_table_names:
names.append(name.text.replace("LME ", ""))
for price in metal_table_prices:
prices.append(price.text.strip())
return names, prices
def get_peso_conversion():
response = requests.get('https://themoneyconverter.com/USD/MXN')
response.raise_for_status()
peso = response.text
soup1 = BeautifulSoup(peso, 'lxml')
conversion = soup1.find("div", class_="cc-result").text
rate = re.search("\d{2}\.\d{4}", conversion).group()
return rate
def get_time():
d = datetime.datetime.now()
date_time = d.strftime("%d/%m/%Y | %H:%M:%S")
return date_time
def convert_values():
names, prices = get_metal_values()
rate = get_peso_conversion()
for k, v in zip(names, prices):
v = (float(v.replace(",", "")) * float(rate))
print(f'{metal_translation[k]}: {v:.2f} $')
def program_run():
print("Metal Prices by ETHAN HETRICK")
print("================================================")
print(f'{get_time()} | 1 USD = {get_peso_conversion()} MXN\n')
print("Precios de metales de London Metal Exchange: (Por tonelada métrica, *Por onza Troy)\n")
convert_values()
print("================================================")
program_run()
</code></pre>
<p>Example Output:</p>
<pre><code>input("\nEscribe 'x' para terminar.\n")
Metal Prices by ETHAN HETRICK
================================================
26/06/2020 | 21:59:00 | 1 USD = 23.0622 MXN
Precios de metales de London Metal Exchange: (Por tonelada métrica, *Por onza Troy)
Aluminio: 36484.40 $
Cobre: 138038.80 $
Zinc: 47438.95 $
Níquel: 293097.50 $
Plomo: 41004.59 $
Estaño: 391826.78 $
Aleación de Aluminio: 27997.51 $
NASAAC: 27444.02 $
Cobalto: 657272.70 $
Oro*: 40711.70 $
Plata*: 410.74 $
Chatarra de Acero: 6065.36 $
Varilla de Acero: 9720.72 $
================================================
Escribe 'x' para terminar.
</code></pre>
<p><strong>This is an updated version of my code from a previous post of mine thanks to @Reinderien</strong></p>
<p>My fiances father owns a metal recycling business in Mexico City, Mexico which requires him to do a lot of calculations when negotiating with clients. Since he was doing this by hand, I decided to automate this for him. I used London Metal Exchange, which is his preferred site to get the current prices, for the metal prices and also got the exchange rate for USD to MXN and applied that as well. I also needed to translate everything to spanish so I used a dictionary. This is my first time utilizing webscraping and the datetime module so any advice to make this program run more efficiently or make the code more concise is much appreciated!</p>
|
[] |
[
{
"body": "<p>You can tidy up the code a bit by directly returning results from functions and not using temporary variables you use only once.</p>\n<p>I would also do the conversion to floats directly in the functions.</p>\n<p><code>BeautifulSoup</code> can directly work on the binary <code>response.content</code>, no need to decode it into a string yourself by using <code>response.text</code>.</p>\n<pre><code>def get_metal_values():\n response = requests.get('https://www.lme.com/')\n response.raise_for_status()\n soup = BeautifulSoup(response.content, 'lxml')\n metal_table = soup.find("table", attrs={"class": "ring-times"})\n names = [name.text.replace("LME ", "").rstrip("*")\n for name in metal_table.tbody.find_all("th")]\n prices = [float(price.text.strip().replace(",", ""))\n for price in metal_table.tbody.find_all("td")]\n return zip(names, prices)\n\ndef get_peso_conversion():\n response = requests.get('https://themoneyconverter.com/USD/MXN')\n response.raise_for_status()\n soup = BeautifulSoup(response.content, 'lxml')\n conversion = soup.find("div", class_="cc-result").text\n return float(re.search("\\d{2}\\.\\d{4}", conversion).group())\n\ndef get_time():\n return datetime.datetime.now().strftime("%d/%m/%Y | %H:%M:%S")\n\ndef convert_values():\n exchange_rate = get_peso_conversion()\n for name, price in get_metal_values():\n print(f'{metal_translation[name]}: {price*exchange_rate:.2f} $')\n</code></pre>\n<p>Note that I also stripped the trailing <code>"*"</code> in the names as I didn't see a reason to keep them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T16:49:50.127",
"Id": "480235",
"Score": "0",
"body": "I actually used the * to signify a change in units in the end result so I kept that. I like how you got rid of a lot of unnecessary variables I was storing! I usually don't put a function in return but I will start doing that thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T16:52:38.200",
"Id": "480236",
"Score": "1",
"body": "@EthanHetrick Yeah, I also like function calls in return. But it is always a balancing act, you don't want too many unnecessary temporary variables around, but also not make it one unreadable line. I think here it works fine like this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T17:05:03.763",
"Id": "480240",
"Score": "0",
"body": "would you know how to get the numbers to show in a more readable format? For example, something that costs 60 thousand dollars and 99 cents in the Spanish-speaking world might be written $60.000,99. Is there a way I can accomplish this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T17:09:14.127",
"Id": "480241",
"Score": "0",
"body": "@EthanHetrick `\"$ {:,.2f}\"` should do the trick. Note the `,` before the `.`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T17:13:56.567",
"Id": "480244",
"Score": "0",
"body": "Just realized that my suggestion doesn't work, as comma and dot are reversed with regards to how they are used in English."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T17:15:38.057",
"Id": "480245",
"Score": "0",
"body": "https://stackoverflow.com/questions/320929/currency-formatting-in-python This might be useful"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T17:27:37.733",
"Id": "480246",
"Score": "0",
"body": "@Graipher . Are list comprehensions that you have used really good to use for such big lines? Wouldn't declaring an empty list like already done and the for loop would be better to use in this particular case? I 'm new here too and would like to learn good practices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T08:47:56.947",
"Id": "480298",
"Score": "1",
"body": "@VisheshMangla Whilst I'm not a fan of 'aligned with opening delimiter' style the style of the comprehensions are fine. The comprehension fits nicely on the two lines and is really easy to read. (Even for someone that despises the indent style). Your suggested edit however made the code longer, harder to read and generally goes completely against the the founding idea of comprehensions because of these things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T08:49:14.707",
"Id": "480299",
"Score": "0",
"body": "Thanks for the answer."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T08:45:23.067",
"Id": "244602",
"ParentId": "244596",
"Score": "2"
}
},
{
"body": "<p>I think it would be better to handle the API stuff to convert prices using a Python package like <a href=\"https://pypi.org/project/CurrencyConverter/\" rel=\"nofollow noreferrer\">CurrencyConverter</a>.</p>\n<p>The site that you are using currently might be down some day or may blacklist your IP because of the many requests that your code is making to convert the prices.</p>\n<p>Also, your code seems to be better converted to a Scrapy project if you are interested in web scraping. <a href=\"https://www.scrapinghub.com/learn-scrapy\" rel=\"nofollow noreferrer\">Scrapy Tutorial by ScrappingHub</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T09:44:49.833",
"Id": "244606",
"ParentId": "244596",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244602",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T03:01:57.140",
"Id": "244596",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"beautifulsoup"
],
"Title": "Real time metal prices and conversion fro USD to MXN using BeautifulSoup updated version"
}
|
244596
|
<p>I am solving the "Sort" problem on <a href="https://open.kattis.com/problems/sort" rel="nofollow noreferrer">Kattis</a>.</p>
<blockquote>
<p>Mirko is a great code breaker. He knows any cipher in the world can be broken by frequency analysis. He has completely the wrong idea what frequency analysis is, however.<br />
He intercepted an enemy message. The message consists of N
numbers, smaller than or equal to C.<br />
Mirko belives freqency analysis consists of sorting this sequence so that more frequent numbers appear before less frequent ones.<br />
Formally, the sequence must be sorted so that given any two numbers X
and Y, X appears before Y if the number of times X appears in the original sequence is larger than the number of time Y does. If the number of appearances is equal, the number whose value appears sooner in the input should appear sooner in the sorted sequence.<br />
Help Mirko by creating a “frequency sorter”.<br />
<em>Input</em><br />
First line of input contains two integers, N (1≤N≤1000), the length of the message, and C (1≤C≤1000000000), the number from the task description above.<br />
The next line contains N positive integers smaller than or equal to C, the message itself.</p>
</blockquote>
<p>Basically, the problem is as follows. Let <code>xs</code> be a nonempty vector of positive integers. There are only few integers in this vector, but they have a big range. (The maximum value <code>c</code> is given in the problem, but my code does not use the information.) Sort the integers according to the following criteria.</p>
<ol>
<li>For any two elements <code>x</code> and <code>y</code> of <code>xs</code>, if <code>x</code> occurs more often than <code>y</code>, then <code>x</code> appears first; if <code>y</code> appears more often, <code>y</code> appears first.</li>
<li>If <code>x</code> and <code>y</code> appear equally often, then <code>x</code> occurs first if the very first occurrence of <code>x</code> is earlier than that of <code>y</code>.</li>
</ol>
<p>I use a comparison sort (provided by the C++ runtime) with a smart comparator. This comparator knows the frequency and the index of the first appearance of every element. This information is not inherent to the integers. Rather, it depends entirely on their location within the vector. This contextual information is generated when a comparator is created for a given vector. Upon application on elements <code>x</code> and <code>y</code>, it returns <code>true</code> if <code>x</code> must appear before <code>y</code>.</p>
<p>I have used custom comparators before, but never have I used anything that contains state. In <a href="https://godbolt.org/z/NHsHSn" rel="nofollow noreferrer">the disassembly with -Os</a> I see many copy and move constructors called under <code>sort(vector<unsigned> &)</code>. The code passes all tests, and it's not slow.</p>
<p><em>But I wonder why the disassembly reveals so many copy and move calls, and whether this pattern of using heavy comparators is discouraged in C++.</em> If this looks like a known pattern, I want to know its name. I appreciate general comments and insights.</p>
<pre><code>#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <iostream>
typedef std::vector<unsigned> vector;
/// Comparison based on knowledge of the entire vector
struct compare {
std::multiset<unsigned> bag;
std::map<unsigned, size_t> indices;
/// Extract frequency and initial index of every element.
explicit compare(vector const &xs) {
for (size_t i = 0u; i < xs.size(); ++i) {
unsigned const x = xs[i];
bag.insert(x);
if (!indices.count(x)) {
indices[x] = i;
}
}
}
/// True if `x` must go before `y`.
[[nodiscard]] bool operator()(unsigned x, unsigned y) const {
return bag.count(x) > bag.count(y)
|| (bag.count(x) == bag.count(y) && indices.at(x) < indices.at(y));
}
};
static void sort(vector &v) {
compare c(v);
std::sort(v.begin(), v.end(), c);
}
int main() {
vector v;
{
// Get `n` unsigned integers from console.
// Unused: `c` (upper bound for integers)
unsigned n, c;
std::cin >> n >> c;
v.reserve(n);
while (n--) {
unsigned x;
std::cin >> x;
v.push_back(x);
}
}
// Sort according to the problem description
sort(v);
// Print all
for (unsigned const x : v) {
std::cout << x << ' ';
}
return 0;
}
</code></pre>
<h1>Update</h1>
<p><em>Summary: Used shared pointers to enforce shared ownership w/o overhead</em></p>
<p>According to G. Sliepen, the internal implementation of <code>std::sort</code> by g++ makes many copy of the Compare object. So, I decided to keep a smart pointer inside the object that takes care of simultaneous uses by different instances of the internal function calls.</p>
<pre><code>#include <memory>
===
struct compare {
private:
struct vector_context {
std::multiset<unsigned> bag;
std::map<unsigned, size_t> indices;
};
std::shared_ptr<vector_context> context;
public:
explicit compare(vector const &xs) : context(new vector_context) {
for (size_t i = 0u; i < xs.size(); ++i) {
unsigned const x = xs[i];
context->bag.insert(x);
if (!context->indices.count(x)) {
context->indices[x] = i;
}
}
}
[[nodiscard]] bool operator()(unsigned x, unsigned y) const {
return context->bag.count(x) > context->bag.count(y)
|| (context->bag.count(x) == context->bag.count(y)
&& context->indices.at(x) < context->indices.at(y));
}
};
</code></pre>
<p>The code change is minimal, and the runtime has improved four-fold.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T11:42:04.273",
"Id": "480203",
"Score": "3",
"body": "Welcome to code review. The rules of the site are that questions that answer programming challenges include the text of the programming challenge and possibly link to it, include the text because links can get broken. In this case I have done it for you, but in the future please include the text in the question."
}
] |
[
{
"body": "<p>The main issue is that the comparator object is passed by value. Not only from your application to <code>std::sort()</code>, but it's also passed by value internally in the <a href=\"https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L1950\" rel=\"noreferrer\">implementation of <code>std::sort()</code></a>. This means that <code>bag</code> and <code>indices</code> get copied by value a lot. So you ideally want to generate those only once, and then have <code>class compare</code> store a pointer or reference to those. I think there are several possible approaches; you could keep the constructor mainly as it is, but instead of storing those vectors directly, use a <code>std::shared_ptr</code> to manage their storage. The default copy constructor will then just take care of updating the refcounts for you:</p>\n<pre><code>struct compare {\n std::shared_ptr<std::multiset<unsigned>> bag;\n std::shared_ptr<std::map<unsigned, size_t>> indices;\n\n /// Extract frequency and initial index of every element.\n explicit compare(vector const &xs):\n bag{new std::multiset<unsigned>},\n indices{new std::map<unsigned, size_t>},\n {\n for (size_t i = 0u; i < xs.size(); ++i) {\n unsigned const x = xs[i];\n bag->insert(x);\n if (!indices->count(x)) {\n (*indices)[x] = i;\n }\n }\n }\n\n /// True if `x` must go before `y`.\n [[nodiscard]] bool operator()(unsigned x, unsigned y) const {\n return bag->count(x) > bag_>count(y)\n || (bag->count(x) == bag->count(y) && indices->at(x) < indices->at(y));\n }\n};\n</code></pre>\n<p>You can improve this further by combining <code>bag</code> and <code>indices</code> into on struct, so you only need one <code>std::shared_ptr</code> to hold them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T21:47:34.547",
"Id": "480265",
"Score": "0",
"body": "Thank you. I appreciate this answer because I had no idea where smart pointers (in this case `shared_ptr` representing shared ownership) could be used. I had heard about the concept of ownership, but this answer pushed me to dig deeper. Thank you for introducing me to this concept."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T10:22:04.177",
"Id": "244608",
"ParentId": "244597",
"Score": "5"
}
},
{
"body": "<p>As explained in another answer, the implementation of the standard library that you use internally passes the comparator by value. It would not have to do that, but you still would have passed it by value to <code>sort</code>, and it is best to avoid that copying altogether. Now, you do not need to change the structure of your program to avoid this.</p>\n<p>First, now that you are aware of the problem, I would advise you to make the comparator non-copyable just to ensure that you do not accidentally copy it.</p>\n<pre><code>struct compare {\n // There is no need to copy this.\n compare(const compare &) = delete;\n\n...\n</code></pre>\n<p>With that change, your original program will not compile any more. Now next, we do not pass your heavy-weight comparator itself any more, but a light-weight wrapper that only holds a reference to it.</p>\n<pre><code>static void sort(vector &v) {\n const compare c(v);\n std::sort(v.begin(), v.end(),\n [&c](unsigned x, unsigned y) { return c(x, y); });\n}\n</code></pre>\n<p>Now this does exactly what you intended in the first place. If you are worried that you might later change the type of the numbers from unsigned to something else and forget to also change it in the lambda, you can use <code>const auto &</code> there instead of unsigned.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T21:50:27.000",
"Id": "480267",
"Score": "0",
"body": "Thank you. I learned that `std::copy(RandomIt, RandomIt, Compare)` is allowed to internally pass around the Compare function by value."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T16:21:31.910",
"Id": "244619",
"ParentId": "244597",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "244608",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T03:03:39.117",
"Id": "244597",
"Score": "10",
"Tags": [
"c++",
"programming-challenge",
"design-patterns",
"c++17"
],
"Title": "C++, sort integers using knowledge of entire vector"
}
|
244597
|
<p>Continuing with algorithms I've implemented a binary search tree validator. I don't like the two boolean variables within <code>NodeFollowsBSTContract</code> as it feels too complicated. I feel like it should be cleaned up but don't see how, yet.</p>
<p>Also, before each recursive step down, to check child nodes, a new list is created. Is there's a better way to implement this check that doesn't repeatedly create new lists?</p>
<pre><code>public class BinaryTreeNode
{
public BinaryTreeNode Left { get; set; }
public BinaryTreeNode Right { get; set; }
public int? Value { get; }
public BinaryTreeNode(int value)
{
Value = value;
}
}
public class ValidateBST
{
BinaryTreeNode _root;
public ValidateBST(BinaryTreeNode root)
{
_root = root;
}
public bool IsBinarySearchTree()
{
if ((_root.Left?.Value ?? 0) <= (_root.Value)
|| (_root.Right?.Value ?? 0) > (_root.Value))
{
var listIncludingRootValue = new List<int>()
{
_root.Value.Value
};
var leftLegValid = NodeFollowsBSTContract(_root.Left, new List<int>(), new List<int>(listIncludingRootValue));
var rightLegvalid = NodeFollowsBSTContract(_root.Right, new List<int>(listIncludingRootValue), new List<int>());
return leftLegValid && rightLegvalid;
}
else
{
return false;
}
}
private bool NodeFollowsBSTContract(BinaryTreeNode node, List<int> parentSmallerValues, List<int> parentLargerValues)
{
if (node == null)
{
return true;
}
bool isLessThanAllParentLargerValues = !parentLargerValues.Any()
|| parentLargerValues.Where(value => node.Value.Value <= value).Count() == parentLargerValues.Count;
bool isGreaterThanAllParentSmallerValues = !parentSmallerValues.Any()
|| parentSmallerValues.Where(value => node.Value.Value > value).Count() == parentSmallerValues.Count;
if (!isLessThanAllParentLargerValues || !isGreaterThanAllParentSmallerValues)
{
return false;
}
if (node.Left != null)
{
var updatedLargerValues = GenerateUpdatedLists(node.Value.Value, parentLargerValues);
var updatedSmallervalues = new List<int>(parentSmallerValues);
if (!NodeFollowsBSTContract(node.Left, updatedSmallervalues, updatedLargerValues))
{
return false;
}
}
if (node.Right != null)
{
var updatedvalues = GenerateUpdatedLists(node.Value.Value, parentSmallerValues);
if (!NodeFollowsBSTContract(node.Right, updatedvalues, parentLargerValues))
{
return false;
}
}
return true;
}
private List<int> GenerateUpdatedLists(int addValue, List<int> values)
{
var updatedValues = new List<int>(values)
{
addValue
};
return updatedValues;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You can tremendously reduce the memory requirements of this code by acknowledging that you can replace the lists you use by single values:</p>\n<pre><code>private static bool IsBinarySearchTree(Node root, int max, int min)\n</code></pre>\n<p>this allows you to successively tighten the bounds on subtrees without storing the values you traversed in a list:</p>\n<pre><code>public static bool IsBinarySearchTree() \n{\n var valid = true;\n // could be simplified to a single expression, but this is easier to understand\n valid &= IsBinarySearchTree(_root.Left, _root.Value, Int.MIN_VALUE);\n valid &= IsBinarySearchTree(_root.Right, Int.MAX_VALUE, _root.Value);\n return valid;\n\n}\n</code></pre>\n<p>This should already be enough to write the recursive method and I think you'll learn more if I don't spoil this for you :)</p>\n<p>But if you want a spoiler...</p>\n<blockquote class=\"spoiler\">\n<p> <pre><code>private static bool IsBinarySearchTree(Node root, int max, int min)\n {\n // if there's no node\n if (root == null) return true;\n if (root.Value <= min || root.Value >= max)\n {\n return false;\n }\n return IsBinarySearchTree(root.Left, root.Value, min)\n && IsBinarySearchTree(root.Right, max, root.Value);\n }</code></pre></p>\n</blockquote>\n<p>This simplification is possible because you only need store the smallest larger element and the largest smaller element to be able to guarantee that relation holds for the node you're currently examining.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T09:41:46.857",
"Id": "244605",
"ParentId": "244598",
"Score": "4"
}
},
{
"body": "<blockquote>\n<pre><code>public int? Value { get; }\n</code></pre>\n</blockquote>\n<p>I really can't think of any situation where I would vant to store a <code>null</code> value in a search tree. But maybe I'm too narrow minded? What should the point be?</p>\n<p>It is by the way impossible to set the value to <code>null</code>, because it is <code>readonly</code> and the only constructor takes not an <code>int?</code> but an <code>int</code>. So how would one could set a <code>null</code> value? And because you don't have a default constructor, you can't make a node without a value either.</p>\n<p>In other words: you've made life a little more cumbersome by having a nullable value member on the node. Make it a normal <code>int</code> value.</p>\n<hr />\n<p>In general validation is good and in a lot of situation it's necessary, but it's even better to not allow an invalid data structure in the first place. You can do that by making the constructor of <code>BinaryTreeNode</code> private and the <code>Left</code> and <code>Right</code> members private settable:</p>\n<pre><code> public class BinaryTreeNode\n {\n public BinaryTreeNode Left { get; private set; }\n public BinaryTreeNode Right { get; private set; }\n\n public int? Value { get; }\n\n private BinaryTreeNode(int value)\n {\n Value = value;\n }\n....\n</code></pre>\n<p>Then you just need a static method to create the root node:</p>\n<pre><code> public static BinaryTreeNode Create(int value) => new BinaryTreeNode(value);\n</code></pre>\n<p>and a member method that inserts a new value:</p>\n<pre><code>public void Insert(int value)\n{\n if (value <= Value)\n {\n if (Left == null)\n Left = new BinaryTreeNode(value);\n else\n Left.Insert(value);\n }\n else\n {\n if (Right == null)\n Right = new BinaryTreeNode(value);\n else\n Right.Insert(value);\n }\n}\n</code></pre>\n<p>In this way, you're in full control of the data structure, and you never need to check is validity.</p>\n<hr />\n<p>But if you insists on your approach, you can do it in the following way:</p>\n<pre><code>public bool IsValid()\n{\n return (Left == null || this.Value >= Left.Value && Left.IsValid())\n && (Right == null || this.Value < Right.Value && Right.IsValid());\n}\n</code></pre>\n<p>You don't need to collect any values, but only check if the value of the current node is greater than og equal to value of the left node and smaller than the value of right node.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T18:10:45.913",
"Id": "480249",
"Score": "0",
"body": "I tunnel visioned on the possibility that a leg of a node could be null and erroneously extended that to the value as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T17:11:51.247",
"Id": "244624",
"ParentId": "244598",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244605",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T05:03:12.997",
"Id": "244598",
"Score": "4",
"Tags": [
"c#",
"algorithm"
],
"Title": "Algorithm to determine if binary tree is a Binary Search Tree (BST)"
}
|
244598
|
<h1>Goal</h1>
<ul>
<li>Return a deep copy of a double LinkedList.</li>
<li>Each node also contains an additional random pointer, potentially to any node or null.</li>
</ul>
<h1>Code to start</h1>
<pre class="lang-kotlin prettyprint-override"><code>data class Node<T>(
var data: T?,
var previous: Node<T>? = null,
var next: Node<T>? = null,
var random: Node<T>? = null
class LinkedList {
// TODO: Implement deep copy here.
}
</code></pre>
<h1>Implement</h1>
<pre class="lang-kotlin prettyprint-override"><code>fun main() {
// Setup
val node1 = Node(1)
val node2 = Node(2)
val node3 = Node(3)
node1.next = node2
node1.random = node3
node2.previous = node1
node2.next = node3
node3.previous = node2
node3.random = node1
val linkedList = LinkedList()
val deepCopy = linkedList.nextDeepCopy(node1)
// LinkedList data changed.
node1.data = 101
node2.data = 202
node3.data = 303
val shallowCopy = linkedList.shallowCopy(node1)
println("Deep copy made")
linkedList.print(deepCopy)
println()
println("Shallow copy made")
linkedList.print(shallowCopy)
}
data class Node<T>(
var data: T?,
var previous: Node<T>? = null,
var next: Node<T>? = null,
var random: Node<T>? = null
)
class LinkedList {
fun <T> nextDeepCopy(node: Node<T>?): Node<T>? {
if (node != null) {
return Node(
data = node.data,
previous = newDeepCopy(node.previous),
next = nextDeepCopy(node.next),
random = newDeepCopy(node.random)
)
} else return null
}
fun <T> newDeepCopy(node: Node<T>?): Node<T>? {
if (node != null) {
return Node(
data = node.data,
previous = node.previous,
next = node.next,
random = node.random
)
} else return null
}
fun <T> shallowCopy(node: Node<T>?) = node!!.copy()
fun <T> print(node: Node<T>?){
if (node != null){
println("Node data:${node.data} previous:${node.previous?.data} next:${node.next?.data} random:${node.random?.data}")
print(node.next)
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T18:07:17.050",
"Id": "480247",
"Score": "2",
"body": "Your latest edit has made this question off-topic as the code does not work as intended. Please can you remove your 'answer' that was previously in the question and add it back into the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T18:11:39.327",
"Id": "480250",
"Score": "0",
"body": "I've made the suggested recommendation above re-adding the code. The question seems to be on-topic without the sample code as the question is asking the optimal implementation of a Double LinkedList deep copy in Kotlin. Therefore, it seems appropriate to include the code as an answer vs. in the question."
}
] |
[
{
"body": "<h1>Misplaced Responsibility: <code>print()</code></h1>\n<p>The <code>class LinkedList</code> (or <code>data class Node</code>, see below) should not <code>print()</code> functions.\nCalling <code>print()</code> functions is a separate responsibility and should be done elsewhere in the code:\nWhat if you want your program to support different output formats like JSON or XML and they shall be sent over the network?\nOf course, we don't prepare software for all what-ifs.\nBut we do make the obvious "cuts" between responsibilities.\nTo get a printable representation, extract the text used by the <code>print()</code> calls into a <code>toString()</code> method.\nThen call <code>print(node)</code> from <code>main()</code>.</p>\n<h1>Avoid Feature Envy (from <code>LinkedList</code> on <code>Node</code>)</h1>\n<p><em>Feature Envy</em> is a special type of Misplaced Responsibility.\nThe <code>class LinkedList</code> doesn't have any features of its own, and no state.\nInstead, it only operates on everything in the <code>data class Node</code>.\nThis is a design smell that we call <em>Feature Envy</em>.\nMove all the methods from the <code>class LinkedList</code> to the <code>data class Node</code>.\nThen remove the <code>class LinkedList</code>.</p>\n<p>You will notice that when you fix <em>Feature Envy</em> problems, the lines become shorter: References that have to wander around because of the Feature Envy become the omittable <code>this</code>.</p>\n<p>There are situations where this type of Feature Envy is justified:\nIn cases of specific design patterns like Proxy, Delegate, Facade.</p>\n<p>The <code>class LinkedList</code> does not qualify as a <em>Facade</em> because it exposes the type <code>Node<T></code>.\nIt would only qualify if its type <code>Node<T></code> would be hidden from the user, and the only other type the user sees were <code><T></code>.</p>\n<p>The sitaution would, of course, change once you give <code>class LinkedList</code> fields <code>head</code> and <code>tail</code>.</p>\n<h1>Avoid error-prone interfaces</h1>\n<p>The current interface is error-prone.\nIt allows for broken linked lists.\nThe fields <code>next</code> and <code>previous</code> should be read-only for the user of <code>Node</code>.\nInstead, the user of <code>Node</code> should have to go through a method like <code>insertAfter()</code>, <code>insertBefore()</code>, <code>delete()</code>.\nAfter all, insertion and deletion are not atomic operations but should be transactions.\nAs a next step, you could ponder about the thread-safety of these operations.</p>\n<h1>Avoid exposing implementation detail</h1>\n<p>That a LinkedList is implemented with Nodes is an implementation detail that the user doesn't need to know.\nThe user should be able to focus on the primary purposes of LinkedLists:</p>\n<ul>\n<li>Payload (data)</li>\n<li>Iteration/Traversal</li>\n<li>Insertion and Removal\nYour interface is too low-level.</li>\n</ul>\n<p>The perfect <code>LinkedList</code> interface is (almost?) indistiguishable from an <code>ArrayList</code> interface. It should be possible to swap one implementation, like <code>LinkedList</code>, for another, like <code>ArrayList</code>, due to performance considerations (<em>O(1)</em> random access for <code>ArrayList</code>, <em>O(n/2)</em> random access for <code>LinkedList</code> vs <em>O(1)</em> insert/delete for <code>LinkedList</code>, <em>O(n/2)</em> insert/delete for <code>ArrayList</code>) without having to change all the code that uses the list.</p>\n<h1>Null-Checking</h1>\n<p>Only use <code>Type?</code> if you really need to support nullability.\nI recommend to use <code>Type</code> instead of <code>Type?</code> whereever you can.\nThat the Kotlin compiler can enforce NonNull is one of the many strengths that it has over Java.\nDon't squander it by making everything nullable with <code>?</code>.</p>\n<h1>BUG: <code>fun nextDeepCopy()</code> doesn't create a deep copy</h1>\n<p>It doesn't, because it doesn't recurse to itself but calls <code>newDeepCopy()</code>, and that is not recursive.</p>\n<p>The correct way to create a deep copy of a LinkedList with additional random pointers would be to</p>\n<ol>\n<li>Create a map with the old nodes as key and the new node as value.</li>\n<li>Loop over the map, setting the pointers of the new nodes by a lookup in the map.\nTraditional ways of copying a LinkedList won't work because of the random pointer.</li>\n</ol>\n<p>Also, <code>fun newDeepCopy()</code> does exactly the same thing as the built-in <code>fun copy()</code>, it creates a shallow copy of the current object.</p>\n<h1>Unit Tests?</h1>\n<p>There are ways how to prevent bugs like the one above.\nI recommend writing unit tests.\nEven better, use Test-Driven Development.</p>\n<h1>Use <code>if</code>-expressions</h1>\n<p>In Kotlin, <code>if</code> is an expression.\nYou can make use of it.</p>\n<p>The code:</p>\n<pre><code>if (condition) return a else return b\n</code></pre>\n<p>can also be written as, more idiomatic:</p>\n<pre><code>return if (condition) a else b\n</code></pre>\n<p>This would allow for all of your functions to become expression functions.</p>\n<h1>Piece of Sample Code</h1>\n<p>Here's a code snippet to show how your code could look like:</p>\n<pre><code>data class Node<T>(\n var data: T?,\n var previous: Node<T>? = null,\n var next: Node<T>? = null,\n var random: Node<T>? = null\n) {\n fun shallowCopy() = copy() // You could even omit this\n fun deepCopy(): Node<T> = TODO("Implement this")\n fun toString() = "Node data:${data} previous:${previous?.data} next:${next?.data} random:${random?.data}"\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T14:11:01.027",
"Id": "480424",
"Score": "0",
"body": "Very small remark: instead of the if-expression, `let` or `run` offers an even more compact solution, `node?.run { Node(data, previous, next, random) }` given that you don't go for the even simpler option: `node?.copy()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T20:29:39.207",
"Id": "480530",
"Score": "0",
"body": "Thank you for the thorough code review @Christian Hujer! I will post a new answer with the `nextDeepCopy()` bug fix, and then I will continue to refactor based on the additional notes above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T20:15:49.283",
"Id": "480628",
"Score": "1",
"body": "@tieskedh, Good point. I've found for myself it can be easy to get carried away with too much nesting using the accessor extension functions so I try to be cognizant based on the use case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T12:03:09.987",
"Id": "480661",
"Score": "1",
"body": "you're right. I'm less restricted in frequency, but more on the nesting-level: almost never more than one extension-scope function and I choose for the not-extension scope function unless there's a good reason."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T07:29:50.483",
"Id": "244654",
"ParentId": "244600",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244654",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T07:30:30.007",
"Id": "244600",
"Score": "2",
"Tags": [
"linked-list",
"kotlin"
],
"Title": "Double LinkedList Deep Copy in Kotlin"
}
|
244600
|
<p>Here is my source code for my very first app in Java. I am completely new to the language; any help and criticism is welcomed!</p>
<pre><code>package com.company;
import java.util.*;
public class Main {
public static float multiply(float a, float b)
{
return a*b;
}
public static float divide(float a, float b)
{
return a/b;
}
public static float addition(float a, float b)
{
return a+b;
}
public static float subtraction(float a, float b)
{
return a-b;
}
public static void main(String[] args)
{
Scanner scanner;
float firstNum, secondNum, result;
String operation;
scanner = new Scanner(System.in);
while(true){
System.out.println("Select operation (*,/,+,-)");
operation = scanner.next();
if (operation.matches("[*/+-]")) {
break;
} else {
System.out.println("Invalid operation");
}
}
System.out.println("Type in first number");
firstNum = scanner.nextFloat();
System.out.println("Type in second number");
secondNum = scanner.nextFloat();
switch(operation)
{
case "*": result = multiply(firstNum, secondNum); break;
case "/": result = divide(firstNum, secondNum); break;
case "+": result = addition(firstNum, secondNum); break;
case "-": result = subtraction(firstNum, secondNum); break;
default: result = 0;
}
System.out.println("Result of your operation is " + result);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T08:53:45.557",
"Id": "480406",
"Score": "0",
"body": "If you're interested in how to implement more complex expressions with operator precedence etc. take a look at the \"expr\" program in Gnu coreutils project. https://github.com/coreutils It's C but it's quite easily translated to Java. Instead of asking for input you could just require it as command line arguments like the aforementioned Gnu tool does. If you're reading input from console as an exercise, it's a lesson that has practically zero payout. I have never had to read user input from console during my 25 years as software developer."
}
] |
[
{
"body": "<p>For a first application in Java, good job!</p>\n<p>I have some suggestions for your code.</p>\n<h2>When using regex, try to uses the <code>java.util.regex.Pattern</code> class instead of the <code>java.lang.String#matches</code> method.</h2>\n<p>When using the <code>java.lang.String#matches</code> method, the regex pattern is recompiled each time the method is called. This can cause a slowdown in your method execution.</p>\n<p><strong>How to uses the matcher</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>Pattern pattern = Pattern.compile("[*/+-]");\nwhile (true) {\n //[...]\n if (pattern.matcher(operation).matches()) {\n //[...]\n }\n //[...]\n}\n</code></pre>\n<h2>Extract some of the logic to methods.</h2>\n<p>Extracting code can make the code shorter and easier to read. Also when you have logic that does the same thing, you can generally move it into a method and reuse it.</p>\n<ul>\n<li>You can make a method that asks a question and read the next float; this will allow you to reuse the same method.</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n //[...]\n firstNum = askQuestionAndReceiveFloat(scanner, "Type in first number");\n secondNum = askQuestionAndReceiveFloat(scanner, "Type in second number");\n //[...]\n}\n\nprivate static float askQuestionAndReceiveFloat(Scanner scanner, String question) {\n System.out.println(question);\n return scanner.nextFloat();\n}\n</code></pre>\n<ul>\n<li>You can extract the logic to parse the operation.</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code>private static String askForOperation(Pattern pattern, Scanner scanner) {\n String operation;\n while (true) {\n System.out.println("Select operation (*,/,+,-)");\n operation = scanner.next();\n\n if (pattern.matcher(operation).matches()) {\n break;\n } else {\n System.out.println("Invalid operation");\n }\n }\n return operation;\n}\n</code></pre>\n<ul>\n<li>If you are using Java 14, you can use the newer version of the <a href=\"https://docs.oracle.com/en/java/javase/14/language/switch-expressions.html\" rel=\"nofollow noreferrer\"><code>switch-case</code></a> and return the value.</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code>private static float getResult(float firstNum, float secondNum, String operation) {\n return switch (operation) {\n case "*" -> multiply(firstNum, secondNum);\n case "/" -> divide(firstNum, secondNum);\n case "+" -> addition(firstNum, secondNum);\n case "-" -> subtraction(firstNum, secondNum);\n default -> 0;\n };\n}\n</code></pre>\n<p>Those's changes will make the main method shorter and easier to read!</p>\n<h2>Use <code>java.io.PrintStream#printf</code> instead of <code>java.io.PrintStream#println</code> when you have to concatenate</h2>\n<p><code>java.io.PrintStream#printf</code> offer you to use <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Formatter.html\" rel=\"nofollow noreferrer\">patterns</a> to build the string without concatenating it manually. The only downside is you will be forced to add the break line character yourself; in java you can use the <code>%n</code> to break the line (portable between various platforms) or uses the traditional <code>\\n</code> / <code>\\r\\n</code>.</p>\n<pre class=\"lang-java prettyprint-override\"><code>System.out.printf("Result of your operation is %s%n", result);\n</code></pre>\n<h1>Refactored code</h1>\n<pre class=\"lang-java prettyprint-override\"><code>public static float multiply(float a, float b) {\n return a * b;\n}\n\npublic static float divide(float a, float b) {\n return a / b;\n}\n\npublic static float addition(float a, float b) {\n return a + b;\n}\n\npublic static float subtraction(float a, float b) {\n return a - b;\n}\n\nprivate static float askQuestionAndReceiveFloat(Scanner scanner, String question) {\n System.out.println(question);\n return scanner.nextFloat();\n}\n\nprivate static String askForOperation(Pattern pattern, Scanner scanner) {\n String operation;\n while (true) {\n System.out.println("Select operation (*,/,+,-)");\n operation = scanner.next();\n\n if (pattern.matcher(operation).matches()) {\n break;\n } else {\n System.out.println("Invalid operation");\n }\n }\n return operation;\n}\n\nprivate static float getResult(float firstNum, float secondNum, String operation) {\n return switch (operation) {\n case "*" -> multiply(firstNum, secondNum);\n case "/" -> divide(firstNum, secondNum);\n case "+" -> addition(firstNum, secondNum);\n case "-" -> subtraction(firstNum, secondNum);\n default -> 0;\n };\n}\n\npublic static void main(String[] args) {\n Pattern pattern = Pattern.compile("[*/+-]");\n Scanner scanner = new Scanner(System.in);\n float firstNum, secondNum, result;\n String operation = askForOperation(pattern, scanner);\n\n firstNum = askQuestionAndReceiveFloat(scanner, "Type in first number");\n secondNum = askQuestionAndReceiveFloat(scanner, "Type in second number");\n result = getResult(firstNum, secondNum, operation);\n\n System.out.printf("Result of your operation is %s%n", result);\n}\n</code></pre>\n<p>Also, I suggest to handle the <code>x / 0</code> case :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T18:08:51.317",
"Id": "480248",
"Score": "0",
"body": "Many thanks! Very \"verbose\" comments :) I have a lot to learn from this"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T16:46:58.843",
"Id": "244621",
"ParentId": "244610",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244621",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T11:43:22.120",
"Id": "244610",
"Score": "4",
"Tags": [
"java",
"beginner"
],
"Title": "Calculator console app in Java"
}
|
244610
|
<p>I have a CSV like the following.</p>
<pre class="lang-none prettyprint-override"><code>Category,Position,Name,Time,Team,avg_power,20minWKG,Male?,20minpower
A,1,Tom Smith ,00:41:58.95,7605,295,4.4,1,299.2
A,2,James Johnson,00:41:58.99,2740,281,4.5,1,283.95
A,3,Tom Lamb,00:41:59.25,1634,311,4.2,1,315
B,1,Elliot Farmer,00:45:06.23,7562,306,3.9,1,312
B,2,Matt Jones,00:45:10.10,4400,292,4.0,1,300
B,3,Patrick James,00:45:39.83,6508,299,4.1,1,311.6
</code></pre>
<p>I get the time of the rider in first place of category 'A'.
I then give any rider that is 15% slower than this 0 points in a new CSV.
For example if the first rider take 1 minute 40 seconds, then anyone slower than 1 minute 55 seconds will get 0 points.</p>
<pre class="lang-py prettyprint-override"><code>def convert(seconds): # function to convert amount of seconds to a time format
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
return "%d:%02d:%02d" % (hour, minutes, seconds)
with open("results.csv", 'rt', encoding='UTF-8', errors='ignore') as file: # opening the full results file
reader = csv.reader(file, skipinitialspace=True, escapechar='\\') # skipping headers
MaleCategoryList = [] # setting category as blank so a change is recognised
for row in reader:
if row[0] not in MaleCategoryList:
if row[0] == "A":
firstPlaceTime = datetime.strptime(row[3], "%H:%M:%S.%f")
timeInSecs = firstPlaceTime.second + firstPlaceTime.minute * 60 + firstPlaceTime.hour * 3600
timeDifference = timeInSecs * 1.15
MaxTime = datetime.strptime(convert(timeDifference), "%H:%M:%S")
# some code here which is not relevant i.e calculate points
if cat == "A" and datetime.strptime(row[3], "%H:%M:%S.%f") > MaxTime:
points = int(0)
position_for_file = "DQ Time-Cut"
cat = "Time Cut"
data = {'Position': position_for_file, 'Category': cat, 'Name': name, 'Club': club,
'Points': points, 'Time': time} # dictionary of data to write to CSV
</code></pre>
<p>I feel that my code is very messy and inefficient. This is as there are lots of if in my loop and I believe a lot of the calculations seem unnecessary. Do you have any ideas of how I could improve my code?</p>
<p>I would prefer to not use Pandas if possible. This is as I have never used. However if there is a fast and easily maintainable solution to this with Pandas then I would be interested.</p>
|
[] |
[
{
"body": "<h2>Time calculation</h2>\n<pre><code>timeInSecs = firstPlaceTime.second + firstPlaceTime.minute * 60 + firstPlaceTime.hour * 3600\n</code></pre>\n<p>The first thing to do is attempt to get this as a <code>timespan</code> and avoid your own time math. In other words,</p>\n<pre><code>from datetime import datetime, time, timedelta\n\nMIDNIGHT = time()\n\n# ...\n\nfirst_place_time = datetime.strptime(row[3], "%H:%M:%S.%f")\ntime_span = first_place_time - datetime.combine(first_place_time, MIDNIGHT)\ntime_difference = time_span.total_seconds() * 1.15\n</code></pre>\n<h2>Unpacking</h2>\n<p>You can unpack your row and avoid <code>row[0]</code>, etc. fixed indexing, like:</p>\n<pre><code>category, position, name, race_time = row[:4]\n</code></pre>\n<h2>Call reuse</h2>\n<p>This is written twice:</p>\n<pre><code>datetime.strptime(row[3], "%H:%M:%S.%f")\n</code></pre>\n<p>so store it to a temporary variable.</p>\n<h2>PEP8</h2>\n<p><code>MaleCategoryList</code> should be <code>male_category_list</code>, and <code>MaxTime</code> should be <code>max_time</code>.</p>\n<h2>Convert</h2>\n<p>Given the above code, you can get rid of most of <code>convert</code>. You should not put the time through another round-trip using a string.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T14:41:32.000",
"Id": "480214",
"Score": "0",
"body": "Thanks, I'll have a go with your fixes soon. I'm fairly new to Python, I think unpacking is a good idea, I will implement that, could you explain the PEP8 section please from a quick look it seems like that's the general convention but why do you convert `MaleCategoryList` but not `firstPlaceTime` for example? I've also updated the code with a full CSV"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T14:42:37.147",
"Id": "480215",
"Score": "0",
"body": "I just offered examples; `first_place_time` would also be affected."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T14:29:48.693",
"Id": "244613",
"ParentId": "244611",
"Score": "6"
}
},
{
"body": "<p>Since you asked for <code>pandas</code>, here is one way to do it:</p>\n<pre><code>import pandas as pd\nimport numpy as np\n\ndf = pd.read_csv("results.csv", encoding='UTF-8',\n skipinitialspace=True, escapechar='\\\\')\n# convert the times to timedeltas right away\ndf["Time"] = pd.to_timedelta(df["Time"])\n# if it is not already sorted, do so\ndf = df.sort_values("Time")\n# we are going to need this mask to distinguish between category A and the others\ncategory_A = df["Category"] == "A"\n# calculate the cutoff time, after which people get 0 points\ncutoff = df.loc[category_A, "Time"].min().total_seconds() * 1.15\n# calculate the points for all runners (however you do that)\ndf["Points"] = calculate_points(df)\n# set the points to 0 for all runners in category A which are above the cutoff time\ndf.loc[category_A & (df["Time"].dt.total_seconds() > cutoff), "Points"] = 0\n# save to new file\ndf.to_csv("output.csv")\nprint(df)\n\n# Category Position Name Time Team avg_power 20minWKG Male? 20minpower Points\n# 0 A 1 Tom Smith 00:41:58.950000 7605 295 4.4 1 299.20 100.0\n# 1 A 2 James Johnson 00:41:58.990000 2740 281 4.5 1 283.95 100.0\n# 3 B 1 Elliot Farmer 00:45:06.230000 7562 306 3.9 1 312.00 42.0\n# 4 B 2 Matt Jones 00:45:10.100000 4400 292 4.0 1 300.00 42.0\n# 5 B 3 Patrick James 00:45:39.830000 6508 299 4.1 1 311.60 42.0\n# 2 A 3 Tom Lamb 00:51:59.250000 1634 311 4.2 1 315.00 0.0\n</code></pre>\n<p>Note that I modified the time of "Tom Lamb" so that there is actually a runner which is affected by the time cut</p>\n<hr />\n<p>This is not the nicest code. It could be improved if this cut was done in each category, compared to the fastest person in that category, or, potentially, if you showed the point calculation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T15:06:47.290",
"Id": "480218",
"Score": "1",
"body": "I have added point calculation but I’m not sure it’s the most useful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T22:29:24.117",
"Id": "480270",
"Score": "0",
"body": "Also, I just re-read this the cut isn't done to everyone in the category as the calculation is if you are more than 15% above first-place time in Cat A you get 0 points. I like the pandas answer but I did not notice much more of a speed/debuggability improvement so didn't use it as is would be harder for me to change myself."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T14:59:15.860",
"Id": "244614",
"ParentId": "244611",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "244613",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T13:47:20.397",
"Id": "244611",
"Score": "5",
"Tags": [
"python",
"datetime"
],
"Title": "Removing points from slow riders"
}
|
244611
|
<p>I tried printing the first pair of prime number in between a list of numbers with a particular difference. But my run time is still too high (for large range of numbers). I want to reduce the run time by using any method from standard library like <code>itertools</code>.</p>
<pre><code>def prime(x):
"""To generate prime number"""
a = x // 2 + 1
for i in range(2, x):
if x % i == 0:
return False
elif i == a:
return True
def gap(p, q, m):
"""To generate gap in between two prime numbers"""
"""p is the difference,q is the lower limit where the list of numbers in between which prime is filtered,m is the upper limit"""
b = []
a = b.append
c = prime
q = (q // 2) * 2 + 1
for i in range(q, m + 1, 2):
if c(i) == True:
a(i)
if len(b) > 1:
if b[-1] - b[-2] == p:
return [b[-2], b[-1]]
</code></pre>
|
[] |
[
{
"body": "<p>The most basic method of checking the primality of a given integer n is called trial division. This method divides n by each integer from 2 up to the square root of n. Any such integer dividing n evenly establishes n as composite; otherwise it is prime. Integers larger than the square root do not need to be checked because, whenever n=a * b, one of the two factors a and b is less than or equal to the square root of n. Another optimization is to check only primes as factors in this range. For instance, to check whether 37 is prime, this method divides it by the primes in the range from <span class=\"math-container\">\\$2\\ to\\ √37\\$</span>, which are <span class=\"math-container\">\\$2, 3,\\ and\\ 5\\$</span>. Each division produces a nonzero remainder, so 37 is indeed prime (from wikipedia).</p>\n<pre><code>import math\ndef prime(x):\n r = int(math.sqrt(x))\n for i in range(2, r + 1):\n if x % i == 0:\n return False\n return True\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T04:56:20.513",
"Id": "480289",
"Score": "2",
"body": "Primality testing such as Miller-Rabin is significantly faster for large numbers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T14:55:49.243",
"Id": "480326",
"Score": "1",
"body": "The `range(...)` function requires integer arguments. `sqrt(...)` returns a float., so your code generates a `TypeError`. Use `isqrt()`. Secondly, be careful of non-inclusive endpoints. `prime(25)` would incorrectly return `True`, since 5 is a divisor of 25, but `5 in range(2, 5)` is false."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T18:14:36.233",
"Id": "480351",
"Score": "0",
"body": "If the bugs in the code sample were fixed, this would be the best answer, as it directly addresses the question (run time performance)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T18:19:20.823",
"Id": "480352",
"Score": "0",
"body": "@AdrianMcCarthy DOne, Thanks"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T18:16:29.850",
"Id": "244628",
"ParentId": "244615",
"Score": "3"
}
},
{
"body": "<p>First thing first, get rid of these ugly <code>a</code> and <code>c</code>. They do not add any value, but only obfuscate the code.</p>\n<pre><code>def gap(p, q, m):\n """To generate gap in between two prime numbers"""\n"""p is the difference,q is the lower limit where the list of numbers in between which prime is filtered,m is the upper limit"""\n b = []\n q = (q // 2) * 2 + 1\n for i in range(q, m + 1, 2):\n if prime(i):\n b.append(i)\n if len(b) > 1:\n if b[-1] - b[-2] == p:\n return [b[-2], b[-1]]\n</code></pre>\n<p>Notice that I also removed a redundant <code>== True</code>.</p>\n<p>Second, you don't need to keep the entire list of primes. You are only interested in the last two of them. Consider</p>\n<pre><code>def gap(p, q, m):\n b = find_first_prime_after(q)\n for i in range(b + 2, m + 1, 2):\n if prime(i):\n if i - b == p:\n return b, i\n b = i\n</code></pre>\n<p>Finally, your primality test is very suboptimal. Implementing the sieve would give you a boost.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T10:51:24.143",
"Id": "480412",
"Score": "0",
"body": "How does the find_first_prime_after works? Do I need to write a def for it? Or it's an inbuilt function."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T20:12:16.067",
"Id": "244635",
"ParentId": "244615",
"Score": "4"
}
},
{
"body": "<p>Depending on how large your lower and upper limits are, it may be faster to just generate all primes using a <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes</a> implementation.</p>\n<p>If the limits are beyond what is reasonable to generate all primes for, then <a href=\"https://en.wikipedia.org/wiki/Primality_test\" rel=\"nofollow noreferrer\">primality testing</a> such as Miller-Rabin is significantly faster than trial division. For example, <code>gmpy2.is_prime</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T04:55:35.187",
"Id": "244649",
"ParentId": "244615",
"Score": "3"
}
},
{
"body": "<p>You ask for speed up, so let's get timing data for the version you posted. I've appended this to your code</p>\n<pre><code>from timeit import default_timer as timer\nargs = (2, 1234567, 2345678)\nprint(args)\nfoo = gap(*args)\n\ndef timedGap():\n start = timer()\n gap(*args)\n end = timer()\n return end-start\n\n(timedGap() for dummy in range(1, 3))\ntimings = tuple((timedGap() for dummy in range(1, 10)))\nprint( ( min(timings), sum(timings)/len(timings), max(timings) ) )\nprint(foo)\n</code></pre>\n<p>This is configured to search for a pair of twin primes in the range [ 1 234 567, 2 345 678 ]. It prints the arguments to <code>gap()</code>, then runs <code>gap()</code> once to get the result, stored in <code>foo</code>. Then runs <code>timedGap()</code> three times, discarding the timing data, in an attempt to do whatever priming is possible. Then runs <code>timedGap()</code> ten times to gather run time statistics. What is reported is (minimal time, average time, and maximal time) then the contents of <code>foo</code>.</p>\n<p>On my hardware, your code produces the following output (with timings truncated to milliseconds for readability).</p>\n<pre><code>(2, 1234567, 2345678)\n(0.889..., 0.928..., 0.956...)\n[1234757, 1234759]\n</code></pre>\n<p>The same timing protocol is used subsequently.</p>\n<p>First, a prime is <code>2</code>, <code>3</code>, congruent to <code>1</code> modulo <code>6</code> or congruent to <code>5</code> modulo <code>6</code>. (Proof 1) So in prime(x), you should only be testing one-third of <code>range(2,x)</code>. Also, the smallest prime divisor of a composite number is no greater than the square root of that number. (Proof 2) This means we can rewrite <code>prime(x)</code> as follows.</p>\n<pre><code>from math import sqrt, floor\ndef prime(x):\n """Test that x is a prime number. Requires x is a positive integer."""\n if not( (x > 0) and isinstance(x, int) ):\n raise ValueError("x must be a positive integer.")\n # Note that the original prime() incorrect returns nothing when passed 1 as input. Let's fix that.\n # 1 is not prime.\n if (x == 1):\n return False\n # We check 2, 3, AND 5 explicitly so that we can start the subsequent range at 6.\n # Note that this leaves only (1/2)(2/3)(4/5) = 4/15 ~= 25% of integers to check further.\n if (x == 2) or (x == 3) or (x == 5):\n return True\n if (x % 2 == 0) or (x % 3 == 0) or (x % 5 == 0):\n return False\n # Rather than alternately increment by 2 and 4, test twice per block of 6.\n for i in range(6, floor(sqrt(x)) + 1, 6):\n if x %(i+1) == 0:\n return False\n if x %(i+5) == 0:\n return False\n return True\n</code></pre>\n<p>and timing (truncated at microseconds):</p>\n<pre><code>(2, 1234567, 2345678)\n(0.000657..., 0.000676..., 0.000729...)\n[1234757, 1234759]\n</code></pre>\n<p>so that's more than 1000-times faster.</p>\n<p>We could replace the checks with <code>x % 2</code>, <code>x % 3</code>, and <code>x % 5</code>, with <code>math.gcd(x,30) > 1</code>, but this doesn't save enough time to bother.</p>\n<p>I don't have time to improve your <code>gap()</code>, but here are some comments/observations.</p>\n<p>We already know that all primes except 2 and 3 are congruent to 1 or 5 modulo 6, so the only possible prime gaps start at 2 and have odd length, start at 3 and have even length, or start at a prime congruent to 1 or 5 modulo 6 and have length congruent to 5-5=0, 5-1=4, 1-5=2, or 1-1=0 modulo 6. (And the collection of integers that are congruent to 0, 2, or 4 modulo 6 is the even integers.) This should allow us to reject impossible <code>p</code>s much faster.</p>\n<p>(A brief style comment: <code>p</code> and <code>q</code> are common labels for prime numbers and <code>m</code> is a common label for an integer. <strong>Much</strong> better argument names for <code>gap()</code> are <code>start</code>, <code>end</code>, and <code>gapSize</code>.)</p>\n<p>Observations:</p>\n<ul>\n<li>The list of primes less than the least potential member of a sought pair are of no use to us, so retaining them (and modifying a list of them) is a waste of time and space.</li>\n<li>We only need to iterate through potential least members of the pair to find the first pair and we can stop as soon as the second member would be outside of the search range.</li>\n<li>So let <code>i</code> be the potential first prime in the pair and have it range from <code>q</code> to <code>m - p</code>, only taking values where <code>i</code> and <code>i + p</code> are congruent to <code>1</code>s and <code>5</code>s modulo <code>6</code>. (For instance, if <code>p</code> is <code>2</code>, then the least member must be congruent to <code>5</code> modulo <code>6</code> and the greater member is automatically congruent to <code>1</code> modulo <code>6</code>.)</li>\n</ul>\n<p>Proof 1:</p>\n<p>An integer, <code>N</code>, is congruent to <code>a</code> modulo <code>6</code> if there is an integer <code>k</code> such that <code>N == a+6k</code>.</p>\n<ul>\n<li>If <code>N</code> is congruent to <code>0</code> modulo <code>6</code> then <code>N = 0 + 6k</code> and <code>6</code> divides <code>N</code>, so <code>N</code> is not prime.</li>\n<li>If <code>N</code> is congruent to <code>2</code> modulo <code>6</code> then <code>N = 2 + 6k = 2(1+3k)</code> and <code>2</code> divides <code>N</code>, so either <code>N = 2</code> or <code>N</code> is not prime.</li>\n<li>If <code>N</code> is congruent to <code>3</code> modulo <code>6</code> then <code>N = 3 + 6k = 3(1+2k)</code> and <code>3</code> divides <code>N</code>, so either <code>N = 3</code> or <code>N</code> is not prime.</li>\n<li>If <code>N</code> is congruent to <code>4</code> modulo <code>6</code> then <code>N = 4 + 6k = 2(2+3k)</code> and <code>2</code> divides <code>N</code>, so <code>N</code> is not prime. (We can skip "<code>N = 2</code>" as a possibility because <code>2+3k</code> can never be <code>1</code>.)</li>\n</ul>\n<p>We have found that for <code>N</code> to be prime, either <code>N = 2</code>, <code>N = 3</code>, <code>N</code> is congruent to <code>1</code> modulo <code>6</code>, or <code>N</code> is congruent to <code>5</code> modulo <code>6</code>.</p>\n<p>Proof 2:</p>\n<p>Suppose that <code>N</code> is a composite number, so that it has at least two prime divisors. Assume further that all the prime divisors are greater than the square root of <code>N</code>. This is a contradiction. Call the two smallest prime divisors of <code>N</code> by the names <code>p</code> and <code>q</code>. Note that <code>p > sqrt(N)</code> and <code>q > sqrt(N)</code> and that <code>pq</code> is a divisor of <code>N</code> so is no greater than <code>N</code>. But, <code>pq > sqrt(N)sqrt(N) = N</code>, which is a contradiction. Therefore, any composite integer has a prime divisor no greater than its square root.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T21:49:47.100",
"Id": "244682",
"ParentId": "244615",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T15:17:30.947",
"Id": "244615",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"time-limit-exceeded",
"primes",
"iteration"
],
"Title": "Finding the first pair of prime numbers that have some specified difference"
}
|
244615
|
<p>Please review my C++ CSV parsing class.</p>
<p>I have some specific questions:</p>
<ol>
<li>Should <code>get_next_record</code> be a static function?</li>
<li><code>CsvParser</code> implies values will be separated by commas so is a field separator constructor over the top?</li>
<li><code>record.clear()</code> at the beginning of <code>get_next_record</code>. Any other ways of solving the problem of removing last record. I realise that you could return record, but then you have the problem of how to deal with EOF or a stream error.</li>
</ol>
<p><code>CsvParser.hpp</code></p>
<pre><code>#ifndef CSV_PARSER_HPP_
#define CSV_PARSER_HPP_
#include <iostream>
#include <string>
#include <vector>
using Field = std::string;
using Record = std::vector<Field>;
using Records = std::vector<Record>;
class CsvParser {
public:
CsvParser(char field_separator = ',');
bool get_next_record(std::istream& istrm, Record& record) const;
private:
char field_separator_char;
};
#endif // CSV_PARSER_HPP_
</code></pre>
<p><code>CsvParser.cpp</code></p>
<pre><code>#include "CsvParser.hpp"
CsvParser::CsvParser(char field_separator) : field_separator_char(field_separator) {}
bool CsvParser::get_next_record(std::istream& istrm, Record& record) const {
// Having to clear record because otherwise the program will keep pushing back
// fields into the vector feels dirty. How could this be improved?
record.clear();
bool in_quotes = false;
Field field;
int ch;
while (istrm) {
ch = istrm.get();
if (ch == EOF || (ch == '\n' && !in_quotes)) {
if (ch == EOF && record.empty() && field.empty()) {
return false;
}
else {
record.push_back(field);
return true;
}
}
else if (ch == field_separator_char && !in_quotes) {
record.push_back(field);
field.clear();
}
else if (ch == '"') {
if (!in_quotes) {
in_quotes = true;
}
else {
// Could be an embedded " if next symbol not comma
int nextch = istrm.peek();
if (nextch != field_separator_char && nextch != '\n' && nextch != EOF) {
field += static_cast<char>(ch);
}
else {
in_quotes = false;
}
}
}
else if (ch == '\r') {
if (in_quotes) {
field += static_cast<char>(ch);
}
}
else {
field += static_cast<char>(ch);
}
}
return false;
}
</code></pre>
<p>Exercising using google test:</p>
<pre><code>#include <gtest/gtest.h>
#include "CsvParser.hpp"
#include <sstream>
#include <string>
class CsvParserTest : public ::testing::Test {
public:
CsvParser parser;
};
TEST_F(CsvParserTest, EmptyRecord) {
const std::string csv{ "" };
std::stringstream strm(csv);
Record record;
EXPECT_FALSE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 0u);
}
TEST_F(CsvParserTest, SimpleSingleRecord) {
const std::string csv{ "AA,BB,CC" };
std::stringstream strm(csv);
Record record;
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "AA");
EXPECT_EQ(record[1], "BB");
EXPECT_EQ(record[2], "CC");
}
TEST_F(CsvParserTest, SimpleTwoRecord) {
const std::string csv{ "AA,BB,CC\r\nDD,EE,FF" };
std::stringstream strm(csv);
Record record;
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "AA");
EXPECT_EQ(record[1], "BB");
EXPECT_EQ(record[2], "CC");
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "DD");
EXPECT_EQ(record[1], "EE");
EXPECT_EQ(record[2], "FF");
}
TEST_F(CsvParserTest, SimpleQuotedField) {
const std::string csv{ "\"A\",BB,CCC" };
std::stringstream strm(csv);
Record record;
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "A");
EXPECT_EQ(record[1], "BB");
EXPECT_EQ(record[2], "CCC");
}
TEST_F(CsvParserTest, QuotesEmbeddedInQuotedField) {
const std::string csv{ "\"\"A\"\",BB,CCC" };
std::stringstream strm(csv);
Record record;
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "\"A\"");
EXPECT_EQ(record[1], "BB");
EXPECT_EQ(record[2], "CCC");
}
TEST_F(CsvParserTest, LinefeedEmbeddedInQuotedField) {
const std::string csv{ "\"\"A\n\"\",BB,CCC" };
std::stringstream strm(csv);
Record record;
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "\"A\n\"");
EXPECT_EQ(record[1], "BB");
EXPECT_EQ(record[2], "CCC");
}
TEST_F(CsvParserTest, CommaEmbeddedInQuotedField) {
const std::string csv{ R"(""A,"",BB,CCC)" };
std::stringstream strm(csv);
Record record;
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], R"("A,")");
EXPECT_EQ(record[1], "BB");
EXPECT_EQ(record[2], "CCC");
}
TEST_F(CsvParserTest, EmptyRow) {
const std::string csv{ ",," };
std::stringstream strm(csv);
Record record;
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0].size(), 0u);
EXPECT_EQ(record[1].size(), 0u);
EXPECT_EQ(record[2].size(), 0u);
}
TEST_F(CsvParserTest, QuotedFollowedByTwoEmptyFields) {
const std::string csv{ "\"A\n\n\nB\",," };
std::stringstream strm(csv);
Record record;
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "A\n\n\nB");
EXPECT_EQ(record[1].size(), 0u);
EXPECT_EQ(record[2].size(), 0u);
}
TEST_F(CsvParserTest, EmptyThenQuotedThenEmptyField) {
const std::string csv{ ",\"A\n\n\nB\"," };
std::stringstream strm(csv);
Record record;
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0].size(), 0u);
EXPECT_EQ(record[1], "A\n\n\nB");
EXPECT_EQ(record[2].size(), 0u);
}
TEST_F(CsvParserTest, EmptyEmptyThenQuoted) {
const std::string csv{ ",,\"A\n\n\nB\"" };
std::stringstream strm(csv);
Record record;
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0].size(), 0u);
EXPECT_EQ(record[1].size(), 0u);
EXPECT_EQ(record[2], "A\n\n\nB");
}
TEST_F(CsvParserTest, CRLFEndOfLIne) {
const std::string csv{ "A,B,C\r\nD,E,F" };
std::stringstream strm(csv);
Record record;
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "A");
EXPECT_EQ(record[1], "B");
EXPECT_EQ(record[2], "C");
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "D");
EXPECT_EQ(record[1], "E");
EXPECT_EQ(record[2], "F");
}
TEST_F(CsvParserTest, EmbeddedCRLF) {
const std::string csv{ "A,\"B\r\nC\",D\r\nE,F,G" };
std::stringstream strm(csv);
Record record;
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "A");
EXPECT_EQ(record[1], "B\r\nC");
EXPECT_EQ(record[2], "D");
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "E");
EXPECT_EQ(record[1], "F");
EXPECT_EQ(record[2], "G");
}
TEST_F(CsvParserTest, Complex) {
const std::string csv = "AAA,BB,CCC\nDDD,EE,FFF\n\"A A\",\"B\nB\",CC\n\"A,B,C\",\"D E\",F\n\"Billy \"Da Man\" Hooker\",,\n,,\n,,\"Yo bitches!\"\n,,\"Holler if you luv dem \"hat\" bitches\"\n,\"These are my long\nnotes on a load\nof stuff\n fancy some commas:,,,,,,,,,,,,,,,,,,,,,,,,,,,\",";
std::stringstream strm(csv);
Record record;
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "AAA");
EXPECT_EQ(record[1], "BB");
EXPECT_EQ(record[2], "CCC");
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "DDD");
EXPECT_EQ(record[1], "EE");
EXPECT_EQ(record[2], "FFF");
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "A A");
EXPECT_EQ(record[1], "B\nB");
EXPECT_EQ(record[2], "CC");
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "A,B,C");
EXPECT_EQ(record[1], "D E");
EXPECT_EQ(record[2], "F");
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "Billy \"Da Man\" Hooker");
EXPECT_EQ(record[1], "");
EXPECT_EQ(record[2], "");
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "");
EXPECT_EQ(record[1], "");
EXPECT_EQ(record[2], "");
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "");
EXPECT_EQ(record[1], "");
EXPECT_EQ(record[2], "Yo bitches!");
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "");
EXPECT_EQ(record[1], "");
EXPECT_EQ(record[2], "Holler if you luv dem \"hat\" bitches");
EXPECT_TRUE(parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "");
EXPECT_EQ(record[1], "These are my long\nnotes on a load\nof stuff\n fancy some commas:,,,,,,,,,,,,,,,,,,,,,,,,,,,");
EXPECT_EQ(record[2], "");
}
TEST_F(CsvParserTest, TabSeparated) {
const std::string csv{ "AA\tBB\tCC\nDD\tEE\tFF" };
std::stringstream strm(csv);
Record record;
CsvParser tab_parser('\t');
EXPECT_TRUE(tab_parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "AA");
EXPECT_EQ(record[1], "BB");
EXPECT_EQ(record[2], "CC");
EXPECT_TRUE(tab_parser.get_next_record(strm, record));
EXPECT_EQ(record.size(), 3u);
EXPECT_EQ(record[0], "DD");
EXPECT_EQ(record[1], "EE");
EXPECT_EQ(record[2], "FF");
}
</code></pre>
|
[] |
[
{
"body": "<p>The code is too low level and it lacks functionality.</p>\n<p>It would be more idiomatic (and probably more efficient depending on circumstances) to use <code>std::getline</code> and extract the whole line from the stream. Then you can just find separators <code>,</code> one by one via <code>find_first_of</code> function of string and separate the line into array of strings.</p>\n<p>This method might be lacking when there large rows in the csv file but the whole design of getting vector of strings is an even bigger victim of this case. Consider using a container buffer and vector of string views instead.</p>\n<p>Lack of functionality: at times one has knowledge of the format of the csv file and want to perform conversion inplace instead of getting a vector of strings. If you could make a couple methods that satisfy common cases you need to support it would transform your csv library into a usable one.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T20:25:51.367",
"Id": "480261",
"Score": "0",
"body": "CSV format uses embedded field and record separators so getline would not work (without modification anyway)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T20:29:43.333",
"Id": "480262",
"Score": "0",
"body": "Could you give me some help on the couple methods that would satisfy common cases? Not sure what you have in mind?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T04:30:43.610",
"Id": "480288",
"Score": "0",
"body": "@arcomber oh, the quotes. Damn. Well you can analyze if the last separator is inside quotes and repeat (with modification) getline with `\"` and then with `\\n` but that's indeed annoying. About common use cases - imagine user knows that expected format of rows is `int, int, double, string` and he wants to obtain the ints and double and store them in a vector of a class of his choice. To accomodate it, you can make method that converts the strings into tuple of `int,int,double,string` and pass it to the user defined function that converts to the type that the user needs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T13:26:43.273",
"Id": "480317",
"Score": "0",
"body": "Like tuple idea, will work on that."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T18:06:10.047",
"Id": "244627",
"ParentId": "244620",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244627",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T16:28:27.733",
"Id": "244620",
"Score": "2",
"Tags": [
"c++",
"parsing",
"csv"
],
"Title": "Library for parsing CSV data"
}
|
244620
|
<p>I am using a dictionary to save possible trajectories in a game. A trajectory is defined as a list of numbers separated by <code>_</code>. For example <code>'3_7_2_5'</code> is a trajectory of 4 steps. I use a dictionary as I assign a value to each trajectory. The meaning of this value does not matter for the purpose of my question. I also save the trajectories in separated dictionaries if they have different numbers of steps.</p>
<p>I want to update the dictionary in such a way that only the trajectories starting from <code>'1'</code> are preserved. Moreover, I want to remove the <code>'1'</code> from the name, since I don't need to keep listing a step that has already been made.</p>
<pre><code># here I create the initial dictionaries
pts=[{},{},{}]
for j in range(20):
k=random.choice(range(3))
path=str(k)
for d in range(len(pts)):
k=random.choice(range(4))
pts[d][path]=k
path+='_'+str(k)
print 'initial dictionaries =',pts
# here I make the update
ind=1
new_pts=[{},{},{}]
path=str(ind)
for d in range(len(pts)-1):
for path in pts[d+1]:
if path[:len(str(ind))]==str(ind):
new_pts[d][path[len(str(ind))+1:]]=pts[d+1][path]
pts=new_pts
print 'updated dictionaries =',pts
</code></pre>
<p>As you can see, the first element of the old list <code>pts</code> has been discarded. The second element has been used to create the first element of the updated list and so on.</p>
<p>Now, it seems to me that my algorithm is not very efficient. For updating the dictionary I am using a <code>for</code> loop over all keys, even though most of them are going to be discarded.
Is there a better, faster way to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T02:50:35.167",
"Id": "480283",
"Score": "1",
"body": "(Please include an import such that `random.choice()` works by just cut&paste. Please tag [tag:python-2.x] (or add parentheses to the `print`).) `For [update I] loop over all keys, even though most [are] discarded` For really helpful reviews, please provide more context: Why are those entries in the dictionary in the first place? What is special about *trajectories starting from '1'*? (What about those starting from `0`?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T19:38:57.947",
"Id": "480354",
"Score": "0",
"body": "@greybeard \nIn my example, I assume that I actually made the choice `'1'`.Therefore the trajectories must be updated, keeping only those that were starting by `'1'`. The choice of `1` specifically is arbitrary, I could have chosen `0` or any number in my example."
}
] |
[
{
"body": "<h1>Basic Review</h1>\n<ol>\n<li><p>You should <code>import print_function from __future__</code>. So you can use print like you can in Python 3.</p>\n</li>\n<li><p>Your variable names are poor.</p>\n<ul>\n<li><code>j</code> should be <code>_</code>.</li>\n<li>What do <code>j</code>, <code>k</code> and <code>d</code> mean?</li>\n<li>Why not just type out <code>parts</code> rather than use <code>pts</code>?</li>\n</ul>\n</li>\n<li><p>The way you're generating key value pairs in not amazing. If you make a function to build 20 keys then it would be much easier to understand. This is as things are split into two core aspects.</p>\n<ul>\n<li>Building key</li>\n<li>Building the dictionary</li>\n</ul>\n</li>\n<li><p>You should really use some functions.</p>\n</li>\n<li><p>You should really follow PEP 8. Your code is really hard to read because it looks like a block of characters, rather than a Python program.</p>\n</li>\n</ol>\n<h1>Functional changes</h1>\n<ol start=\"6\">\n<li>\n<blockquote>\n<p>A trajectory is defined as a list of numbers separated by <code>_</code>.</p>\n</blockquote>\n<p>You should make it a tuple of numbers, <code>(3, 7, 2, 5)</code>.</p>\n</li>\n<li>\n<blockquote>\n<p>I also save the trajectories in separated dictionaries if they have different numbers of steps.</p>\n</blockquote>\n<p>I see no reason to do this.</p>\n</li>\n<li><p>You may benefit from using <a href=\"https://en.wikipedia.org/wiki/Trie\" rel=\"nofollow noreferrer\">a trie</a> instead.</p>\n<p>Since you're just printing the new dictionaries it doesn't make much sense.\nHowever it looks exactly like what you want datatype wise.</p>\n<p>I have included a <code>build</code> and an <code>as_dict</code> method to make understanding how it works a little simpler. You can easily remove the need for <code>build</code> by using it to build the trie directly from <code>generate_keys</code>.</p>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>from __future__ import print_function\nimport random\n\n\ndef generate_keys(amount, choices):\n for _ in range(amount):\n yield tuple(\n random.choice(choices[i])\n for i in range(random.randint(1, len(choices)))\n )\n\n\nclass Trie(dict):\n value = DEFAULT = object()\n\n @classmethod\n def build(cls, mapping):\n trie = cls()\n for keys, value in mapping.items():\n node = trie\n for key in keys:\n node = node.setdefault(key, cls())\n node.value = value\n return trie\n\n def _as_dict(self, path):\n for key, value in self.items():\n keys = path + (key,)\n if value.value is not self.DEFAULT:\n yield keys, value.value\n for item in value._as_dict(keys):\n yield item\n\n def as_dict(self):\n return dict(self._as_dict(()))\n\n\npaths = {}\nfor key in generate_keys(20, [range(3), range(4), range(5)]):\n paths[key] = random.randrange(10)\n\ntrie = Trie.build(paths)\npaths_new = trie[1].as_dict()\n\n# Sort the output so it's easier to read\nprint('Initial dictionary =', dict(sorted(paths.items())))\nprint('Inital Trie =', trie)\nprint('Updated dictionaries =', dict(sorted(paths_new.items())))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T22:31:16.553",
"Id": "480366",
"Score": "0",
"body": "TY. When I try to run your code, it returns the following error\n\n`yield from value._as_dict(keys)\n ^\nSyntaxError: invalid syntax\n `"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T07:31:58.680",
"Id": "480394",
"Score": "1",
"body": "@3sm1r Ah yes, I forgot that's not in Python 2. I have changed to a Python 2 version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T01:33:16.643",
"Id": "481007",
"Score": "0",
"body": "Very nice. \nWhen you write `class Trie(dict):`, does it serve to be able to give all the properties of dictionaries to the instances of the class?\nAlso, what is the use of `value = DEFAULT = object()` ? What does `object()` do and why are you writing `DEFAULT` like that ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T03:46:18.793",
"Id": "481011",
"Score": "0",
"body": "^ the first question of my previous comment was just about why you need to write `class Trie(dict):` instead of just `class Trie:`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T08:50:47.837",
"Id": "481021",
"Score": "1",
"body": "@3sm1r \"why you need to write\" where would `node.setdefault`, `self.items` and `trie[1]` come from? If you're happy to write your own version of each of these functions then you can just use `class Trie(object):` since you're in Python 2. `DEFAULT` is a constant and is following [PEP 8](https://www.python.org/dev/peps/pep-0008/#naming-conventions). `object()` makes an empty object, which is used here `value.value is not self.DEFAULT`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T17:03:49.610",
"Id": "481055",
"Score": "0",
"body": "Good. \nHere you created a dictionary first and then you used the `build` function for the trie.\nIf I'd like to add new paths to the trie directly, I will need to create a method in the `Trie` class that is used to associate a value to a particular node, correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T17:16:00.537",
"Id": "481060",
"Score": "0",
"body": "@3sm1r I do not understand the question. But no you probably can just use the above code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T17:42:03.647",
"Id": "481066",
"Score": "0",
"body": "Suppose I already created a trie and I want to specifically assign the value `5` to the node `(1,2,3)` and suppose that node `(1,2,3)` has never been explored before, so it's an expansion of the existing `trie`. How can I update the `trie` without creating the dictionary first and then using the `build` function, but just using a method, something like `trie.update(new_node,value)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T17:48:15.677",
"Id": "481067",
"Score": "0",
"body": "@3sm1r the code shows you how you can do that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T17:59:11.820",
"Id": "481071",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/110210/discussion-between-3sm1r-and-peilonrayz)."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T13:43:45.090",
"Id": "244660",
"ParentId": "244623",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244660",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T17:01:19.637",
"Id": "244623",
"Score": "2",
"Tags": [
"python",
"python-2.x",
"hash-map"
],
"Title": "Updating a dictionary of trajectories after a step has been made"
}
|
244623
|
<p>I want to preface this by saying I didn't quite know where to put this because this isn't quite a stack overflow question. <strong>So if this is the wrong place to post, please let me know, and please let me know where I could post this type of question.</strong></p>
<p>I recently wrote a program with various functions doing a different thing, however each function was ~100-200 lines long. And since I didn't want to make global parameters, many lines in one function repeated in the other (I redefined the same variables if the user chose to run a different function).</p>
<p>I found my code very difficult to debug, and the general feedback was because it was formatted very poorly, and I should split my code up into multiple functions. However when I tried to look into what should be included in functions, how are they split, etc. It was a bit more vague and unclear.</p>
<p>So I've taken an excerpt from my program and split it into various functions. It gives the proper output as the other program.</p>
<p>The below script basically takes an input (sparta-pred.tab), extracts certain parameters, and modifies it based on user input (seq.txt, mutation_list).</p>
<p>This is the original:</p>
<pre><code>import re
def fun():
seq_start=1
amino_acid_count=(0+seq_start)-1
sequence_list=[]
with open('seq.txt') as sequence_file:
for amino_acid in sequence_file:
stripped_amino_acid=amino_acid.strip().upper()
for word in stripped_amino_acid:
amino_acid_count+=1
sequence_list.append(str(amino_acid_count)+word)
y=0
sparta_file_list1=[]
sparta_file_list2=[]
proline_counter=0
with open('sparta_pred.tab') as sparta_predictions:
for line in sparta_predictions:
modifier=line.strip().upper()
if re.findall('^\d+',modifier):
A=modifier.split()
del A[5:8]
del A[3]
A[0:3]=["".join(A[0:3])]
joined=" ".join(A)
proline_searcher=re.search('\BP',joined)
if proline_searcher != None:
proline_counter+=1
if proline_counter<2:
proline_count=re.search('^\d+',joined)
sparta_file_list1.append(f'{proline_count.group(0)}PN'+' 1000'+' 1000')
sparta_file_list1.append(joined)
if proline_searcher != None:
y+=1
if y==4:
proline_count=re.search('^\d+',joined)
sparta_file_list1.append(f'{proline_count.group(0)}PHN'+' 1000'+' 1000')
y=0
proline_counter=0
mutation_list1=['133R']
mutation_list2=['133A']
if mutation_list1==() or mutation_list2==():
for amino_acids in sparta_file_list1:
sparta_file_list2.append(amino_acids)
else:
for mutations,mutations2 in zip(mutation_list1,mutation_list2):
for amino_acids in sparta_file_list1:
if re.findall(mutations,amino_acids):
splitting=amino_acids.split()
mutation=re.sub(mutations,mutations2,splitting[0])
mutation_value=re.sub('\d+.\d+',' 1000',splitting[1])
mutation_value2=re.sub('\d+.\d+',' 1000',splitting[2])
mutation_replacement=mutation+mutation_value+mutation_value2
sparta_file_list2.append(mutation_replacement)
else:
sparta_file_list2.append(amino_acids)
sparta_file_list3=[]
for aa in sparta_file_list2:
modifiers=aa.strip()
splitter=modifiers.split()
searcher=re.search('^\d+[A-Z]',splitter[0])
compiler=re.compile(searcher.group(0))
sparta_sequence_comparison=list(filter(compiler.match,sequence_list))
if sparta_sequence_comparison != []:
sparta_file_list3.append(aa)
temp_list=[]
temp_counter=0
for checker in sparta_file_list3:
temp_modifier=checker.strip()
temp_split=temp_modifier.split()
temp_finder=re.search('^\d+',temp_split[0])
temp_list.append(temp_finder.group(0))
temp_counter+=1
if temp_counter==5:
if int(temp_finder.group(0))==int(temp_list[0]):
break
else:
del sparta_file_list3[0:4]
break
if len(sparta_file_list3)%6 != 0:
del sparta_file_list3[-5:-1]
</code></pre>
<p>That entire thing is under one function in my original program (the same lines are copy/pasted into other functions that use the same files as well). This is my attempt to split the above into functions:</p>
<pre><code>import re
def create_seq_list():
seq_start=1
amino_acid_count=(0+seq_start)-1
sequence_list=[]
with open('seq.txt') as sequence_file:
for amino_acid in sequence_file:
stripped_amino_acid=amino_acid.strip().upper()
for word in stripped_amino_acid:
amino_acid_count+=1
sequence_list.append(str(amino_acid_count)+word)
return sequence_list
def sparta_formater():
y=0
sparta_file_list1=[]
proline_counter=0
with open('sparta_pred.tab') as sparta_predictions:
for line in sparta_predictions:
modifier=line.strip().upper()
if re.findall('^\d+',modifier):
A=modifier.split()
del A[5:8]
del A[3]
A[0:3]=["".join(A[0:3])]
joined=" ".join(A)
proline_searcher=re.search('\BP',joined)
if proline_searcher != None:
proline_counter+=1
if proline_counter<2:
proline_count=re.search('^\d+',joined)
sparta_file_list1.append(f'{proline_count.group(0)}PN'+' 1000'+' 1000')
sparta_file_list1.append(joined)
if proline_searcher != None:
y+=1
if y==4:
proline_count=re.search('^\d+',joined)
sparta_file_list1.append(f'{proline_count.group(0)}PHN'+' 1000'+' 1000')
y=0
proline_counter=0
return sparta_file_list1
def mutation_adder():
sparta_file_list2=[]
mutation_list1=['133R']
mutation_list2=['133A']
if mutation_list1==() or mutation_list2==():
for amino_acids in sparta_formater():
sparta_file_list2.append(amino_acids)
else:
for mutations,mutations2 in zip(mutation_list1,mutation_list2):
for amino_acids in sparta_formater():
if re.findall(mutations,amino_acids):
splitting=amino_acids.split()
mutation=re.sub(mutations,mutations2,splitting[0])
mutation_value=re.sub('\d+.\d+',' 1000',splitting[1])
mutation_value2=re.sub('\d+.\d+',' 1000',splitting[2])
mutation_replacement=mutation+mutation_value+mutation_value2
sparta_file_list2.append(mutation_replacement)
else:
sparta_file_list2.append(amino_acids)
return sparta_file_list2
def sparta_sequence_filter():
sparta_file_list3=[]
sparta_comparison=create_seq_list()
for aa in mutation_adder():
modifiers=aa.strip()
splitter=modifiers.split()
searcher=re.search('^\d+[A-Z]',splitter[0])
compiler=re.compile(searcher.group(0))
sparta_sequence_comparison=list(filter(compiler.match,sparta_comparison))
if sparta_sequence_comparison != []:
sparta_file_list3.append(aa)
return sparta_file_list3
def sparta_bounds_check():
temp_list=[]
temp_counter=0
sparta_filtered_list=sparta_sequence_filter()
for checker in sparta_filtered_list:
temp_modifier=checker.strip()
temp_split=temp_modifier.split()
temp_finder=re.search('^\d+',temp_split[0])
temp_list.append(temp_finder.group(0))
temp_counter+=1
if temp_counter==5:
if int(temp_finder.group(0))==int(temp_list[0]):
break
else:
del sparta_filtered_list[0:4]
break
if len(sparta_filtered_list)%6 != 0:
del sparta_filtered_list[-5:-1]
return sparta_filtered_list
</code></pre>
<p>As a minimal example to run the above (if anyone wanted to test it:</p>
<pre><code>#seq.txt
MSYQVLARKW
#sparta_pred.tab
3 Y HA 0.000 4.561 4.550 0.018 0.000 0.201
3 Y C 0.000 175.913 175.900 0.021 0.000 1.272
3 Y CA 0.000 58.110 58.100 0.017 0.000 1.940
3 Y CB 0.000 38.467 38.460 0.011 0.000 1.050
4 Q N 3.399 123.306 119.800 0.179 0.000 2.598
4 Q HA 0.146 4.510 4.340 0.039 0.000 0.237
4 Q C -2.091 173.967 176.000 0.097 0.000 0.914
4 Q CA -0.234 55.623 55.803 0.092 0.000 1.065
4 Q CB 3.207 32.000 28.738 0.092 0.000 1.586
4 Q HN 0.131 8.504 8.270 0.173 0.000 0.484
5 V N 0.131 120.091 119.914 0.078 0.000 2.398
5 V HA 0.407 4.575 4.120 0.080 0.000 0.286
5 V C 0.162 176.322 176.094 0.109 0.000 1.026
5 V CA -1.507 60.840 62.300 0.078 0.000 0.868
5 V CB 0.770 32.625 31.823 0.052 0.000 0.982
5 V HN 0.418 8.642 8.190 0.057 0.000 0.443
6 L N 7.083 128.385 121.223 0.130 0.000 2.123
6 L HA -0.504 4.085 4.340 0.415 0.000 0.217
6 L C 1.827 178.814 176.870 0.195 0.000 1.081
6 L CA 3.308 58.271 54.840 0.205 0.000 0.772
6 L CB -1.005 41.051 42.059 -0.005 0.000 0.890
6 L HN 0.241 8.694 8.230 0.097 -0.164 0.437
7 A N -4.063 118.812 122.820 0.092 0.000 2.131
7 A HA -0.337 4.023 4.320 0.067 0.000 0.220
7 A C 0.433 178.071 177.584 0.090 0.000 1.158
7 A CA 2.471 54.552 52.037 0.073 0.000 0.665
7 A CB -0.332 18.690 19.000 0.036 0.000 0.795
7 A HN -0.517 7.889 8.150 0.063 -0.219 0.460
8 R N -4.310 116.247 120.500 0.096 0.000 2.191
8 R HA -0.056 4.313 4.340 0.048 0.000 0.196
8 R C 2.152 178.488 176.300 0.060 0.000 0.991
8 R CA 1.349 57.485 56.100 0.060 0.000 1.075
8 R CB 0.834 31.147 30.300 0.023 0.000 1.040
8 R HN 0.244 8.408 8.270 0.109 0.172 0.526
9 K N 0.144 120.608 120.400 0.108 0.000 2.283
9 K HA -0.130 4.148 4.320 -0.069 0.000 0.202
9 K C 0.691 177.214 176.600 -0.129 0.000 1.048
9 K CA 2.415 58.707 56.287 0.008 0.000 0.948
9 K CB -0.114 32.430 32.500 0.074 0.000 0.742
9 K HN -0.617 7.728 8.250 0.159 0.000 0.458
10 W N -4.007 117.283 121.300 -0.016 0.000 2.846
10 W HA 0.195 4.850 4.660 -0.009 0.000 0.391
10 W C -1.455 175.056 176.519 -0.013 0.000 1.011
10 W CA -1.148 56.191 57.345 -0.011 0.000 1.832
10 W CB 0.166 29.622 29.460 -0.007 0.000 1.151
10 W HN -0.634 7.728 8.180 0.377 0.045 0.582
11 R N 1.894 122.475 120.500 0.134 0.000 2.483
11 R HA -0.096 4.293 4.340 0.083 0.000 0.329
11 R C -1.368 174.959 176.300 0.045 0.000 0.961
11 R CA -0.713 55.431 56.100 0.073 0.000 1.041
11 R CB 0.187 30.506 30.300 0.033 0.000 0.930
11 R HN -0.880 7.272 8.270 0.107 0.182 0.413
12 P HA -0.173 4.278 4.420 0.051 0.000 0.257
12 P C -1.027 176.281 177.300 0.014 0.000 1.162
12 P CA 0.741 63.865 63.100 0.040 0.000 0.762
12 P CB 0.046 31.768 31.700 0.036 0.000 0.753
13 Q N 1.152 120.951 119.800 -0.001 0.000 2.396
13 Q HA 0.193 4.514 4.340 -0.032 0.000 0.220
13 Q C 0.275 176.261 176.000 -0.024 0.000 0.900
13 Q CA 0.394 56.181 55.803 -0.027 0.000 0.925
13 Q CB 2.516 31.223 28.738 -0.051 0.000 1.065
13 Q HN 0.012 8.472 8.270 0.002 -0.188 0.535
</code></pre>
<p>Both scripts should give identical outputs.</p>
<p>The full code is on github:
<a href="https://github.com/sam-mahdi/Peaklist_Assignment_Library-PAL-/blob/master/AVS/AVS.py" rel="nofollow noreferrer">https://github.com/sam-mahdi/Peaklist_Assignment_Library-PAL-/blob/master/AVS/AVS.py</a></p>
<p>However, all I am currently looking at in the above is whether I've got the right idea in terms of splitting my code into functions and proper formatting.</p>
|
[] |
[
{
"body": "<p>At first glance, here are the few things I saw that need to be fixed:</p>\n<ol>\n<li>Your functions seem pretty long, and this possibly leads to violation of single responsibility principle. Make sure each of them does only a single job.</li>\n<li>There are many <code>magic numbers</code> (such as using 0:3, 0:4 while slicing arrays). Same applies to your strings too. As someone who reads your code, I do not understand how/why you used them. Obviously, this is because such usages decrease understandability of your code. Defining constant variables might be needed.</li>\n<li>Your variable names are not descriptive enough. Avoid using names such as <code>aa</code>, <code>temp</code> etc.</li>\n<li>Name your functions by verbs not by nouns. For example, instead of <code>sparta_formater</code> use <code>format_sparta</code>.</li>\n<li>Divide your program into modules. Do not write everything in a single file, separate them according to what they do.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T21:12:46.893",
"Id": "480264",
"Score": "0",
"body": "So the functions need to be split even further? Each function is only 1 loop and is doing only one thing. 2. So should I define the slice? I.E. chemical_shifts=A[3] then del chemical_shifts. 3. It was difficult to come up with names prior since I had so much under 1 fun and was running out of names to use, but I can repeat names now that they're split into different functions. 5. Do you mean write separate files and simply import them into my main file loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T07:39:39.957",
"Id": "480395",
"Score": "1",
"body": "Even your functions is only 1 loop, they seem to be doing many things. What I mean by \"single responsibility\" is that you should have separate functions for parsing the lists or taking inputs etc. By doing so, you can also reduce duplicate code which I believe another problem in your code (for example: `proline_count=re.search('^\\d+',joined)` line is repeated 4 times and that is a smell in code). About your magic numbers (or strings), I recommend to define constant variables. For 5, yes divide your problem into smaller problems and try to solve each in another module (or simply file)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T13:34:59.230",
"Id": "480422",
"Score": "0",
"body": "Regarding splitting it into different files and importing them as modules. I tried this, but this significantly slowed down my program (10x slower)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T15:34:07.197",
"Id": "480428",
"Score": "1",
"body": "In normal circumstances, I don't expect importing modules to cause any performance drop. However, if you imported them in a function that you make calls repeatedly, this could be the reason. https://stackoverflow.com/a/18463100/10054375 This answer might be helpful in this case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T15:58:45.487",
"Id": "480432",
"Score": "1",
"body": "Oh I see. Yes I was calling my function within a loop. I presume redefining the output of my imported value (i.e. some variable=called function), and then looping through that will resolve this (so it doesn't loop through my entire 2nd script)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T17:42:02.120",
"Id": "480474",
"Score": "0",
"body": "One additional comment regarding importing modules. My other files still need to import other modules to work at times (i.e. import re, import os, import numpy,etc.). Won't these additional imports slow down the program?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T20:11:24.757",
"Id": "244634",
"ParentId": "244629",
"Score": "5"
}
},
{
"body": "<p>I think you are trying to reinvent the wheel.\nThis task can be easily achieved with <a href=\"https://pandas.pydata.org/pandas-docs/stable\" rel=\"nofollow noreferrer\">Pandas</a>.\nUsing Pandas should come with a few benefits:</p>\n<ul>\n<li>it will make your code more precise,</li>\n<li>it will reduce its length, and</li>\n<li>it will increase the readability. Which will make the reviewers give more attention to your code.</li>\n</ul>\n<p>After <a href=\"https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html\" rel=\"nofollow noreferrer\">installing Pandas</a> you can use the <code>pandas.read_table</code> function to get going.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T13:22:38.833",
"Id": "480315",
"Score": "0",
"body": "I'v tried doing the exact thing in Pandas before, but came across a variety of shortcomings in what I wanted to achieve (especially when it came trying to extract and modify data in certain ways using series). Additionally, I wanted to write this in pure python, so it doesn't require any dependancies (e.g. pandas)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T13:25:49.760",
"Id": "480316",
"Score": "1",
"body": "Can you please elaborate on like what problems did you face?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T13:31:19.290",
"Id": "480318",
"Score": "0",
"body": "This was one such example: https://stackoverflow.com/questions/58868516/formatting-issues-using-regex-and-pandas . However even trying use series I found it difficult to insert values (you may index, but this is designed to work with multiple formats, so the index could always be diff.). NOTE: The script I have posted above (in this post) is a small part of a much larger program. So the link I just posted is to a question of another part of this program (just in case there was any confusion in why they are discussing 2 different things)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T13:42:20.117",
"Id": "480319",
"Score": "0",
"body": "Sorry, I 'm not used to understand such big posts. I 'm loading your file in my jupyter notebook. Can you guide me through the steps so that I can see the error?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T13:45:31.210",
"Id": "480320",
"Score": "0",
"body": "I understood by your StackOverflow question that you were trying to use regex to search in some column and the search was giving you errors. Was it the problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T13:56:38.920",
"Id": "480321",
"Score": "0",
"body": "The issue was with how pandas uses strings. If you convert your data into strings so you can use regex with it, it only displayes the first and last 5 rows. As for the above post, I'm just looking at whether I split up my code into functions properly (i.e. is this the proper format). So there is no error (unless you mean the code from the link I sent you, in which case I don't have that anymore, that post is from a while ago)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T14:01:29.330",
"Id": "480322",
"Score": "0",
"body": "Let's try some tweaks, How about this, pd.read_table..., dtype=str, keep_default_na=False)?Have you used this before?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T14:04:18.633",
"Id": "480323",
"Score": "1",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/109959/discussion-between-samman-and-vishesh-mangla)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T14:04:48.913",
"Id": "480324",
"Score": "0",
"body": "I can try to make your code better but that would definitely not be the best practice in this situation. Pandas while reading implicitly converts datatype and that creates an issue often. Using dtype=str, all fields are read as strings. I can't guarantee but this can solve the issue. Once the columns are read as str you can explicitly convert the datatypes to what you want."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T06:37:44.137",
"Id": "244653",
"ParentId": "244629",
"Score": "3"
}
},
{
"body": "<h2>Function naming</h2>\n<p>As @OnurArı suggested, your naming needs work. In particular, this:</p>\n<pre><code>def fun(): \n</code></pre>\n<p>is probably worse than having no function at all, so it's good that you attempted to split it up.</p>\n<p>Some nuance to the other answer: yes, <code>mutation_adder</code> should be <code>add_mutation</code> (imperative-tense verb) as a function. Where you <em>would</em> see <code>MutationAdder</code> (noun) is if it's a class name.</p>\n<h2>List formation</h2>\n<pre><code>mutation_list1=['133R']\nmutation_list2=['133A']\nif mutation_list1==() or mutation_list2==():\n for amino_acids in sparta_formater():\n sparta_file_list2.append(amino_acids)\n</code></pre>\n<p>doesn't make a huge amount of sense. Neither of those conditions will ever be true, because you just populated the lists manually. Even if the lists "might" be empty, you should be comparing them to empty lists <code>[]</code> instead of empty tuples <code>()</code>.</p>\n<p>Further, you don't need that <code>for</code>. Since <code>sparta_formater</code> returns an iterable, you could simply</p>\n<pre><code>sparta_file_list2.extend(sparta_formater())\n</code></pre>\n<p>Finally, don't call variables <code>list1</code> and <code>list2</code>. The numbers hide the actual intent of the variable, and it's not really even useful to call something a <code>list</code> - it's more informative to add a type hint and pluralize the variable name, i.e.</p>\n<pre><code>mutations: List[str] = ['133R']\n</code></pre>\n<h2>Regexes</h2>\n<p>This:</p>\n<pre><code> compiler=re.compile(searcher.group(0))\n</code></pre>\n<p>is not a compiler. <code>re.compile</code>, the function, is technically the compiler, but what you get out of it is a regular expression object. Don't call <code>compile</code> within a loop - the whole purpose that <code>compile</code> exists is to pay the cost of compilation once up front, outside of the loop, so that using it within the loop is faster.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T16:18:55.877",
"Id": "480434",
"Score": "1",
"body": "Thank you for the feedback. Only one thing to comment, for mutation_list, this is only an excerpt of a much larger script that uses GUI inputs. In some cases mutation_list will be empty, in others it won't. However, when splitting them up, I had to redefine mutation_list so it would work in my test case. That's why I have that if mutation_list is empty (because it might be in some cases)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T16:25:08.550",
"Id": "480436",
"Score": "1",
"body": "That's fine, though - when eliding code for the purposes of a review, it's very important to show something like `# elided for review brevity` to make it more obvious where things are missing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T16:33:20.013",
"Id": "480443",
"Score": "1",
"body": "Yeah, thank you! This is my first time writing a biggerish program, and while I think I have a decent grasp now on writing code (at least the basics), I am completely unfamiliar with, I believe it might be software design? Basically I can write the script, but I have no idea how to format it or structure it so it isn't just one long massive file. Thus, trying to learn how to use functions, naming terminology, learning how to comment, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T16:34:01.953",
"Id": "480444",
"Score": "1",
"body": "You're in the right place :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T08:30:44.840",
"Id": "480572",
"Score": "0",
"body": "@Reinderen Can their code be improved by my deleted post? https://codereview.stackexchange.com/a/244694/226167 ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T08:34:41.040",
"Id": "480573",
"Score": "0",
"body": "Here in this line in first `with`'s last line `sequence_list.append(str(amino_acid_count)+word)` , I think they are trying to get \"1 M\", \"2 P\", \"9 S\" and so on which is what dicts are for and collections.Counter might be what they want. I 'm not sure of this though."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T16:04:01.627",
"Id": "244720",
"ParentId": "244629",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T18:22:37.720",
"Id": "244629",
"Score": "1",
"Tags": [
"python",
"file-system"
],
"Title": "amino acid data prediction"
}
|
244629
|
<p>I have written this code for depth first tree traversals.
It feels like a lot of boilerplate, and I want to refactor it to remove this boilerplate.
However I haven't done a lot of refactoring before, and I don't really know where to start.</p>
<p>The code mostly consists of:</p>
<ul>
<li><p>Three interfaces</p>
<ul>
<li><code>Node</code>, which defines two methods returning the left or right child of a node.</li>
<li><code>TreeTraverser</code>, which is simply an <code>Iterator</code> for <code>Node</code> implementing classes.</li>
<li><code>TraversalStateIncrementer</code>, which defines two methods, <code>inital()</code> which returns an enum signifying the first <code>Node</code> to handle in an order (such as <code>LEFT</code>, <code>RIGHT</code>, <code>SELF</code>, mirroring the order of function calls in a recursive implementation)</li>
</ul>
</li>
<li><p>One <code>enum</code></p>
<ul>
<li><code>TraversalState</code>: <code>LEFT</code>, <code>RIGHT</code>, <code>SELF</code>, or <code>POP</code>. See <code>TraversalStateIncrementer</code>. The <code>POP</code> is used to signify that a <code>Node</code> should be popped off the stack (an internal node stack in the <code>abstract class</code>)</li>
</ul>
</li>
<li><p>One <code>abstract class</code> with a <code>private static inner class</code></p>
<ul>
<li><code>AbstractOrderTreeTraverser</code> which implements all boilerplate except the order of traversal, which is provided by an injected <code>TraversalStateIncrementer</code>.</li>
</ul>
</li>
</ul>
<p><code>Node.java</code></p>
<pre><code>package dev.nylander.util.tree;
import java.util.Optional;
public interface Node<NODE extends Node<NODE>> {
Optional<NODE> getLeft();
Optional<NODE> getRight();
}
</code></pre>
<p><code>TreeTraverser.java</code></p>
<pre><code>package dev.nylander.util.tree;
import java.util.Iterator;
public interface TreeTraverser<NODE extends Node<NODE>> extends Iterator<NODE> {
}
</code></pre>
<p><code>TraversalStateIncrementer.java</code></p>
<pre><code>package dev.nylander.util.tree;
interface TraversalStateIncrementer {
TraversalState initial();
TraversalState increment(TraversalState state);
}
</code></pre>
<p><code>TraversalState.java</code></p>
<pre><code>package dev.nylander.util.tree;
enum TraversalState {
RIGHT, LEFT, SELF, POP
}
</code></pre>
<p><code>AbstractOrderTreeTraverser.java</code><br />
Here's where the "magic" happens.</p>
<pre><code>package dev.nylander.util.tree;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Stack;
abstract class AbstractOrderTreeTraverser<NODE extends Node<NODE>> implements TreeTraverser<NODE> {
private final TraversalStateIncrementer incrementer;
private final NODE root;
private final Stack<NodeStatePair<NODE>> traversalStack = new Stack<>();
private NODE next = null;
public AbstractOrderTreeTraverser(NODE root, TraversalStateIncrementer incrementer) {
this.root = root;
this.incrementer = incrementer;
setupStack();
}
@Override
public final boolean hasNext() {
traverseUntilNext();
return next != null;
}
@Override
public final NODE next() {
traverseUntilNext();
if (next == null)
throw new NoSuchElementException();
return popNext();
}
private void setupStack() {
traversalStack.push(newNodeStatePair(root));
}
private NodeStatePair<NODE> newNodeStatePair(NODE node) {
return new NodeStatePair<>(node, incrementer.initial());
}
private void traverseUntilNext() {
while (next == null && !traversalStack.isEmpty()) {
NodeStatePair<NODE> current = traversalStack.peek();
TraversalState currentState = current.state();
current.setState(incrementer.increment(currentState));
handleState(currentState);
}
}
private void handleState(TraversalState state) {
NodeStatePair<NODE> current = traversalStack.peek();
switch (state) {
case LEFT:
Optional<NODE> optionalLeft = current.node().getLeft();
pushAsNodeStatePair(optionalLeft);
break;
case RIGHT:
Optional<NODE> optionalRight = current.node().getRight();
pushAsNodeStatePair(optionalRight);
break;
case SELF:
next = current.node();
break;
case POP:
traversalStack.pop();
break;
}
}
private void pushAsNodeStatePair(Optional<NODE> possibleNode) {
possibleNode.ifPresent(node -> traversalStack.push(newNodeStatePair(node)));
}
private NODE popNext() {
NODE poppedNext = next;
next = null;
return poppedNext;
}
private static class NodeStatePair<NODE extends Node<NODE>> {
private final NODE node;
private TraversalState state;
NodeStatePair(NODE node, TraversalState initialState) {
this.node = node;
this.state = initialState;
}
public void setState(TraversalState state) {
this.state = state;
}
public TraversalState state() {
return state;
}
public NODE node() {
return node;
}
}
}
</code></pre>
<p>How should I go about refactoring this code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T15:12:55.507",
"Id": "480328",
"Score": "2",
"body": "Have you considered implementing the tree traversal as a stream? It would simplify traversal state management and allow for trivial parallelization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T17:54:33.380",
"Id": "480350",
"Score": "0",
"body": "@TorbenPutkonen while I am familiar with the convenience of streams, I am not familiar with their implementation. I will look into the docs and see what I can do. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T15:36:51.923",
"Id": "481480",
"Score": "1",
"body": "See [Spliterator](https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T18:52:59.700",
"Id": "244630",
"Score": "3",
"Tags": [
"java"
],
"Title": "Traversing a binary tree using a Node interface and an abstract Traverser class using a strategy pattern for order"
}
|
244630
|
<p>I'd like to know if this code is usable, because I'm not sure, thank you. The code is used to upload images to a predefined folder for users.</p>
<pre><code>if(isset($_FILES['avatar']) AND !empty($_FILES['avatar']['name'])) {
$tailleMax = 6844685465456456;
$extensionsValides = array('jpg', 'jpeg', 'gif', 'png');
if($_FILES['avatar']['size'] <= $tailleMax) {
$extensionUpload = strtolower(substr(strrchr($_FILES['avatar']['name'], '.'), 1));
if(in_array($extensionUpload, $extensionsValides)) {
$resultat = move_uploaded_file($_FILES['avatar']['tmp_name'], 'uploads/'.$_SESSION['id'].'.'.$extensionUpload);
if($resultat) {
echo "success";
} else {
echo "Erreur durant l'importation de votre photo de profil extension";
}
} else {
echo "Votre photo de profil doit être au format jpg, jpeg, gif ou png";
}
} else {
echo "Votre photo de profil ne doit pas dépasser 2Mo";
}
}else{
echo ':/';
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p><code>if(isset($_FILES['avatar']) AND !empty($_FILES['avatar']['name'])) {</code> can more simply be: <code>if(!empty($_FILES['avatar']['name'])) {</code> because if the latter is <code>true</code>, then the former is <code>true</code> as well.</p>\n</li>\n<li><p><code>$tailleMax</code>, <code>$extensionsValides</code>, <code>$resultat</code> are "single-use variables". In the majority of cases, I prefer not to declare single-use variables because they end up needlessly bloating my scripts. That said, there are times when they are advisable:</p>\n<ol>\n<li>When the value is somewhat mysterious in what it is for.</li>\n<li>When the declaration prevents writing a line of code which is excessively long.<br><br></li>\n</ol>\n<p>If you think you may use the first two variables elsewhere in your project, then it would be sensible to store then in a config file for ease of use and maintenance.</p>\n</li>\n<li><p>There is A LOT of debate on the web about how to best determine the extension / mime type of an imported file and cleanse it of any malicious code. On <a href=\"https://codereview.stackexchange.com/search?q=%5Bphp%5D%20validate%20uploaded%20image%20file\">Code Review</a> and <a href=\"https://security.stackexchange.com/search?q=validate%20upload%20image\">Information Security</a> you may research as much as you like. After spending a couple hours reading heaps of posts all over Stack Exchange about how everything can be spoofed by the user and how using the <code>GD</code> extension to recreate the uploaded image, I'm actually not game enough to post a claim on what is best / most secure. If you merely want the portion of the filename after the latest dot, then there are several ways to isolate that with fewer function calls.</p>\n</li>\n<li><p>As a personal preference, I like to write all of my failing conditions earlier in my script and reserve the successful outcome(s) for the later in the script. I don't know if you need to <code>exit()</code> or <code>return</code> for your script, but using these process ending calls will prevent your script for using "arrow head" tabbing (an antipattern). In other words, this will keep more of your code "left" and require less horizontal scrolling in your IDE.</p>\n</li>\n</ol>\n<p>Here's an untested version of what I am suggesting that assumes that you are doing something like passing a string response back to an ajax call:</p>\n<pre><code>if (empty($_FILES['avatar']['name'])) {\n exit('No importation');\n}\nif ($_FILES['avatar']['size'] > 6844685465456456) {\n exit('Votre photo de profil ne doit pas dépasser 2Mo');\n}\n$extensionUpload = strtolower(pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION));\nif (!in_array($extensionUpload, ['jpg', 'jpeg', 'gif', 'png'])) {\n exit('Votre photo de profil doit être au format jpg, jpeg, gif ou png');\n}\nif (!move_uploaded_file($_FILES['avatar']['tmp_name'], "uploads/{$_SESSION['id']}.{$extensionUpload}")) {\n exit("Erreur durant l'importation de votre photo de profil extension");\n}\nexit('success');\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T17:53:19.690",
"Id": "480349",
"Score": "0",
"body": "Thank's for your message"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T20:05:18.597",
"Id": "480525",
"Score": "0",
"body": "Please never thank in a comment."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T05:14:09.003",
"Id": "244650",
"ParentId": "244632",
"Score": "0"
}
},
{
"body": "<p>Just a few remarks:</p>\n<p>I am wondering how that magic value of 6844685465456456 was determined :) I don't think that is equivalent to 2 Mb.</p>\n<hr />\n<p>You need to use proper <strong>indentation</strong>, especially when you have nested control blocks - readability is important. Lack of readability here can result in a greater likelihood of logic errors.</p>\n<hr />\n<p>This code is <strong>not</strong> helpful at all:</p>\n<pre><code> }else{\n echo ':/';\n }\n</code></pre>\n<p>It doesn't tell the user what the problem is. Don't you hate those forms that tell you 'invalid input, try again' but don't actually tell you the problem and leave you guessing ?</p>\n<hr />\n<p>This code (borrowed from <a href=\"https://codereview.stackexchange.com/a/244650/219060\">mickmackusa</a>):</p>\n<pre><code>if (!move_uploaded_file($_FILES['avatar']['tmp_name'], "uploads/{$_SESSION['id']}.{$extensionUpload}")) {\n exit("Erreur durant l'importation de votre photo de profil extension");\n}\n</code></pre>\n<p>You are showing an error message to the user but it should be treated like an <strong>exception</strong>. This code could fail for several reasons like:</p>\n<ul>\n<li>invalid file name</li>\n<li>disk full/not mounted</li>\n<li>etc</li>\n</ul>\n<p>But at this point it's not the user fault. It's a malfunction in your application or a server issue. There is nothing the user can do. So I would handle the exception and send an alert. If your application is broken you'll want to be notified and fix it asap, before someone reaches out to you.</p>\n<hr />\n<p>This code is not foolproof:</p>\n<pre><code>$resultat = move_uploaded_file($_FILES['avatar']['tmp_name'], 'uploads/'.$_SESSION['id'].'.'.$extensionUpload);\n</code></pre>\n<p>You are expecting that the session variable <code>ID</code> will be set. It's perfectly possible that the user has the page opened already and the session expires after some time. When submitting the form the session variable could be unset, unless you have more code elsewhere (an include perhaps) that verifies that the session is active. If there is no active session you'll probably redirect the user to the login page.</p>\n<p>So the resulting file name could be incorrect and not what you expected (eg: <code>.jpg</code>). It could be one reason why <code>move_uploaded_file</code> would fail in your script. In itself it doesn't present an obvious security risk though but it is a bug.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T00:02:44.260",
"Id": "244688",
"ParentId": "244632",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244688",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T19:06:29.770",
"Id": "244632",
"Score": "2",
"Tags": [
"php"
],
"Title": "Is this code is safe or not (img upload) ? [PHP]"
}
|
244632
|
<p>I have updated my my gene sequencing program from my <a href="https://codereview.stackexchange.com/q/244535/226388">previous post</a>.
That post explains what each functions accomplish.
If you need clarifications feel free to ask.</p>
<p>Any tips to make the code more concise or efficient are much appreciated. Are there any functions that you think would be useful?</p>
<p>Here are example <a href="https://www.ncbi.nlm.nih.gov/nuccore/NC_000006.12?report=fasta&from=26156329&to=26157115" rel="nofollow noreferrer">FASTA</a> and <a href="https://www.ncbi.nlm.nih.gov/nuccore/NC_000006.12?report=genbank&from=26156329&to=26157115" rel="nofollow noreferrer">GenBank</a> files, for reference.</p>
<pre><code>import random
import re
from collections import defaultdict
nucleotides = ("A", "C", "G", "T")
rnanucleotides = ("A", "C", "G", "U")
rev_compliment = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'}
RNA_codon_table = {"UUU": "F", "CUU": "L", "AUU": "I", "GUU": "V",
"UUC": "F", "CUC": "L", "AUC": "I", "GUC": "V",
"UUA": "L", "CUA": "L", "AUA": "I", "GUA": "V",
"UUG": "L", "CUG": "L", "AUG": "M", "UCU": "S",
"GUG": "V", "CCU": "P", "ACU": "T", "GCU": "A",
"UCC": "S", "CCC": "P", "ACC": "T", "GCC": "A",
"UCA": "S", "CCA": "P", "ACA": "T", "GCA": "A",
"UCG": "S", "CCG": "P", "ACG": "T", "GCG": "A",
"UAU": "Y", "CAU": "H", "AAU": "N", "GAU": "D",
"UAC": "Y", "CAC": "H", "AAC": "N", "GAC": "D",
"UAA": "_", "CAA": "Q", "AAA": "K", "GAA": "E",
"UAG": "_", "CAG": "Q", "AAG": "K", "GAG": "E",
"UGU": "C", "CGU": "R", "AGU": "S", "GGU": "G",
"UGC": "C", "CGC": "R", "AGC": "S", "GGC": "G",
"UGA": "_", "CGA": "R", "AGA": "R", "GGA": "G",
"UGG": "W", "CGG": "R", "AGG": "R", "GGG": "G"
}
amino_acid_weights = {
"A": 71.03711,
"C": 103.00919,
"D": 115.02694,
"E": 129.04259,
"F": 147.06841,
"G": 57.02146,
"H": 137.05891,
"I": 113.08406,
"K": 128.09496,
"L": 113.08406,
"M": 131.04049,
"N": 114.04293,
"P": 97.05276,
"Q": 128.05858,
"R": 156.10111,
"S": 87.03203,
"T": 101.04768,
"V": 99.06841,
"W": 186.07931,
"Y": 163.06333,
"_": 0,
}
def title_screen():
print("""-. .-. .-. .-. .-. .-. .
||\|||\ /|||\|||\ /|||\|||\ /|
|/ \|||\|||/ \|||\|||/ \|||\||
~ `-~ `-` `-~ `-` `-~ `-""")
print("DNA SEQUENCE ANALYZER by Ethan Hetrick\n")
def user_selection():
response = input("What would you like to do?\n"
"1. Input your own DNA sequence.\n"
"2. Input your own RNA sequence.\n"
"3. Generate random sequence data.\n"
"4. Import a file in FASTA format.\n"
"5. Import a file in GenBank format.\n")
if response == '1':
seq = input("Input your DNA sequence here: \n").upper().strip()
seq = validate_seq(seq)
tag = "Your DNA sequence"
return seq, tag
elif response == '3':
try:
x = int(input("How many nucleotides long do you want your sequence? Enter an integer.\n"))
seq = ''.join([random.choice(nucleotides) for nuc in range(x)])
tag = "Random DNA sequence"
return seq, tag
except ValueError:
print("Invalid response.\n")
run('seq', 'tag')
elif response == '2':
rna = input("Input your RNA sequence here: \n").upper().strip()
rna = validate_seq(rna)
seq = rev_transcription(rna)
tag = "Your RNA sequence"
return seq, tag
elif response == '4':
try:
for i in fasta():
tag = i[0]
seq = i[1]
if "U" in seq:
seq = rev_transcription(seq)
return seq, tag
except FileNotFoundError:
print("\nFile not found. Please input a valid file path.\n")
elif response == '5':
try:
seq, tag = genbank_to_fasta()
return seq, tag
except FileNotFoundError:
print("\nFile not found. Please input a valid file path.\n")
else:
print("Invalid response.\n")
def fasta():
sequences = defaultdict(str)
file = input(r'Input the path to your file: ')
with open(f'{file}') as f:
lines = f.readlines()
current_tag = None
list = []
for line in lines:
m = re.match('^>(.+)', line)
if m:
current_tag = m.group(1)
else:
sequences[current_tag] += line.strip()
for tag, seq in sequences.items():
list.append([tag, seq])
return list
def genbank_to_fasta():
file = input(r'Input the path to your file: ')
with open(f'{file}') as f:
gb = f.readlines()
locus = re.search('NC_\d+\.\d+', gb[3]).group()
region = re.search('(\d+)?\.+(\d+)', gb[2])
definition = re.search('\w.+', gb[1][10:]).group()
definition = definition.replace(definition[-1], "")
tag = locus + ":" + region.group(1) + "-" + region.group(2) + " " + definition
sequence = ""
for line in (gb):
pattern = re.compile('[atgc]{10}')
matches = pattern.finditer(line)
for match in matches:
sequence += match.group().upper()
end_pattern = re.search('[atgc]{1,9}', gb[-3])
sequence += end_pattern.group().upper()
return sequence, tag
def validate_seq(dnaseq):
if len(dnaseq) == 0:
print("Empty sequence.\n")
user_selection()
else:
for nuc in dnaseq:
if nuc not in nucleotides or rnanucleotides:
print("Invalid sequence.\n")
user_selection()
else:
return dnaseq
def nuc_count(dnaseq, tag):
print("\n================================================")
print(f'THE ANALYSIS: >{tag}\n')
if len(dnaseq) >= 1000:
print(f'Total: {len(dnaseq)/1000} kbp\n')
else:
print(f'Total: {len(dnaseq)} bp\n')
print("Nucleotide frequency:")
for letter in nucleotides:
letter_total = dnaseq.count(letter)
letter_per = (letter_total / len(dnaseq))
print(f'{letter}: {letter_total} : {letter_per:%}')
GC = ((dnaseq.count("G") + dnaseq.count("C"))/(len(dnaseq)))
print(f'GC content: {GC:%}')
def rev_transcription(rnaseq):
dnaseq = rnaseq.replace("U", "T")
return dnaseq
def DNA_to_cDNA(dnaseq):
cdna = "".join([rev_compliment[nuc] for nuc in dnaseq])
return cdna
def transcription(dnaseq):
rna = dnaseq.replace("T", "U")
print(f"RNA: 5' {rna} 3'")
return rna
def translation(dnaseq, init_pos=0):
dnaseq = dnaseq.replace("T", "U")
return [RNA_codon_table[dnaseq[pos:pos + 3]] for pos in range(init_pos, len(dnaseq) - 2, 3)]
def gen_reading_frames(dnaseq):
frames = []
frames.append(translation(dnaseq, 0))
frames.append(translation(dnaseq, 1))
frames.append(translation(dnaseq, 2))
frames.append(translation(DNA_to_cDNA(dnaseq)[::-1], 0))
frames.append(translation(DNA_to_cDNA(dnaseq)[::-1], 1))
frames.append(translation(DNA_to_cDNA(dnaseq)[::-1], 2))
return frames
def prot_from_rf(aa_seq):
prot1 = []
proteins = []
for aa in aa_seq:
if aa == "_":
proteins.extend(prot1)
prot1 = []
else:
if aa == "M":
prot1.append("")
for i in range(len(prot1)):
prot1[i] += aa
return proteins
def all_proteins_from_rfs(dnaseq, startReadPos=0, endReadPos=0):
if endReadPos > startReadPos:
rfs = gen_reading_frames(dnaseq[startReadPos: endReadPos])
else:
rfs = gen_reading_frames(dnaseq)
all_proteins = []
for rf in rfs:
prots = prot_from_rf(rf)
for p in prots:
all_proteins.append(p)
return all_proteins
def protein_weight(protein):
weights = (([amino_acid_weights[protein[pos: pos + 1]] for pos in range(0, len(protein))]))
weight = round(sum(weights), 3)
return weight
def printing(seq, frames):
print("\nThe 6 possible reading frames:")
for i, frame in enumerate(frames):
print(f'{i + 1}. {"".join(frame)}')
print("\nAll possible proteins:")
list = []
for prot in all_proteins_from_rfs(seq):
if prot not in list:
list.append(prot)
list.sort(key=len, reverse=True)
for i, prot in enumerate(list):
print(f'{i + 1}. {prot}: {protein_weight(prot)} Da')
print("================================================\n")
def run(seq, tag):
if seq == 'seq' and tag == 'tag':
seq, tag = user_selection()
nuc_count(seq, tag)
cseq = DNA_to_cDNA(seq)
print(f"\nDNA: 5' {seq} 3'")
print(f"cDNA: 3' {cseq} 5'")
transcription(seq)
translation(seq)
all_proteins_from_rfs(seq, startReadPos=0, endReadPos=0)
frames = gen_reading_frames(seq)
printing(seq, frames)
title_screen()
run('seq', 'tag')
</code></pre>
<p>Example output</p>
<pre><code>================================================
THE ANALYSIS: >NC_000006.12:26156329-26157115 Homo sapiens chromosome 6, GRCh38.p13 Primary Assembly
Total: 787 bp
Nucleotide frequency:
A: 221 : 28.081321%
C: 246 : 31.257942%
G: 230 : 29.224905%
T: 90 : 11.435832%
GC content: 60.482846%
DNA: 5' CGAGTCCCGGCCAGTGCCTCTGCTTCCGGCTCGAATTGCTCTCGCTCACGCTTGCCTTCAACATGTCCGAGACTGCGCCTGCCGCGCCCGCTGCTCCGGCCCCTGCCGAGAAGACTCCCGTGAAGAAGAAGGCCCGCAAGTCTGCAGGTGCGGCCAAGCGCAAAGCGTCTGGGCCCCCGGTGTCCGAGCTCATTACTAAAGCTGTTGCCGCCTCCAAGGAGCGCAGCGGCGTATCTTTGGCCGCTCTCAAGAAAGCGCTGGCAGCCGCTGGCTATGACGTGGAGAAGAACAACAGCCGCATCAAGCTGGGTCTCAAGAGCCTGGTGAGCAAGGGCACCCTGGTGCAGACCAAGGGCACCGGCGCGTCGGGTTCCTTCAAACTCAACAAGAAGGCGGCCTCTGGGGAAGCCAAGCCTAAGGCTAAAAAGGCAGGCGCGGCCAAGGCCAAGAAGCCAGCAGGAGCGGCGAAGAAGCCCAAGAAGGCGACGGGGGCGGCCACCCCCAAGAAGAGCGCCAAGAAGACCCCAAAGAAGGCGAAGAAGCCGGCTGCAGCTGCTGGAGCCAAAAAAGCGAAAAGCCCGAAAAAGGCGAAAGCAGCCAAGCCAAAAAAGGCGCCCAAGAGCCCAGCGAAGGCCAAAGCAGTTAAACCCAAGGCGGCTAAACCAAAGACCGCCAAGCCCAAGGCAGCCAAGCCAAAGAAGGCGGCAGCCAAGAAAAAGTAGAAAGTTCCTTTGGCCAACTGCTTAGAAGCCCAACACAACCCAAAGGCTCTTTTCAGAGCCACCCA 3'
cDNA: 3' GCTCAGGGCCGGTCACGGAGACGAAGGCCGAGCTTAACGAGAGCGAGTGCGAACGGAAGTTGTACAGGCTCTGACGCGGACGGCGCGGGCGACGAGGCCGGGGACGGCTCTTCTGAGGGCACTTCTTCTTCCGGGCGTTCAGACGTCCACGCCGGTTCGCGTTTCGCAGACCCGGGGGCCACAGGCTCGAGTAATGATTTCGACAACGGCGGAGGTTCCTCGCGTCGCCGCATAGAAACCGGCGAGAGTTCTTTCGCGACCGTCGGCGACCGATACTGCACCTCTTCTTGTTGTCGGCGTAGTTCGACCCAGAGTTCTCGGACCACTCGTTCCCGTGGGACCACGTCTGGTTCCCGTGGCCGCGCAGCCCAAGGAAGTTTGAGTTGTTCTTCCGCCGGAGACCCCTTCGGTTCGGATTCCGATTTTTCCGTCCGCGCCGGTTCCGGTTCTTCGGTCGTCCTCGCCGCTTCTTCGGGTTCTTCCGCTGCCCCCGCCGGTGGGGGTTCTTCTCGCGGTTCTTCTGGGGTTTCTTCCGCTTCTTCGGCCGACGTCGACGACCTCGGTTTTTTCGCTTTTCGGGCTTTTTCCGCTTTCGTCGGTTCGGTTTTTTCCGCGGGTTCTCGGGTCGCTTCCGGTTTCGTCAATTTGGGTTCCGCCGATTTGGTTTCTGGCGGTTCGGGTTCCGTCGGTTCGGTTTCTTCCGCCGTCGGTTCTTTTTCATCTTTCAAGGAAACCGGTTGACGAATCTTCGGGTTGTGTTGGGTTTCCGAGAAAAGTCTCGGTGGGT 5'
RNA: 5' CGAGUCCCGGCCAGUGCCUCUGCUUCCGGCUCGAAUUGCUCUCGCUCACGCUUGCCUUCAACAUGUCCGAGACUGCGCCUGCCGCGCCCGCUGCUCCGGCCCCUGCCGAGAAGACUCCCGUGAAGAAGAAGGCCCGCAAGUCUGCAGGUGCGGCCAAGCGCAAAGCGUCUGGGCCCCCGGUGUCCGAGCUCAUUACUAAAGCUGUUGCCGCCUCCAAGGAGCGCAGCGGCGUAUCUUUGGCCGCUCUCAAGAAAGCGCUGGCAGCCGCUGGCUAUGACGUGGAGAAGAACAACAGCCGCAUCAAGCUGGGUCUCAAGAGCCUGGUGAGCAAGGGCACCCUGGUGCAGACCAAGGGCACCGGCGCGUCGGGUUCCUUCAAACUCAACAAGAAGGCGGCCUCUGGGGAAGCCAAGCCUAAGGCUAAAAAGGCAGGCGCGGCCAAGGCCAAGAAGCCAGCAGGAGCGGCGAAGAAGCCCAAGAAGGCGACGGGGGCGGCCACCCCCAAGAAGAGCGCCAAGAAGACCCCAAAGAAGGCGAAGAAGCCGGCUGCAGCUGCUGGAGCCAAAAAAGCGAAAAGCCCGAAAAAGGCGAAAGCAGCCAAGCCAAAAAAGGCGCCCAAGAGCCCAGCGAAGGCCAAAGCAGUUAAACCCAAGGCGGCUAAACCAAAGACCGCCAAGCCCAAGGCAGCCAAGCCAAAGAAGGCGGCAGCCAAGAAAAAGUAGAAAGUUCCUUUGGCCAACUGCUUAGAAGCCCAACACAACCCAAAGGCUCUUUUCAGAGCCACCCA 3'
The 6 possible reading frames:
1. RVPASASASGSNCSRSRLPSTCPRLRLPRPLLRPLPRRLP_RRRPASLQVRPSAKRLGPRCPSSLLKLLPPPRSAAAYLWPLSRKRWQPLAMTWRRTTAASSWVSRAW_ARAPWCRPRAPARRVPSNSTRRRPLGKPSLRLKRQARPRPRSQQERRRSPRRRRGRPPPRRAPRRPQRRRRSRLQLLEPKKRKARKRRKQPSQKRRPRAQRRPKQLNPRRLNQRPPSPRQPSQRRRQPRKSRKFLWPTA_KPNTTQRLFSEPP
2. ESRPVPLLPARIALAHACLQHVRDCACRARCSGPCREDSREEEGPQVCRCGQAQSVWAPGVRAHY_SCCRLQGAQRRIFGRSQESAGSRWL_RGEEQQPHQAGSQEPGEQGHPGADQGHRRVGFLQTQQEGGLWGSQA_G_KGRRGQGQEASRSGEEAQEGDGGGHPQEERQEDPKEGEEAGCSCWSQKSEKPEKGESSQAKKGAQEPSEGQSS_TQGG_TKDRQAQGSQAKEGGSQEKVESSFGQLLRSPTQPKGSFQSHP
3. SPGQCLCFRLELLSLTLAFNMSETAPAAPAAPAPAEKTPVKKKARKSAGAAKRKASGPPVSELITKAVAASKERSGVSLAALKKALAAAGYDVEKNNSRIKLGLKSLVSKGTLVQTKGTGASGSFKLNKKAASGEAKPKAKKAGAAKAKKPAGAAKKPKKATGAATPKKSAKKTPKKAKKPAAAAGAKKAKSPKKAKAAKPKKAPKSPAKAKAVKPKAAKPKTAKPKAAKPKKAAAKKK_KVPLANCLEAQHNPKALFRAT
4. WVALKRAFGLCWASKQLAKGTFYFFLAAAFFGLAALGLAVFGLAALGLTALAFAGLLGAFFGLAAFAFFGLFAFLAPAAAAGFFAFFGVFLALFLGVAAPVAFLGFFAAPAGFLALAAPAFLALGLASPEAAFLLSLKEPDAPVPLVCTRVPLLTRLLRPSLMRLLFFSTS_PAAASAFLRAAKDTPLRSLEAATALVMSSDTGGPDALRLAAPADLRAFFFTGVFSAGAGAAGAAGAVSDMLKASVSESNSSRKQRHWPGL
5. GWL_KEPLGCVGLLSSWPKELSTFSWLPPSLAWLPWAWRSLV_PPWV_LLWPSLGSWAPFLAWLLSPFSGFSLFWLQQLQPASSPSLGSSWRSSWGWPPPSPSWASSPLLLASWPWPRLPF_P_AWLPQRPPSC_V_RNPTRRCPWSAPGCPCSPGS_DPA_CGCCSSPRHSQRLPALS_ERPKIRRCAPWRRQQL___ARTPGAQTLCAWPHLQTCGPSSSRESSRQGPEQRARQAQSRTC_RQA_ARAIRAGSRGTGRDS
6. GGSEKSLWVVLGF_AVGQRNFLLFLGCRLLWLGCLGLGGLWFSRLGFNCFGLRWALGRLFWLGCFRLFRAFRFFGSSSCSRLLRLLWGLLGALLGGGRPRRLLGLLRRSCWLLGLGRACLFSLRLGFPRGRLLVEFEGTRRAGALGLHQGALAHQALETQLDAAVVLLHVIASGCQRFLESGQRYAAALLGGGNSFSNELGHRGPRRFALGRTCRLAGLLLHGSLLGRGRSSGRGRRSLGHVEGKREREQFEPEAEALAGT
All possible proteins:
1. MSETAPAAPAAPAPAEKTPVKKKARKSAGAAKRKASGPPVSELITKAVAASKERSGVSLAALKKALAAAGYDVEKNNSRIKLGLKSLVSKGTLVQTKGTGASGSFKLNKKAASGEAKPKAKKAGAAKAKKPAGAAKKPKKATGAATPKKSAKKTPKKAKKPAAAAGAKKAKSPKKAKAAKPKKAPKSPAKAKAVKPKAAKPKTAKPKAAKPKKAAAKKK: 21833.993 Da
2. MTWRRTTAASSWVSRAW: 2034.001 Da
3. MRLLFFSTS: 1082.558 Da
================================================
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T21:49:23.863",
"Id": "480266",
"Score": "1",
"body": "My previous recommendations? Do those :) https://codereview.stackexchange.com/a/244149/25834"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T21:54:23.633",
"Id": "480268",
"Score": "0",
"body": "@Reinderien I believe I implemented most of them thank you!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T20:31:47.617",
"Id": "244636",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"regex",
"bioinformatics"
],
"Title": "Genetic sequence analyzer that reads FASTA and GenBank file formats and outputs all possible gene products"
}
|
244636
|
<p>I've put together my first table using Qt's QTableView and a custom data model. Currently, some data is populated on initialisation, and the user has the option of adding and deleting entries.</p>
<pre><code>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>
using namespace std;
QList<Contact> contacts;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QList<QString> contactNames;
QList<QString> contactPhoneNums;
contacts.append(Contact{4,"Adam"});
contacts.append(Contact{5,"James"});
contacts.append(Contact{2,"Emily"});
contacts.append(Contact{1,"Mark"});
// Create model:
PhoneBookModel = new TestModel(this);
// Connect model to table view:
ui->tableView->setModel(PhoneBookModel);
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableView->setSelectionMode( QAbstractItemView::SingleSelection );
// Make table header visible and display table:
ui->tableView->horizontalHeader()->setVisible(true);
ui->tableView->show();
//slots to signals
connect(ui->tableView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::foo);
}
void MainWindow::foo(){
QItemSelectionModel *selected = ui->tableView->selectionModel();
QModelIndexList rowList = selected->selectedRows();
if (rowList.size() == 0){
ui->label->setText("YAY");
ui->tableView->selectRow(0);
} else {
ui->label->setText(contacts.at(rowList.at(0).row()).name);
}
}
MainWindow::~MainWindow()
{
delete ui;
}
TestModel::TestModel(QObject *parent) : QAbstractTableModel(parent)
{
}
int TestModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return contacts.length();
}
int TestModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 2;
}
QVariant TestModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || role != Qt::DisplayRole) {
return QVariant();
}
if (index.column() == 0) {
return contacts[index.row()].id;
} else if (index.column() == 1) {
return contacts[index.row()].name;
}
return QVariant();
}
void TestModel::update(int row){
QModelIndex i = this->index(row,0,QModelIndex());
QModelIndex p = this->index(row,1,QModelIndex());
emit dataChanged(i,p);
emit layoutChanged();
}
QVariant TestModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {
if (section == 0) {
return QString("Name");
} else if (section == 1) {
return QString("Phone");
}
}
return QVariant();
}
void MainWindow::on_DeleteButton_clicked()
{
QItemSelectionModel *selected = ui->tableView->selectionModel();
QModelIndexList rowList = selected->selectedRows();
for (int i = 0; i < rowList.count(); i++)
{
contacts.removeAt(rowList.at(i).row());
if (rowList.at(i).row() == contacts.size()){ //last element
ui->tableView->selectRow(rowList.at(i).row()-1);
} else {
}
PhoneBookModel->update(rowList.at(i).row());
foo();
}
}
void MainWindow::on_AddButton_clicked()
{
int id = ui->id->text().toInt();
QString name = ui->name->text();
contacts.append(Contact{id,name});
PhoneBookModel->update(contacts.size()-1);
}
</code></pre>
<p>It all works fine, although I worry that I may be using QTableView incorrectly and/or inefficiently. Any suggestions on how to improve my code while maintaining the same functionality would be appreciated.</p>
|
[] |
[
{
"body": "<p>I can't find anything wrong.If really give some suggestions, it would be the case of the function name 'on_AddButton_clicked' and 'on_DeleteButton_clicked'.It will be better to use 'addButton' and 'deleteButton'.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-23T22:21:04.793",
"Id": "483146",
"Score": "0",
"body": "_It will be better to use 'addButton' and 'deleteButton'_ No it would not, cause it would break the automatic signal connection."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-22T13:16:31.327",
"Id": "245871",
"ParentId": "244637",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T21:45:50.677",
"Id": "244637",
"Score": "2",
"Tags": [
"c++",
"gui",
"qt"
],
"Title": "QTableView implementation"
}
|
244637
|
<p>I have this C# method which get the character and its count which has highest occurrence</p>
<pre><code> public KeyValuePair<char, int> CountCharMax_Dictionary_LINQ(string s)
{
char[] chars = s.ToCharArray();
var result = chars.GroupBy(x => x)
.OrderByDescending(x => x.Count())
.ToDictionary(x => x.Key, x => x.Count())
.FirstOrDefault();
return result;
}
</code></pre>
<p>It works but is there any better or efficient way to get the same result? Is there any difference if I return it as Tuple vs KeyValuePair?</p>
<p>Test data:</p>
<ul>
<li>Input: 122. Expected Output: 2,1</li>
<li>Input: 122111. Expected Output: 1,4</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T23:37:05.593",
"Id": "480272",
"Score": "2",
"body": "The expected output for input \"122\" should be \"2, 2\", not \"2, 1\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T00:09:16.160",
"Id": "480273",
"Score": "0",
"body": "Ops yeah. Indeed."
}
] |
[
{
"body": "<p>As per <a href=\"https://stackoverflow.com/a/19522559/3312\">this answer</a>, it would be wiser to use a tuple in this case. I use lowercase "t"uple as I highly recommend the built-in language support for tuples <code>(char, int)</code> over the explicit <code>Tuple<T1, T2></code> declaration, etc. Few more points:</p>\n<ul>\n<li>What should happen in a tie? Which gets returned? If any is acceptable, it's fine as-is. To be more of a determinate function, secondarily order by the character itself.</li>\n<li>Don't need to convert it to a character array as a string already <em>is</em> a character array.</li>\n<li>Re-order the <code>OrderByDescending</code> and the <code>Select</code> so that <code>Count</code> only has to be called once.</li>\n<li>It can be made <code>static</code> since it doesn't access class instance data.</li>\n<li>It can be made an extension method if in a <code>static</code> class.</li>\n<li>It can be made into an expression-bodied method.</li>\n<li>Maybe consider a better name; one that confers what it does rather than how it does it.</li>\n</ul>\n<p>All that said, here's my take:</p>\n<pre><code> public static (char, int) MaxCharacterFrequency(this string s) =>\n s.GroupBy(x => x)\n .Select(x => (x.Key, x.Count()))\n .OrderByDescending(x => x.Item2)\n .ThenBy(x => x.Item1)\n .FirstOrDefault();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T00:38:38.283",
"Id": "480274",
"Score": "0",
"body": "`It can be made static since it doesn't access class instance data.` If the method doesn't access to class instance data, with static, it is safer and use less memory?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T15:52:47.073",
"Id": "480330",
"Score": "0",
"body": "I would say that objectively it does use less memory for two reasons: 1. The class instance is not required to be created and 2. The implicit `this` parameter is not passed to the method. It's not anything substantial, but it's more of an idiomatic correctness to do so."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T23:29:43.847",
"Id": "244640",
"ParentId": "244638",
"Score": "7"
}
},
{
"body": "<p>There is not much to add to Slicers answer other than underscore in names is rather un-C#-ish, and you should avoid single character names (<code>s</code>) as well.</p>\n<p>You ask for more efficient ways for the algorithm. One could be the following:</p>\n<pre><code>public (char value, int count) MaxByFrequency(string input)\n{\n var chars = input.ToCharArray();\n Array.Sort(chars);\n char value = ' ';\n int max = 0;\n\n for (int i = 0; i < chars.Length; )\n {\n int j = i;\n char ch = chars[j];\n while (j < chars.Length && chars[j] == ch) j++;\n\n if (j - i > max)\n {\n max = j - i;\n value = ch;\n }\n\n i = j;\n }\n\n return (value, max);\n}\n</code></pre>\n<p>It is efficient time wise (in my measures more than twice as fast) but of cause is rather "expensive" in memory usage because of the temporary array of chars.</p>\n<hr />\n<p>Another linq approach using <code>Aggregate</code> could be:</p>\n<pre><code>public (char value, int count) MaxByFrequency(string input)\n{\n (char value, int count) seed = (' ', 0);\n return input\n .GroupBy(c => c)\n .Aggregate(seed, (acc, gr) =>\n {\n int cnt = gr.Count();\n if (cnt > acc.count)\n return (gr.Key, cnt);\n return acc;\n });\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T19:22:41.627",
"Id": "244675",
"ParentId": "244638",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244640",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T22:14:50.083",
"Id": "244638",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Get the character and its count which has highest occurrence"
}
|
244638
|
<p>This is a follow-up question to <a href="https://codereview.stackexchange.com/questions/243831/c-simple-hashcons-data-structure">my previous question</a></p>
<p>I have modified the code according to the feedback I got from <a href="https://codereview.stackexchange.com/questions/243831/c-simple-hashcons-data-structure">here</a> and my Professor. However, my Professor is still not happy with the final code. More specifically he is not a fan searching once to see if the item exists in the table and searching for the second time to insert the item. I am wondering how can I solve this problem or rewrite the code to be more efficient.</p>
<p><code>hashcons.h</code></p>
<pre><code>#ifndef HASHCONS_H
#define HASHCONS_H
#include <stddef.h>
#include <stdbool.h>
typedef int (*Hash_Cons_Hash)(void *);
typedef bool (*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 hashcons table
*/
void *hash_cons_get(void *temp_item, size_t temp_size, HASH_CONS_TABLE table);
#endif
</code></pre>
<p><code>hashcons.c</code></p>
<pre><code>#include <stdlib.h>
#include <string.h>
#include "prime.h"
#include "hashcons.h"
#define HC_INITIAL_BASE_SIZE 61
#define MAX_DENSITY 0.5
/**
* Initializes a table
* @param hc table
* @param capacity new capacity
*/
void hc_initialize(HASH_CONS_TABLE hc, const int capacity) {
hc->capacity = capacity;
hc->table = calloc(hc->capacity, sizeof(void *));
hc->size = 0;
}
/**
* Finds the candidate index intended to get inserted or searched in table
* @param hc table
* @param item the item looking to be added or removed
* @param insert_mode true indicates insert false indicates search
* @return
*/
static int hc_candidate_index(HASH_CONS_TABLE hc, void *item, bool insert_mode) {
int attempt = 0;
int hash = hc->hashf(item);
int index = hash % hc->capacity;
int step_size = 0;
while (attempt++ < hc->capacity) {
if (insert_mode && hc->table[index] == NULL) {
return index;
} else if (!insert_mode && hc->equalf(hc->table[index], item)) {
return index;
}
if (attempt == 0) {
step_size = hash % (hc->capacity - 2);
}
index = (index + step_size) % hc->capacity;
}
return -1;
}
/**
* Insert an item into table
* @param hc table
* @param item the item intended to get inserted into the table
*/
static void hc_insert(HASH_CONS_TABLE hc, void *item) {
int index = hc_candidate_index(hc, item, true);
hc->table[index] = item;
hc->size++;
}
/**
* Search an item in table
* @param hc table
* @param item the item intended to get searched in the table
* @return the item or null
*/
static void *hc_search(HASH_CONS_TABLE hc, void *item) {
int index = hc_candidate_index(hc, item, false);
return index == -1 ? NULL : hc->table[index];
}
static void hc_resize(HASH_CONS_TABLE hc, const int capacity) {
void **old_table = hc->table;
int old_capacity = hc->capacity;
hc_initialize(hc, capacity);
for (int i = 0; i < old_capacity; i++) {
void *item = old_table[i];
if (item != NULL) {
hc_insert(hc, item);
}
}
free(old_table);
}
/**
* Insert an item into table if item is not already in table or just returns the existing item
* @param item the item
* @param temp_size item size
* @param hc table
* @return item just got inserted into the table or existing item
*/
void *hash_cons_get(void *item, size_t temp_size, HASH_CONS_TABLE hc) {
void *result;
if (hc->table == NULL) {
hc_initialize(hc, HC_INITIAL_BASE_SIZE);
}
if (hc->size > hc->capacity * MAX_DENSITY) {
const int new_capacity = next_twin_prime((hc->capacity << 1) + 1);
hc_resize(hc, new_capacity);
}
if ((result = hc_search(hc, item)) != NULL) {
return result;
} else {
result = malloc(temp_size);
memcpy(result, item, temp_size);
hc_insert(hc, result);
return result;
}
}
</code></pre>
<p>prime.h</p>
<pre><code>#ifndef PRIME_H
#define PRIME_H
int next_twin_prime(int x);
#endif
</code></pre>
<p>prime.c</p>
<pre><code>#include "prime.h"
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define INITIAL_TABLE_SIZE 9973
struct PrimesTable {
int size;
bool *table;
};
struct PrimesTable primesTable = {0, 0};
/**
* Create a boolean array "prime[0..n]" and initialize
* all entries it as true. A value in prime[i] will
* finally be false if i is Not a prime, else true.
*/
void initialize_sieve_of_eratosthenes(int n) {
if (primesTable.table == NULL) {
primesTable.size = n;
primesTable.table = malloc(n * sizeof(bool));
memset(primesTable.table, true, primesTable.size);
} else {
int original_size = primesTable.size;
bool *original_table = primesTable.table;
primesTable.size = n;
primesTable.table = malloc(n * sizeof(bool));
memset(primesTable.table, true, primesTable.size);
memcpy(primesTable.table, original_table, original_size * sizeof(bool));
free(original_table);
}
for (int p = 2; p * p < n; p++) {
// If primes[p] is not changed, then it is a prime
if (primesTable.table[p] == true) {
// Update all multiples of p
for (int i = p * 2; i <= n; i += p) primesTable.table[i] = false;
}
}
}
/**
* Return the next prime greater than parameter such that -2 is also a prime
*/
int next_twin_prime(int x) {
if (primesTable.table == 0) {
initialize_sieve_of_eratosthenes(INITIAL_TABLE_SIZE);
}
int i;
for (i = x + 1; i < primesTable.size; i++) {
if (primesTable.table[i] && primesTable.table[i - 2]) return i;
}
initialize_sieve_of_eratosthenes((primesTable.size << 1) + 1);
return next_twin_prime(x);
}
</code></pre>
<p><a href="https://github.com/amir734jj/hashcons/tree/ba50c155420293816bf86ea8f33b3ef45b5266c3" rel="nofollow noreferrer">Repository URL</a></p>
<p><strong>Added by Reviewer</strong></p>
<p>common.h</p>
<pre><code>#ifndef COMMON_H
#define COMMON_H
#define TRUE 1
#define FALSE 0
#endif
</code></pre>
<p>test.h</p>
<pre><code>#ifndef TEST_h
#define TEST_h
void test_integer_table();
#endif
</code></pre>
<p>test.c</p>
<pre><code>#include "stdlib.h"
#include "stdio.h"
#include "stdbool.h"
#include "hashcons.h"
long hash_integer(void *p) {
return *((int *) p);
}
bool equals_integer(void *p1, void *p2) {
if (p1 == NULL || p2 == NULL) {
return false;
}
int *i1 = (int *) p1;
int *i2 = (int *) p2;
return *i1 == *i2;
}
static struct hash_cons_table integer_table = {
0, 0, 0,
&hash_integer,
&equals_integer
};
int *new_integer(int n) {
return hash_cons_get(&n, sizeof(int), &integer_table);
}
void assertTrue(const char *message, bool b) {
if (!b) {
fprintf(stderr, "Assertion failed: %s\n", message);
exit(1);
}
}
void test_integer_table() {
int *i3 = new_integer(3);
assertTrue("initial i3", *i3 == 3);
int *i8 = new_integer(8);
assertTrue("initial i8", *i8 == 8);
assertTrue("later i3", *i3 == 3);
for (int i = 0; i < 100; ++i) {
char buffer[256];
sprintf(buffer, "integer for %d", i);
assertTrue(buffer, *new_integer(i) == i);
}
}
</code></pre>
<p>main.c</p>
<pre><code>#include "common.h"
#include "hashcons.h"
#include <stdio.h>
#include <stdlib.h>
#include "test.h"
typedef struct dummy {
int key;
} *DUMMY;
long hash(void *item) {
return 13 * ((DUMMY) item)->key + 17;
}
int equal(void *item1, void *item2) {
if (item1 == NULL || item2 == NULL) {
return FALSE;
}
return ((DUMMY) item1)->key == ((DUMMY) item2)->key;
}
DUMMY create_dummy(int key) {
DUMMY dummy = malloc(sizeof(dummy));
dummy->key = key;
return dummy;
}
static int test_adding_items(HASH_CONS_TABLE hc, int test_sample)
{
printf("starting to add stuff\n");
int failure_count = 0;
for (int i = 0; i < test_sample; i++) {
void *item = create_dummy(i);
if (!hash_cons_get(item, sizeof(struct dummy), hc))
{
failure_count++;
}
}
printf("finished adding stuff\n");
return failure_count;
}
static int test_getting_times(HASH_CONS_TABLE hc, int test_sample)
{
printf("starting to get stuff\n");
int failure_count = 0;
for (size_t i = 0; i < test_sample; i++) {
void *item = create_dummy(i);
if (hash_cons_get(item, sizeof(struct dummy), hc) == NULL)
{
failure_count++;
printf("Item %d not found\n", i);
}
}
printf("finished getting stuff\n");
return failure_count;
}
int main() {
HASH_CONS_TABLE hc = malloc(sizeof(struct hash_cons_table));
hc->hashf = hash;
hc->equalf = equal;
hc->size = 0;
int count = 300;
printf("starting to add stuff\n");
int i;
for (i = 0; i < count; i++) {
void *item = create_dummy(i);
hash_cons_get(item, sizeof(struct dummy), hc);
}
printf("finished adding stuff\n");
printf("starting to get stuff\n");
for (i = 0; i < count; i++) {
void *item = create_dummy(i);
if (hash_cons_get(item, sizeof(struct dummy), hc) == NULL)
{
printf("Item %d not found\n", i);
}
}
printf("finished getting stuff\n");
printf("Done!");
test_integer_table();
test_adding_items(hc, 100);
test_getting_times(hc, 100);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>General Observations</strong><br />\nThe code has improved from the last version quite a bit. It now utilizes a more common algorithm for getting primes and this new algorithm should perform better. The code in hashcons.c is less complex and most or all of any possible bugs have been removed (thank you for removing the possible recursion).</p>\n<p>I have taken the liberty of adding the files that were not included in both reviews from the repository. You can delete this if you like, but I am reviewing them.</p>\n<p>Upate the repository readme file with the explanation of what a hashcons is that I had in my original review, as well as an explanation of what hashcons.c and prime.c do.</p>\n<p>The most major area for improvement is memory allocation in C The 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><strong>Test for Possible Memory Allocation Errors</strong><br />\nI addressed this in the first review, however, I will address it again because it is very important.</p>\n<p>In modern high level languages such as C++, memory allocation errors throw an exception that the programmer can catch. This is not the case in the C programming language. As the code is now, if this code was used in software to control an airplane during flight <strong>I would not get on that airplane</strong>, there is inherent <code>Unknown Behavior</code> (UB) in how <code>malloc()</code> and <code>calloc()</code> are used in the code, this is especially true if the code is working in a limited memory application such as embedded control systems. The failure of memory allocation in C on regular computers is less of an issue since there is a lot of memory, but in limited environments this is still important.</p>\n<p>Here is the code I am talking about:</p>\n<p>In main.c:</p>\n<pre><code>int main() {\n HASH_CONS_TABLE hc = malloc(sizeof(struct hash_cons_table));\n hc->hashf = hash;\n hc->equalf = equal;\n hc->size = 0;\n\nDUMMY create_dummy(int key) {\n DUMMY dummy = malloc(sizeof(dummy));\n dummy->key = key;\n return dummy;\n}\n</code></pre>\n<p>In hashcons.c</p>\n<pre><code>void hc_initialize(HASH_CONS_TABLE hc, const int capacity) {\n hc->capacity = capacity;\n hc->table = calloc(hc->capacity, sizeof(*hc->table));\n hc->size = 0;\n}\n</code></pre>\n<p>In prime.c</p>\n<pre><code>void initialize_sieve_of_eratosthenes(int n) {\n if (primesTable.table == NULL) {\n primesTable.size = n;\n primesTable.table = malloc(n * sizeof(bool));\n memset(primesTable.table, true, primesTable.size);\n } else {\n int original_size = primesTable.size;\n bool *original_table = primesTable.table;\n\n primesTable.size = n;\n primesTable.table = malloc(n * sizeof(bool));\n memset(primesTable.table, true, primesTable.size);\n memcpy(primesTable.table, original_table, original_size * sizeof(bool));\n free(original_table);\n }\n</code></pre>\n<p>Each call of <code>malloc()</code> or <code>calloc()</code> should be followed by a test to see if the pointer is <code>NULL</code> to prevent accessing the address <code>0</code>, this will prevent UB.</p>\n<p>Examples:</p>\n<pre><code>int main() {\n HASH_CONS_TABLE hc = malloc(sizeof(struct hash_cons_table));\n if (hc == NULL)\n {\n fprintf(stderr, "Memory Allocation of HASH_CONS_TABLE hc error in main().\\nExiting Program.");\n return(EXIT_FAILURE);\n }\n hc->hashf = hash;\n hc->equalf = equal;\n hc->size = 0;\n\nDUMMY create_dummy(int key) {\n DUMMY dummy = malloc(sizeof(dummy));\n if (dummy == NULL)\n {\n fprintf(stderr, "Memory Allocation error in create_dummy().\\nExiting Program.");\n exit(EXIT_FAILURE);\n }\n dummy->key = key;\n return dummy;\n}\n\nvoid initialize_sieve_of_eratosthenes(int n) {\n if (primesTable.table == NULL) {\n primesTable.size = n;\n primesTable.table = malloc(n * sizeof(bool));\n if (primesTable.table == NULL)\n {\n fprintf(stderr, "Memory Allocation of primesTable.table error in initialize_sieve_of_eratosthenes().\\nExiting Program.");\n exit(EXIT_FAILURE);\n }\n memset(primesTable.table, true, primesTable.size);\n } else {\n int original_size = primesTable.size;\n bool *original_table = primesTable.table;\n\n primesTable.size = n;\n primesTable.table = malloc(n * sizeof(bool));\n if (primesTable.table == NULL)\n {\n fprintf(stderr, "Memory Allocation of primesTable.table error in initialize_sieve_of_eratosthenes().\\nExiting Program.");\n exit(EXIT_FAILURE);\n }\n memset(primesTable.table, true, primesTable.size);\n memcpy(primesTable.table, original_table, original_size * sizeof(bool));\n free(original_table);\n }\n</code></pre>\n<p><strong>Convention When Using Memory Allocation in C</strong><br />\nWhen using <code>malloc()</code>, <code>calloc()</code> or <code>realloc()</code> in C a common convetion is to <code>sizeof(*PTR)</code> rather <code>sizeof(PTR_TYPE)</code>, this make the code easier to maintain and less error prone, since less editing is required if the type of the pointer changes.</p>\n<p>Example:</p>\n<pre><code>int main() {\n HASH_CONS_TABLE hc = malloc(sizeof(*hc)); // << What the pointer points to rather than sizeof struct.\n if (hc == NULL)\n {\n fprintf(stderr, "Memory Allocation of HASH_CONS_TABLE hc error in main().\\nExiting Program.");\n return(EXIT_FAILURE);\n }\n hc->hashf = hash;\n hc->equalf = equal;\n hc->size = 0;\n</code></pre>\n<p><strong>Improve Testing</strong><br />\nMove all the testing functions into test.c, and provide interfaces for them, you might also want to consider moving the DUMMY test struct to test.c as well.</p>\n<p>Make an overall test function in test.c and test.h that will test everything, have it call the current test functions.</p>\n<p>Increase the test sample size to stress test the hashcons algorithm and the prime algorithm.</p>\n<p>Take the overall start and end time of the functions to get an average value of the time insertion takes (you may not need this if you profile the code).</p>\n<p>Profile the current code and the original code to see if there is an improvement in insertion and search times.</p>\n<p><strong>Missing Edit in main.c</strong><br />\nWhile most of the program has been converted to use <code>stdbool.h</code>, <code>main.c</code> still includes <code>common.h</code> and uses FALSE rather than false in the function <code>equal()</code> which also returns <code>int</code> rather than <code>bool</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-02T13:12:11.757",
"Id": "480795",
"Score": "0",
"body": "@chux-ReinstateMonica thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T16:44:15.330",
"Id": "244727",
"ParentId": "244639",
"Score": "3"
}
},
{
"body": "<p><strong>Undefined behavior: Access outside array</strong></p>\n<p>Allocation is for <code>n</code> elements, yet code attempts to access 1 past <code>primesTable.table[n-1]</code></p>\n<pre><code>... malloc(n * sizeof(bool));\n...\nfor (int i = p * 2; i <= n; i += p) primesTable.table[i] = false;\n// ^\n</code></pre>\n<p><strong>Bug, wrong function type</strong></p>\n<p><code>hash()</code> returns <code>long</code> yet <code>.hashf</code> points to a function returning <code>int</code>.</p>\n<pre><code>long hash(void *item) {\n return 13 * ((DUMMY) item)->key + 17;\n}\n\ntypedef int (*Hash_Cons_Hash)(void *);\nHash_Cons_Hash hashf; \nhc->hashf = hash; \n</code></pre>\n<p><strong>Bug, signed integer overflow and negative indexes</strong></p>\n<p><code>13 * ((DUMMY) item)->key</code> itself can signed integer overflow resulting in UB. Possible for <code>hash()</code> to return a negative value which cascades into UB in array indexing.</p>\n<p>Performing an <code>int * int + int</code> and assigning that to <code>long</code> does not provide for a wider product when <code>long</code> wider than <code>int</code>.</p>\n<pre><code>long hash(void *item) {\n return 13 * ((DUMMY) item)->key + 17; // problem code\n}\n</code></pre>\n<p><code>hash % hc->capacity</code> does not help as the result is signed: [-(hc->capacity-1) ... +(hc->capacity-1)].</p>\n<pre><code>int index = hash % hc->capacity;\n</code></pre>\n<p>I recommend to return an unsigned type like <code>size_t</code> from the hash function, then apply an <em>unsigned</em> <code>% hc->capacity</code>, such as</p>\n<pre><code>size_t hashu(const void *item) {\n return (size_t)8191 * ((DUMMY) item)->key + 17;\n}\n</code></pre>\n<p><strong>Bug <code>int</code> overflow</strong></p>\n<p>When <code>int n</code> is a prime near <code>INT_MAX</code>, <code>p * p</code> overflows. UB and potential infinite loop.</p>\n<pre><code>for (int p = 2; p * p < n; p++) {\n</code></pre>\n<p>Safe alternate</p>\n<pre><code>for (int p = 2; p < n/p; p++) {\n</code></pre>\n<p>Further, I expect <code><=</code> is needed</p>\n<pre><code>for (int p = 2; p <= n/p; p++) {\n</code></pre>\n<p><strong>On the edge of a bug: <code>bool</code> initialization</strong></p>\n<p>When <code>sizeof(bool) > 1</code>, like <code>sizeof(int)</code>, <code>memset(primesTable.table, true, primesTable.size);</code> sets each <code>bool</code> object to 0x01010101. On reading <code>table[i]</code>, that non-zero value is <em>true</em>, yet may look strange in debugging as <code>0x00000001</code> might be expected.</p>\n<p>For me, I would reverse the table flags and initialize with <code>memset(primesTable.table, false, primesTable.size);</code> or better yet, use an <code>unsigned char</code> array and then initialize either way.</p>\n<p><strong>Simplify allocation</strong></p>\n<p>Allocate to the size of the referenced data, not the type. Easier to code right, review and maintain.</p>\n<pre><code>// primesTable.table = malloc(n * sizeof(bool));\nprimesTable.table = malloc(sizeof primesTable.table[0] * (n + 1u));\n// I also think OP needs a + 1 to prevent UB ^^^^ \n</code></pre>\n<p><strong>Do not hide pointers</strong></p>\n<p>There are times to hide, but not here.</p>\n<pre><code>//typedef struct dummy {\n// int key;\n//} *DUMMY;\nstruct dummy {\n int key;\n};\n// or if you are trying to abstract the struct\ntypedef struct {\n int key;\n} dummy;\n</code></pre>\n<p><strong>include test</strong></p>\n<p>In general, list <code><></code> first. then <code>""</code>, <em>except</em> for the corresponding <code>.h</code>. This helps test that <code>hashcons.h</code> indeed can get called without prior includes.</p>\n<p>In <code>"hashcons.c"</code></p>\n<pre><code>#include "hashcons.h"\n#include <stdlib.h>\n#include <string.h>\n#include "prime.h"\n// #include "hashcons.h" move to first\n</code></pre>\n<p><strong>Naming</strong></p>\n<p><code>hashcons.h</code> defines <code>HASH_CONS_...</code> and <code>hash_cons_...</code>. I recommend to use a <code>_</code> in the filename or drop <code>_</code> from the functions names.</p>\n<p><strong><code>bool</code> size</strong></p>\n<p><code>bool</code> may be the size of an <code>int</code>, or <code>char</code>, or ...</p>\n<p>For space savings of a large <code>bool</code> array, consider <code>unsigned char</code> for the array which is defined as size 1. This might be a smidge slower, but IMO worth the potential space reduction.</p>\n<pre><code>// bool *table;\nunsigned char *table;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T23:53:05.853",
"Id": "244861",
"ParentId": "244639",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244727",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T22:20:56.867",
"Id": "244639",
"Score": "5",
"Tags": [
"c",
"homework"
],
"Title": "Follow up to \"C simple hashcons data structure\""
}
|
244639
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.